From 0500502826c3ea0bd26966ac470ba1be0ecae71f Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 1 Jun 2022 03:48:39 +0000 Subject: [PATCH 01/11] feat: allow users to disable spell check in search requests feat: allow users to add labels in search requests docs: deprecate indexable/searchable on the product level custom attributes docs: keep the API doc up-to-date with recent changes PiperOrigin-RevId: 452193046 Source-Link: https://github.com/googleapis/googleapis/commit/4e0282f92e4e581b79062063488bf62fa837a905 Source-Link: https://github.com/googleapis/googleapis-gen/commit/3fa3c84e3da8c8e604e129c141367dd0926878f3 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiM2ZhM2M4NGUzZGE4YzhlNjA0ZTEyOWMxNDEzNjdkZDA5MjY4NzhmMyJ9 --- owl-bot-staging/v2/.coveragerc | 17 + owl-bot-staging/v2/.flake8 | 33 + owl-bot-staging/v2/MANIFEST.in | 2 + owl-bot-staging/v2/README.rst | 49 + owl-bot-staging/v2/docs/conf.py | 376 + owl-bot-staging/v2/docs/index.rst | 7 + .../v2/docs/retail_v2/catalog_service.rst | 10 + .../v2/docs/retail_v2/completion_service.rst | 6 + .../v2/docs/retail_v2/prediction_service.rst | 6 + .../v2/docs/retail_v2/product_service.rst | 10 + .../v2/docs/retail_v2/search_service.rst | 10 + .../v2/docs/retail_v2/services.rst | 11 + owl-bot-staging/v2/docs/retail_v2/types.rst | 7 + .../v2/docs/retail_v2/user_event_service.rst | 6 + .../v2/google/cloud/retail/__init__.py | 193 + .../v2/google/cloud/retail/py.typed | 2 + .../v2/google/cloud/retail_v2/__init__.py | 194 + .../cloud/retail_v2/gapic_metadata.json | 333 + .../v2/google/cloud/retail_v2/py.typed | 2 + .../cloud/retail_v2/services/__init__.py | 15 + .../services/catalog_service/__init__.py | 22 + .../services/catalog_service/async_client.py | 653 ++ .../services/catalog_service/client.py | 861 ++ .../services/catalog_service/pagers.py | 140 + .../catalog_service/transports/__init__.py | 33 + .../catalog_service/transports/base.py | 194 + .../catalog_service/transports/grpc.py | 379 + .../transports/grpc_asyncio.py | 378 + .../services/completion_service/__init__.py | 22 + .../completion_service/async_client.py | 391 + .../services/completion_service/client.py | 592 ++ .../completion_service/transports/__init__.py | 33 + .../completion_service/transports/base.py | 172 + .../completion_service/transports/grpc.py | 323 + .../transports/grpc_asyncio.py | 322 + .../services/prediction_service/__init__.py | 22 + .../prediction_service/async_client.py | 279 + .../services/prediction_service/client.py | 479 ++ .../prediction_service/transports/__init__.py | 33 + .../prediction_service/transports/base.py | 150 + .../prediction_service/transports/grpc.py | 262 + .../transports/grpc_asyncio.py | 261 + .../services/product_service/__init__.py | 22 + .../services/product_service/async_client.py | 1701 ++++ .../services/product_service/client.py | 1903 +++++ .../services/product_service/pagers.py | 140 + .../product_service/transports/__init__.py | 33 + .../product_service/transports/base.py | 308 + .../product_service/transports/grpc.py | 678 ++ .../transports/grpc_asyncio.py | 677 ++ .../services/search_service/__init__.py | 22 + .../services/search_service/async_client.py | 303 + .../services/search_service/client.py | 512 ++ .../services/search_service/pagers.py | 139 + .../search_service/transports/__init__.py | 33 + .../search_service/transports/base.py | 150 + .../search_service/transports/grpc.py | 268 + .../search_service/transports/grpc_asyncio.py | 267 + .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 730 ++ .../services/user_event_service/client.py | 929 +++ .../user_event_service/transports/__init__.py | 33 + .../user_event_service/transports/base.py | 231 + .../user_event_service/transports/grpc.py | 415 + .../transports/grpc_asyncio.py | 414 + .../google/cloud/retail_v2/types/__init__.py | 194 + .../google/cloud/retail_v2/types/catalog.py | 131 + .../cloud/retail_v2/types/catalog_service.py | 248 + .../v2/google/cloud/retail_v2/types/common.py | 736 ++ .../retail_v2/types/completion_service.py | 229 + .../cloud/retail_v2/types/import_config.py | 697 ++ .../retail_v2/types/prediction_service.py | 275 + .../google/cloud/retail_v2/types/product.py | 701 ++ .../cloud/retail_v2/types/product_service.py | 858 ++ .../google/cloud/retail_v2/types/promotion.py | 50 + .../cloud/retail_v2/types/purge_config.py | 107 + .../cloud/retail_v2/types/search_service.py | 1150 +++ .../cloud/retail_v2/types/user_event.py | 508 ++ .../retail_v2/types/user_event_service.py | 154 + owl-bot-staging/v2/mypy.ini | 3 + owl-bot-staging/v2/noxfile.py | 180 + ...atalog_service_get_default_branch_async.py | 44 + ...catalog_service_get_default_branch_sync.py | 44 + ...ted_catalog_service_list_catalogs_async.py | 46 + ...ated_catalog_service_list_catalogs_sync.py | 46 + ...atalog_service_set_default_branch_async.py | 42 + ...catalog_service_set_default_branch_sync.py | 42 + ...ed_catalog_service_update_catalog_async.py | 49 + ...ted_catalog_service_update_catalog_sync.py | 49 + ...completion_service_complete_query_async.py | 46 + ..._completion_service_complete_query_sync.py | 46 + ...on_service_import_completion_data_async.py | 54 + ...ion_service_import_completion_data_sync.py | 54 + ...erated_prediction_service_predict_async.py | 50 + ...nerated_prediction_service_predict_sync.py | 50 + ...ct_service_add_fulfillment_places_async.py | 51 + ...uct_service_add_fulfillment_places_sync.py | 51 + ...uct_service_add_local_inventories_async.py | 49 + ...duct_service_add_local_inventories_sync.py | 49 + ...ed_product_service_create_product_async.py | 50 + ...ted_product_service_create_product_sync.py | 50 + ...ed_product_service_delete_product_async.py | 43 + ...ted_product_service_delete_product_sync.py | 43 + ...rated_product_service_get_product_async.py | 45 + ...erated_product_service_get_product_sync.py | 45 + ...d_product_service_import_products_async.py | 53 + ...ed_product_service_import_products_sync.py | 53 + ...ted_product_service_list_products_async.py | 46 + ...ated_product_service_list_products_sync.py | 46 + ...service_remove_fulfillment_places_async.py | 51 + ..._service_remove_fulfillment_places_sync.py | 51 + ..._service_remove_local_inventories_async.py | 50 + ...t_service_remove_local_inventories_sync.py | 50 + ...ted_product_service_set_inventory_async.py | 52 + ...ated_product_service_set_inventory_sync.py | 52 + ...ed_product_service_update_product_async.py | 48 + ...ted_product_service_update_product_sync.py | 48 + ...2_generated_search_service_search_async.py | 47 + ...v2_generated_search_service_search_sync.py | 47 + ..._event_service_collect_user_event_async.py | 46 + ...r_event_service_collect_user_event_sync.py | 46 + ..._event_service_import_user_events_async.py | 54 + ...r_event_service_import_user_events_sync.py | 54 + ...r_event_service_purge_user_events_async.py | 50 + ...er_event_service_purge_user_events_sync.py | 50 + ..._event_service_rejoin_user_events_async.py | 49 + ...r_event_service_rejoin_user_events_sync.py | 49 + ...er_event_service_write_user_event_async.py | 50 + ...ser_event_service_write_user_event_sync.py | 50 + .../snippet_metadata_retail_v2.json | 3826 +++++++++ .../v2/scripts/fixup_retail_v2_keywords.py | 199 + owl-bot-staging/v2/setup.py | 59 + owl-bot-staging/v2/tests/__init__.py | 16 + owl-bot-staging/v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../v2/tests/unit/gapic/retail_v2/__init__.py | 16 + .../gapic/retail_v2/test_catalog_service.py | 2267 ++++++ .../retail_v2/test_completion_service.py | 1451 ++++ .../retail_v2/test_prediction_service.py | 1279 +++ .../gapic/retail_v2/test_product_service.py | 4085 ++++++++++ .../gapic/retail_v2/test_search_service.py | 1496 ++++ .../retail_v2/test_user_event_service.py | 1988 +++++ owl-bot-staging/v2alpha/.coveragerc | 17 + owl-bot-staging/v2alpha/.flake8 | 33 + owl-bot-staging/v2alpha/MANIFEST.in | 2 + owl-bot-staging/v2alpha/README.rst | 49 + owl-bot-staging/v2alpha/docs/conf.py | 376 + owl-bot-staging/v2alpha/docs/index.rst | 7 + .../docs/retail_v2alpha/catalog_service.rst | 10 + .../retail_v2alpha/completion_service.rst | 6 + .../docs/retail_v2alpha/control_service.rst | 10 + .../retail_v2alpha/prediction_service.rst | 6 + .../docs/retail_v2alpha/product_service.rst | 10 + .../docs/retail_v2alpha/search_service.rst | 10 + .../v2alpha/docs/retail_v2alpha/services.rst | 13 + .../retail_v2alpha/serving_config_service.rst | 10 + .../v2alpha/docs/retail_v2alpha/types.rst | 7 + .../retail_v2alpha/user_event_service.rst | 6 + .../v2alpha/google/cloud/retail/__init__.py | 281 + .../v2alpha/google/cloud/retail/py.typed | 2 + .../google/cloud/retail_v2alpha/__init__.py | 282 + .../cloud/retail_v2alpha/gapic_metadata.json | 561 ++ .../google/cloud/retail_v2alpha/py.typed | 2 + .../cloud/retail_v2alpha/services/__init__.py | 15 + .../services/catalog_service/__init__.py | 22 + .../services/catalog_service/async_client.py | 1352 ++++ .../services/catalog_service/client.py | 1581 ++++ .../services/catalog_service/pagers.py | 140 + .../catalog_service/transports/__init__.py | 33 + .../catalog_service/transports/base.py | 293 + .../catalog_service/transports/grpc.py | 598 ++ .../transports/grpc_asyncio.py | 597 ++ .../services/completion_service/__init__.py | 22 + .../completion_service/async_client.py | 391 + .../services/completion_service/client.py | 592 ++ .../completion_service/transports/__init__.py | 33 + .../completion_service/transports/base.py | 172 + .../completion_service/transports/grpc.py | 323 + .../transports/grpc_asyncio.py | 322 + .../services/control_service/__init__.py | 22 + .../services/control_service/async_client.py | 744 ++ .../services/control_service/client.py | 952 +++ .../services/control_service/pagers.py | 140 + .../control_service/transports/__init__.py | 33 + .../control_service/transports/base.py | 209 + .../control_service/transports/grpc.py | 380 + .../transports/grpc_asyncio.py | 379 + .../services/prediction_service/__init__.py | 22 + .../prediction_service/async_client.py | 279 + .../services/prediction_service/client.py | 479 ++ .../prediction_service/transports/__init__.py | 33 + .../prediction_service/transports/base.py | 150 + .../prediction_service/transports/grpc.py | 262 + .../transports/grpc_asyncio.py | 261 + .../services/product_service/__init__.py | 22 + .../services/product_service/async_client.py | 1804 +++++ .../services/product_service/client.py | 2007 +++++ .../services/product_service/pagers.py | 140 + .../product_service/transports/__init__.py | 33 + .../product_service/transports/base.py | 323 + .../product_service/transports/grpc.py | 724 ++ .../transports/grpc_asyncio.py | 723 ++ .../services/search_service/__init__.py | 22 + .../services/search_service/async_client.py | 303 + .../services/search_service/client.py | 512 ++ .../services/search_service/pagers.py | 139 + .../search_service/transports/__init__.py | 33 + .../search_service/transports/base.py | 150 + .../search_service/transports/grpc.py | 268 + .../search_service/transports/grpc_asyncio.py | 267 + .../serving_config_service/__init__.py | 22 + .../serving_config_service/async_client.py | 954 +++ .../services/serving_config_service/client.py | 1162 +++ .../services/serving_config_service/pagers.py | 140 + .../transports/__init__.py | 33 + .../serving_config_service/transports/base.py | 237 + .../serving_config_service/transports/grpc.py | 438 + .../transports/grpc_asyncio.py | 437 + .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 730 ++ .../services/user_event_service/client.py | 929 +++ .../user_event_service/transports/__init__.py | 33 + .../user_event_service/transports/base.py | 231 + .../user_event_service/transports/grpc.py | 415 + .../transports/grpc_asyncio.py | 414 + .../cloud/retail_v2alpha/types/__init__.py | 284 + .../cloud/retail_v2alpha/types/catalog.py | 528 ++ .../retail_v2alpha/types/catalog_service.py | 453 ++ .../cloud/retail_v2alpha/types/common.py | 1179 +++ .../types/completion_service.py | 223 + .../cloud/retail_v2alpha/types/control.py | 123 + .../retail_v2alpha/types/control_service.py | 197 + .../retail_v2alpha/types/export_config.py | 134 + .../retail_v2alpha/types/import_config.py | 691 ++ .../types/prediction_service.py | 263 + .../cloud/retail_v2alpha/types/product.py | 705 ++ .../retail_v2alpha/types/product_service.py | 877 ++ .../cloud/retail_v2alpha/types/promotion.py | 50 + .../retail_v2alpha/types/purge_config.py | 251 + .../retail_v2alpha/types/search_service.py | 1099 +++ .../retail_v2alpha/types/serving_config.py | 309 + .../types/serving_config_service.py | 234 + .../cloud/retail_v2alpha/types/user_event.py | 507 ++ .../types/user_event_service.py | 154 + owl-bot-staging/v2alpha/mypy.ini | 3 + owl-bot-staging/v2alpha/noxfile.py | 180 + ...log_service_add_catalog_attribute_async.py | 49 + ...alog_service_add_catalog_attribute_sync.py | 49 + ...log_service_get_attributes_config_async.py | 45 + ...alog_service_get_attributes_config_sync.py | 45 + ...log_service_get_completion_config_async.py | 45 + ...alog_service_get_completion_config_sync.py | 45 + ...atalog_service_get_default_branch_async.py | 44 + ...catalog_service_get_default_branch_sync.py | 44 + ...ted_catalog_service_list_catalogs_async.py | 46 + ...ated_catalog_service_list_catalogs_sync.py | 46 + ..._service_remove_catalog_attribute_async.py | 46 + ...g_service_remove_catalog_attribute_sync.py | 46 + ...service_replace_catalog_attribute_async.py | 49 + ..._service_replace_catalog_attribute_sync.py | 49 + ...atalog_service_set_default_branch_async.py | 42 + ...catalog_service_set_default_branch_sync.py | 42 + ..._service_update_attributes_config_async.py | 48 + ...g_service_update_attributes_config_sync.py | 48 + ...ed_catalog_service_update_catalog_async.py | 49 + ...ted_catalog_service_update_catalog_sync.py | 49 + ..._service_update_completion_config_async.py | 48 + ...g_service_update_completion_config_sync.py | 48 + ...completion_service_complete_query_async.py | 46 + ..._completion_service_complete_query_sync.py | 46 + ...on_service_import_completion_data_async.py | 54 + ...ion_service_import_completion_data_sync.py | 54 + ...ed_control_service_create_control_async.py | 53 + ...ted_control_service_create_control_sync.py | 53 + ...ed_control_service_delete_control_async.py | 43 + ...ted_control_service_delete_control_sync.py | 43 + ...rated_control_service_get_control_async.py | 45 + ...erated_control_service_get_control_sync.py | 45 + ...ted_control_service_list_controls_async.py | 46 + ...ated_control_service_list_controls_sync.py | 46 + ...ed_control_service_update_control_async.py | 51 + ...ted_control_service_update_control_sync.py | 51 + ...erated_prediction_service_predict_async.py | 50 + ...nerated_prediction_service_predict_sync.py | 50 + ...ct_service_add_fulfillment_places_async.py | 51 + ...uct_service_add_fulfillment_places_sync.py | 51 + ...uct_service_add_local_inventories_async.py | 49 + ...duct_service_add_local_inventories_sync.py | 49 + ...ed_product_service_create_product_async.py | 50 + ...ted_product_service_create_product_sync.py | 50 + ...ed_product_service_delete_product_async.py | 43 + ...ted_product_service_delete_product_sync.py | 43 + ...rated_product_service_get_product_async.py | 45 + ...erated_product_service_get_product_sync.py | 45 + ...d_product_service_import_products_async.py | 53 + ...ed_product_service_import_products_sync.py | 53 + ...ted_product_service_list_products_async.py | 46 + ...ated_product_service_list_products_sync.py | 46 + ...ed_product_service_purge_products_async.py | 50 + ...ted_product_service_purge_products_sync.py | 50 + ...service_remove_fulfillment_places_async.py | 51 + ..._service_remove_fulfillment_places_sync.py | 51 + ..._service_remove_local_inventories_async.py | 50 + ...t_service_remove_local_inventories_sync.py | 50 + ...ted_product_service_set_inventory_async.py | 52 + ...ated_product_service_set_inventory_sync.py | 52 + ...ed_product_service_update_product_async.py | 48 + ...ted_product_service_update_product_sync.py | 48 + ...a_generated_search_service_search_async.py | 47 + ...ha_generated_search_service_search_sync.py | 47 + ...erving_config_service_add_control_async.py | 46 + ...serving_config_service_add_control_sync.py | 46 + ...fig_service_create_serving_config_async.py | 51 + ...nfig_service_create_serving_config_sync.py | 51 + ...fig_service_delete_serving_config_async.py | 43 + ...nfig_service_delete_serving_config_sync.py | 43 + ...config_service_get_serving_config_async.py | 45 + ..._config_service_get_serving_config_sync.py | 45 + ...nfig_service_list_serving_configs_async.py | 46 + ...onfig_service_list_serving_configs_sync.py | 46 + ...ing_config_service_remove_control_async.py | 46 + ...ving_config_service_remove_control_sync.py | 46 + ...fig_service_update_serving_config_async.py | 49 + ...nfig_service_update_serving_config_sync.py | 49 + ..._event_service_collect_user_event_async.py | 46 + ...r_event_service_collect_user_event_sync.py | 46 + ..._event_service_import_user_events_async.py | 54 + ...r_event_service_import_user_events_sync.py | 54 + ...r_event_service_purge_user_events_async.py | 50 + ...er_event_service_purge_user_events_sync.py | 50 + ..._event_service_rejoin_user_events_async.py | 49 + ...r_event_service_rejoin_user_events_sync.py | 49 + ...er_event_service_write_user_event_async.py | 50 + ...ser_event_service_write_user_event_sync.py | 50 + .../snippet_metadata_retail_v2alpha.json | 7066 +++++++++++++++++ .../scripts/fixup_retail_v2alpha_keywords.py | 219 + owl-bot-staging/v2alpha/setup.py | 59 + owl-bot-staging/v2alpha/tests/__init__.py | 16 + .../v2alpha/tests/unit/__init__.py | 16 + .../v2alpha/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/retail_v2alpha/__init__.py | 16 + .../retail_v2alpha/test_catalog_service.py | 3793 +++++++++ .../retail_v2alpha/test_completion_service.py | 1451 ++++ .../retail_v2alpha/test_control_service.py | 2566 ++++++ .../retail_v2alpha/test_prediction_service.py | 1279 +++ .../retail_v2alpha/test_product_service.py | 4237 ++++++++++ .../retail_v2alpha/test_search_service.py | 1496 ++++ .../test_serving_config_service.py | 3279 ++++++++ .../retail_v2alpha/test_user_event_service.py | 1988 +++++ owl-bot-staging/v2beta/.coveragerc | 17 + owl-bot-staging/v2beta/.flake8 | 33 + owl-bot-staging/v2beta/MANIFEST.in | 2 + owl-bot-staging/v2beta/README.rst | 49 + owl-bot-staging/v2beta/docs/conf.py | 376 + owl-bot-staging/v2beta/docs/index.rst | 7 + .../docs/retail_v2beta/catalog_service.rst | 10 + .../docs/retail_v2beta/completion_service.rst | 6 + .../docs/retail_v2beta/control_service.rst | 10 + .../docs/retail_v2beta/prediction_service.rst | 6 + .../docs/retail_v2beta/product_service.rst | 10 + .../docs/retail_v2beta/search_service.rst | 10 + .../v2beta/docs/retail_v2beta/services.rst | 13 + .../retail_v2beta/serving_config_service.rst | 10 + .../v2beta/docs/retail_v2beta/types.rst | 7 + .../docs/retail_v2beta/user_event_service.rst | 6 + .../v2beta/google/cloud/retail/__init__.py | 275 + .../v2beta/google/cloud/retail/py.typed | 2 + .../google/cloud/retail_v2beta/__init__.py | 276 + .../cloud/retail_v2beta/gapic_metadata.json | 551 ++ .../google/cloud/retail_v2beta/py.typed | 2 + .../cloud/retail_v2beta/services/__init__.py | 15 + .../services/catalog_service/__init__.py | 22 + .../services/catalog_service/async_client.py | 1350 ++++ .../services/catalog_service/client.py | 1579 ++++ .../services/catalog_service/pagers.py | 140 + .../catalog_service/transports/__init__.py | 33 + .../catalog_service/transports/base.py | 293 + .../catalog_service/transports/grpc.py | 598 ++ .../transports/grpc_asyncio.py | 597 ++ .../services/completion_service/__init__.py | 22 + .../completion_service/async_client.py | 391 + .../services/completion_service/client.py | 592 ++ .../completion_service/transports/__init__.py | 33 + .../completion_service/transports/base.py | 172 + .../completion_service/transports/grpc.py | 323 + .../transports/grpc_asyncio.py | 322 + .../services/control_service/__init__.py | 22 + .../services/control_service/async_client.py | 742 ++ .../services/control_service/client.py | 950 +++ .../services/control_service/pagers.py | 140 + .../control_service/transports/__init__.py | 33 + .../control_service/transports/base.py | 209 + .../control_service/transports/grpc.py | 380 + .../transports/grpc_asyncio.py | 379 + .../services/prediction_service/__init__.py | 22 + .../prediction_service/async_client.py | 279 + .../services/prediction_service/client.py | 479 ++ .../prediction_service/transports/__init__.py | 33 + .../prediction_service/transports/base.py | 150 + .../prediction_service/transports/grpc.py | 262 + .../transports/grpc_asyncio.py | 261 + .../services/product_service/__init__.py | 22 + .../services/product_service/async_client.py | 1692 ++++ .../services/product_service/client.py | 1894 +++++ .../services/product_service/pagers.py | 140 + .../product_service/transports/__init__.py | 33 + .../product_service/transports/base.py | 308 + .../product_service/transports/grpc.py | 678 ++ .../transports/grpc_asyncio.py | 677 ++ .../services/search_service/__init__.py | 22 + .../services/search_service/async_client.py | 303 + .../services/search_service/client.py | 512 ++ .../services/search_service/pagers.py | 139 + .../search_service/transports/__init__.py | 33 + .../search_service/transports/base.py | 150 + .../search_service/transports/grpc.py | 268 + .../search_service/transports/grpc_asyncio.py | 267 + .../serving_config_service/__init__.py | 22 + .../serving_config_service/async_client.py | 954 +++ .../services/serving_config_service/client.py | 1162 +++ .../services/serving_config_service/pagers.py | 140 + .../transports/__init__.py | 33 + .../serving_config_service/transports/base.py | 237 + .../serving_config_service/transports/grpc.py | 438 + .../transports/grpc_asyncio.py | 437 + .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 730 ++ .../services/user_event_service/client.py | 929 +++ .../user_event_service/transports/__init__.py | 33 + .../user_event_service/transports/base.py | 231 + .../user_event_service/transports/grpc.py | 415 + .../transports/grpc_asyncio.py | 414 + .../cloud/retail_v2beta/types/__init__.py | 278 + .../cloud/retail_v2beta/types/catalog.py | 528 ++ .../retail_v2beta/types/catalog_service.py | 453 ++ .../cloud/retail_v2beta/types/common.py | 1178 +++ .../retail_v2beta/types/completion_service.py | 223 + .../cloud/retail_v2beta/types/control.py | 112 + .../retail_v2beta/types/control_service.py | 197 + .../retail_v2beta/types/export_config.py | 134 + .../retail_v2beta/types/import_config.py | 691 ++ .../retail_v2beta/types/prediction_service.py | 263 + .../cloud/retail_v2beta/types/product.py | 705 ++ .../retail_v2beta/types/product_service.py | 844 ++ .../cloud/retail_v2beta/types/promotion.py | 50 + .../cloud/retail_v2beta/types/purge_config.py | 107 + .../retail_v2beta/types/search_service.py | 1074 +++ .../retail_v2beta/types/serving_config.py | 309 + .../types/serving_config_service.py | 234 + .../cloud/retail_v2beta/types/user_event.py | 507 ++ .../retail_v2beta/types/user_event_service.py | 154 + owl-bot-staging/v2beta/mypy.ini | 3 + owl-bot-staging/v2beta/noxfile.py | 180 + ...log_service_add_catalog_attribute_async.py | 49 + ...alog_service_add_catalog_attribute_sync.py | 49 + ...log_service_get_attributes_config_async.py | 45 + ...alog_service_get_attributes_config_sync.py | 45 + ...log_service_get_completion_config_async.py | 45 + ...alog_service_get_completion_config_sync.py | 45 + ...atalog_service_get_default_branch_async.py | 44 + ...catalog_service_get_default_branch_sync.py | 44 + ...ted_catalog_service_list_catalogs_async.py | 46 + ...ated_catalog_service_list_catalogs_sync.py | 46 + ..._service_remove_catalog_attribute_async.py | 46 + ...g_service_remove_catalog_attribute_sync.py | 46 + ...service_replace_catalog_attribute_async.py | 49 + ..._service_replace_catalog_attribute_sync.py | 49 + ...atalog_service_set_default_branch_async.py | 42 + ...catalog_service_set_default_branch_sync.py | 42 + ..._service_update_attributes_config_async.py | 48 + ...g_service_update_attributes_config_sync.py | 48 + ...ed_catalog_service_update_catalog_async.py | 49 + ...ted_catalog_service_update_catalog_sync.py | 49 + ..._service_update_completion_config_async.py | 48 + ...g_service_update_completion_config_sync.py | 48 + ...completion_service_complete_query_async.py | 46 + ..._completion_service_complete_query_sync.py | 46 + ...on_service_import_completion_data_async.py | 54 + ...ion_service_import_completion_data_sync.py | 54 + ...ed_control_service_create_control_async.py | 52 + ...ted_control_service_create_control_sync.py | 52 + ...ed_control_service_delete_control_async.py | 43 + ...ted_control_service_delete_control_sync.py | 43 + ...rated_control_service_get_control_async.py | 45 + ...erated_control_service_get_control_sync.py | 45 + ...ted_control_service_list_controls_async.py | 46 + ...ated_control_service_list_controls_sync.py | 46 + ...ed_control_service_update_control_async.py | 50 + ...ted_control_service_update_control_sync.py | 50 + ...erated_prediction_service_predict_async.py | 50 + ...nerated_prediction_service_predict_sync.py | 50 + ...ct_service_add_fulfillment_places_async.py | 51 + ...uct_service_add_fulfillment_places_sync.py | 51 + ...uct_service_add_local_inventories_async.py | 49 + ...duct_service_add_local_inventories_sync.py | 49 + ...ed_product_service_create_product_async.py | 50 + ...ted_product_service_create_product_sync.py | 50 + ...ed_product_service_delete_product_async.py | 43 + ...ted_product_service_delete_product_sync.py | 43 + ...rated_product_service_get_product_async.py | 45 + ...erated_product_service_get_product_sync.py | 45 + ...d_product_service_import_products_async.py | 53 + ...ed_product_service_import_products_sync.py | 53 + ...ted_product_service_list_products_async.py | 46 + ...ated_product_service_list_products_sync.py | 46 + ...service_remove_fulfillment_places_async.py | 51 + ..._service_remove_fulfillment_places_sync.py | 51 + ..._service_remove_local_inventories_async.py | 50 + ...t_service_remove_local_inventories_sync.py | 50 + ...ted_product_service_set_inventory_async.py | 52 + ...ated_product_service_set_inventory_sync.py | 52 + ...ed_product_service_update_product_async.py | 48 + ...ted_product_service_update_product_sync.py | 48 + ...a_generated_search_service_search_async.py | 47 + ...ta_generated_search_service_search_sync.py | 47 + ...erving_config_service_add_control_async.py | 46 + ...serving_config_service_add_control_sync.py | 46 + ...fig_service_create_serving_config_async.py | 51 + ...nfig_service_create_serving_config_sync.py | 51 + ...fig_service_delete_serving_config_async.py | 43 + ...nfig_service_delete_serving_config_sync.py | 43 + ...config_service_get_serving_config_async.py | 45 + ..._config_service_get_serving_config_sync.py | 45 + ...nfig_service_list_serving_configs_async.py | 46 + ...onfig_service_list_serving_configs_sync.py | 46 + ...ing_config_service_remove_control_async.py | 46 + ...ving_config_service_remove_control_sync.py | 46 + ...fig_service_update_serving_config_async.py | 49 + ...nfig_service_update_serving_config_sync.py | 49 + ..._event_service_collect_user_event_async.py | 46 + ...r_event_service_collect_user_event_sync.py | 46 + ..._event_service_import_user_events_async.py | 54 + ...r_event_service_import_user_events_sync.py | 54 + ...r_event_service_purge_user_events_async.py | 50 + ...er_event_service_purge_user_events_sync.py | 50 + ..._event_service_rejoin_user_events_async.py | 49 + ...r_event_service_rejoin_user_events_sync.py | 49 + ...er_event_service_write_user_event_async.py | 50 + ...ser_event_service_write_user_event_sync.py | 50 + .../snippet_metadata_retail_v2beta.json | 6913 ++++++++++++++++ .../scripts/fixup_retail_v2beta_keywords.py | 218 + owl-bot-staging/v2beta/setup.py | 59 + owl-bot-staging/v2beta/tests/__init__.py | 16 + owl-bot-staging/v2beta/tests/unit/__init__.py | 16 + .../v2beta/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/retail_v2beta/__init__.py | 16 + .../retail_v2beta/test_catalog_service.py | 3793 +++++++++ .../retail_v2beta/test_completion_service.py | 1451 ++++ .../retail_v2beta/test_control_service.py | 2554 ++++++ .../retail_v2beta/test_prediction_service.py | 1279 +++ .../retail_v2beta/test_product_service.py | 4085 ++++++++++ .../retail_v2beta/test_search_service.py | 1496 ++++ .../test_serving_config_service.py | 3279 ++++++++ .../retail_v2beta/test_user_event_service.py | 1988 +++++ 554 files changed, 174195 insertions(+) create mode 100644 owl-bot-staging/v2/.coveragerc create mode 100644 owl-bot-staging/v2/.flake8 create mode 100644 owl-bot-staging/v2/MANIFEST.in create mode 100644 owl-bot-staging/v2/README.rst create mode 100644 owl-bot-staging/v2/docs/conf.py create mode 100644 owl-bot-staging/v2/docs/index.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/catalog_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/completion_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/prediction_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/product_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/search_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/services.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/types.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/user_event_service.rst create mode 100644 owl-bot-staging/v2/google/cloud/retail/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/common.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/product.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py create mode 100644 owl-bot-staging/v2/mypy.ini create mode 100644 owl-bot-staging/v2/noxfile.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json create mode 100644 owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py create mode 100644 owl-bot-staging/v2/setup.py create mode 100644 owl-bot-staging/v2/tests/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py create mode 100644 owl-bot-staging/v2alpha/.coveragerc create mode 100644 owl-bot-staging/v2alpha/.flake8 create mode 100644 owl-bot-staging/v2alpha/MANIFEST.in create mode 100644 owl-bot-staging/v2alpha/README.rst create mode 100644 owl-bot-staging/v2alpha/docs/conf.py create mode 100644 owl-bot-staging/v2alpha/docs/index.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail/py.typed create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py create mode 100644 owl-bot-staging/v2alpha/mypy.ini create mode 100644 owl-bot-staging/v2alpha/noxfile.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json create mode 100644 owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py create mode 100644 owl-bot-staging/v2alpha/setup.py create mode 100644 owl-bot-staging/v2alpha/tests/__init__.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py create mode 100644 owl-bot-staging/v2beta/.coveragerc create mode 100644 owl-bot-staging/v2beta/.flake8 create mode 100644 owl-bot-staging/v2beta/MANIFEST.in create mode 100644 owl-bot-staging/v2beta/README.rst create mode 100644 owl-bot-staging/v2beta/docs/conf.py create mode 100644 owl-bot-staging/v2beta/docs/index.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/services.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/types.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst create mode 100644 owl-bot-staging/v2beta/google/cloud/retail/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail/py.typed create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py create mode 100644 owl-bot-staging/v2beta/mypy.ini create mode 100644 owl-bot-staging/v2beta/noxfile.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json create mode 100644 owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py create mode 100644 owl-bot-staging/v2beta/setup.py create mode 100644 owl-bot-staging/v2beta/tests/__init__.py create mode 100644 owl-bot-staging/v2beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc new file mode 100644 index 00000000..a8b114f0 --- /dev/null +++ b/owl-bot-staging/v2/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/retail/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2/.flake8 b/owl-bot-staging/v2/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v2/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in new file mode 100644 index 00000000..985b915c --- /dev/null +++ b/owl-bot-staging/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/retail *.py +recursive-include google/cloud/retail_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst new file mode 100644 index 00000000..cb039760 --- /dev/null +++ b/owl-bot-staging/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Retail API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Retail API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py new file mode 100644 index 00000000..5be9eb4b --- /dev/null +++ b/owl-bot-staging/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-retail documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-retail" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-retail-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-retail.tex", + u"google-cloud-retail Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-retail", + u"Google Cloud Retail Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-retail", + u"google-cloud-retail Documentation", + author, + "google-cloud-retail", + "GAPIC library for Google Cloud Retail API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst new file mode 100644 index 00000000..c70f61bc --- /dev/null +++ b/owl-bot-staging/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + retail_v2/services + retail_v2/types diff --git a/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst b/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst new file mode 100644 index 00000000..5b7227d9 --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst @@ -0,0 +1,10 @@ +CatalogService +-------------------------------- + +.. automodule:: google.cloud.retail_v2.services.catalog_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2.services.catalog_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/completion_service.rst b/owl-bot-staging/v2/docs/retail_v2/completion_service.rst new file mode 100644 index 00000000..551f89ed --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/completion_service.rst @@ -0,0 +1,6 @@ +CompletionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2.services.completion_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst b/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst new file mode 100644 index 00000000..12ffb6ee --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst @@ -0,0 +1,6 @@ +PredictionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2.services.prediction_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/product_service.rst b/owl-bot-staging/v2/docs/retail_v2/product_service.rst new file mode 100644 index 00000000..0b8fa911 --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/product_service.rst @@ -0,0 +1,10 @@ +ProductService +-------------------------------- + +.. automodule:: google.cloud.retail_v2.services.product_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2.services.product_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/search_service.rst b/owl-bot-staging/v2/docs/retail_v2/search_service.rst new file mode 100644 index 00000000..af72819d --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/search_service.rst @@ -0,0 +1,10 @@ +SearchService +------------------------------- + +.. automodule:: google.cloud.retail_v2.services.search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2.services.search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/services.rst b/owl-bot-staging/v2/docs/retail_v2/services.rst new file mode 100644 index 00000000..f86138d7 --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/services.rst @@ -0,0 +1,11 @@ +Services for Google Cloud Retail v2 API +======================================= +.. toctree:: + :maxdepth: 2 + + catalog_service + completion_service + prediction_service + product_service + search_service + user_event_service diff --git a/owl-bot-staging/v2/docs/retail_v2/types.rst b/owl-bot-staging/v2/docs/retail_v2/types.rst new file mode 100644 index 00000000..54951beb --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Retail v2 API +==================================== + +.. automodule:: google.cloud.retail_v2.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst b/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst new file mode 100644 index 00000000..00e214a9 --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst @@ -0,0 +1,6 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.retail_v2.services.user_event_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/google/cloud/retail/__init__.py b/owl-bot-staging/v2/google/cloud/retail/__init__.py new file mode 100644 index 00000000..0d70ed64 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail/__init__.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.retail_v2.services.catalog_service.client import CatalogServiceClient +from google.cloud.retail_v2.services.catalog_service.async_client import CatalogServiceAsyncClient +from google.cloud.retail_v2.services.completion_service.client import CompletionServiceClient +from google.cloud.retail_v2.services.completion_service.async_client import CompletionServiceAsyncClient +from google.cloud.retail_v2.services.prediction_service.client import PredictionServiceClient +from google.cloud.retail_v2.services.prediction_service.async_client import PredictionServiceAsyncClient +from google.cloud.retail_v2.services.product_service.client import ProductServiceClient +from google.cloud.retail_v2.services.product_service.async_client import ProductServiceAsyncClient +from google.cloud.retail_v2.services.search_service.client import SearchServiceClient +from google.cloud.retail_v2.services.search_service.async_client import SearchServiceAsyncClient +from google.cloud.retail_v2.services.user_event_service.client import UserEventServiceClient +from google.cloud.retail_v2.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.retail_v2.types.catalog import Catalog +from google.cloud.retail_v2.types.catalog import ProductLevelConfig +from google.cloud.retail_v2.types.catalog_service import GetDefaultBranchRequest +from google.cloud.retail_v2.types.catalog_service import GetDefaultBranchResponse +from google.cloud.retail_v2.types.catalog_service import ListCatalogsRequest +from google.cloud.retail_v2.types.catalog_service import ListCatalogsResponse +from google.cloud.retail_v2.types.catalog_service import SetDefaultBranchRequest +from google.cloud.retail_v2.types.catalog_service import UpdateCatalogRequest +from google.cloud.retail_v2.types.common import Audience +from google.cloud.retail_v2.types.common import ColorInfo +from google.cloud.retail_v2.types.common import CustomAttribute +from google.cloud.retail_v2.types.common import FulfillmentInfo +from google.cloud.retail_v2.types.common import Image +from google.cloud.retail_v2.types.common import Interval +from google.cloud.retail_v2.types.common import LocalInventory +from google.cloud.retail_v2.types.common import PriceInfo +from google.cloud.retail_v2.types.common import Rating +from google.cloud.retail_v2.types.common import UserInfo +from google.cloud.retail_v2.types.completion_service import CompleteQueryRequest +from google.cloud.retail_v2.types.completion_service import CompleteQueryResponse +from google.cloud.retail_v2.types.import_config import BigQuerySource +from google.cloud.retail_v2.types.import_config import CompletionDataInputConfig +from google.cloud.retail_v2.types.import_config import GcsSource +from google.cloud.retail_v2.types.import_config import ImportCompletionDataRequest +from google.cloud.retail_v2.types.import_config import ImportCompletionDataResponse +from google.cloud.retail_v2.types.import_config import ImportErrorsConfig +from google.cloud.retail_v2.types.import_config import ImportMetadata +from google.cloud.retail_v2.types.import_config import ImportProductsRequest +from google.cloud.retail_v2.types.import_config import ImportProductsResponse +from google.cloud.retail_v2.types.import_config import ImportUserEventsRequest +from google.cloud.retail_v2.types.import_config import ImportUserEventsResponse +from google.cloud.retail_v2.types.import_config import ProductInlineSource +from google.cloud.retail_v2.types.import_config import ProductInputConfig +from google.cloud.retail_v2.types.import_config import UserEventImportSummary +from google.cloud.retail_v2.types.import_config import UserEventInlineSource +from google.cloud.retail_v2.types.import_config import UserEventInputConfig +from google.cloud.retail_v2.types.prediction_service import PredictRequest +from google.cloud.retail_v2.types.prediction_service import PredictResponse +from google.cloud.retail_v2.types.product import Product +from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesMetadata +from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesRequest +from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesResponse +from google.cloud.retail_v2.types.product_service import AddLocalInventoriesMetadata +from google.cloud.retail_v2.types.product_service import AddLocalInventoriesRequest +from google.cloud.retail_v2.types.product_service import AddLocalInventoriesResponse +from google.cloud.retail_v2.types.product_service import CreateProductRequest +from google.cloud.retail_v2.types.product_service import DeleteProductRequest +from google.cloud.retail_v2.types.product_service import GetProductRequest +from google.cloud.retail_v2.types.product_service import ListProductsRequest +from google.cloud.retail_v2.types.product_service import ListProductsResponse +from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesMetadata +from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesRequest +from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesResponse +from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesMetadata +from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesRequest +from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesResponse +from google.cloud.retail_v2.types.product_service import SetInventoryMetadata +from google.cloud.retail_v2.types.product_service import SetInventoryRequest +from google.cloud.retail_v2.types.product_service import SetInventoryResponse +from google.cloud.retail_v2.types.product_service import UpdateProductRequest +from google.cloud.retail_v2.types.promotion import Promotion +from google.cloud.retail_v2.types.purge_config import PurgeMetadata +from google.cloud.retail_v2.types.purge_config import PurgeUserEventsRequest +from google.cloud.retail_v2.types.purge_config import PurgeUserEventsResponse +from google.cloud.retail_v2.types.search_service import SearchRequest +from google.cloud.retail_v2.types.search_service import SearchResponse +from google.cloud.retail_v2.types.user_event import CompletionDetail +from google.cloud.retail_v2.types.user_event import ProductDetail +from google.cloud.retail_v2.types.user_event import PurchaseTransaction +from google.cloud.retail_v2.types.user_event import UserEvent +from google.cloud.retail_v2.types.user_event_service import CollectUserEventRequest +from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsMetadata +from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsRequest +from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsResponse +from google.cloud.retail_v2.types.user_event_service import WriteUserEventRequest + +__all__ = ('CatalogServiceClient', + 'CatalogServiceAsyncClient', + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', + 'ProductServiceClient', + 'ProductServiceAsyncClient', + 'SearchServiceClient', + 'SearchServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'Catalog', + 'ProductLevelConfig', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'SetDefaultBranchRequest', + 'UpdateCatalogRequest', + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2/google/cloud/retail/py.typed b/owl-bot-staging/v2/google/cloud/retail/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py new file mode 100644 index 00000000..c7f56a8d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.catalog_service import CatalogServiceClient +from .services.catalog_service import CatalogServiceAsyncClient +from .services.completion_service import CompletionServiceClient +from .services.completion_service import CompletionServiceAsyncClient +from .services.prediction_service import PredictionServiceClient +from .services.prediction_service import PredictionServiceAsyncClient +from .services.product_service import ProductServiceClient +from .services.product_service import ProductServiceAsyncClient +from .services.search_service import SearchServiceClient +from .services.search_service import SearchServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.catalog import Catalog +from .types.catalog import ProductLevelConfig +from .types.catalog_service import GetDefaultBranchRequest +from .types.catalog_service import GetDefaultBranchResponse +from .types.catalog_service import ListCatalogsRequest +from .types.catalog_service import ListCatalogsResponse +from .types.catalog_service import SetDefaultBranchRequest +from .types.catalog_service import UpdateCatalogRequest +from .types.common import Audience +from .types.common import ColorInfo +from .types.common import CustomAttribute +from .types.common import FulfillmentInfo +from .types.common import Image +from .types.common import Interval +from .types.common import LocalInventory +from .types.common import PriceInfo +from .types.common import Rating +from .types.common import UserInfo +from .types.completion_service import CompleteQueryRequest +from .types.completion_service import CompleteQueryResponse +from .types.import_config import BigQuerySource +from .types.import_config import CompletionDataInputConfig +from .types.import_config import GcsSource +from .types.import_config import ImportCompletionDataRequest +from .types.import_config import ImportCompletionDataResponse +from .types.import_config import ImportErrorsConfig +from .types.import_config import ImportMetadata +from .types.import_config import ImportProductsRequest +from .types.import_config import ImportProductsResponse +from .types.import_config import ImportUserEventsRequest +from .types.import_config import ImportUserEventsResponse +from .types.import_config import ProductInlineSource +from .types.import_config import ProductInputConfig +from .types.import_config import UserEventImportSummary +from .types.import_config import UserEventInlineSource +from .types.import_config import UserEventInputConfig +from .types.prediction_service import PredictRequest +from .types.prediction_service import PredictResponse +from .types.product import Product +from .types.product_service import AddFulfillmentPlacesMetadata +from .types.product_service import AddFulfillmentPlacesRequest +from .types.product_service import AddFulfillmentPlacesResponse +from .types.product_service import AddLocalInventoriesMetadata +from .types.product_service import AddLocalInventoriesRequest +from .types.product_service import AddLocalInventoriesResponse +from .types.product_service import CreateProductRequest +from .types.product_service import DeleteProductRequest +from .types.product_service import GetProductRequest +from .types.product_service import ListProductsRequest +from .types.product_service import ListProductsResponse +from .types.product_service import RemoveFulfillmentPlacesMetadata +from .types.product_service import RemoveFulfillmentPlacesRequest +from .types.product_service import RemoveFulfillmentPlacesResponse +from .types.product_service import RemoveLocalInventoriesMetadata +from .types.product_service import RemoveLocalInventoriesRequest +from .types.product_service import RemoveLocalInventoriesResponse +from .types.product_service import SetInventoryMetadata +from .types.product_service import SetInventoryRequest +from .types.product_service import SetInventoryResponse +from .types.product_service import UpdateProductRequest +from .types.promotion import Promotion +from .types.purge_config import PurgeMetadata +from .types.purge_config import PurgeUserEventsRequest +from .types.purge_config import PurgeUserEventsResponse +from .types.search_service import SearchRequest +from .types.search_service import SearchResponse +from .types.user_event import CompletionDetail +from .types.user_event import ProductDetail +from .types.user_event import PurchaseTransaction +from .types.user_event import UserEvent +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import RejoinUserEventsMetadata +from .types.user_event_service import RejoinUserEventsRequest +from .types.user_event_service import RejoinUserEventsResponse +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CatalogServiceAsyncClient', + 'CompletionServiceAsyncClient', + 'PredictionServiceAsyncClient', + 'ProductServiceAsyncClient', + 'SearchServiceAsyncClient', + 'UserEventServiceAsyncClient', +'AddFulfillmentPlacesMetadata', +'AddFulfillmentPlacesRequest', +'AddFulfillmentPlacesResponse', +'AddLocalInventoriesMetadata', +'AddLocalInventoriesRequest', +'AddLocalInventoriesResponse', +'Audience', +'BigQuerySource', +'Catalog', +'CatalogServiceClient', +'CollectUserEventRequest', +'ColorInfo', +'CompleteQueryRequest', +'CompleteQueryResponse', +'CompletionDataInputConfig', +'CompletionDetail', +'CompletionServiceClient', +'CreateProductRequest', +'CustomAttribute', +'DeleteProductRequest', +'FulfillmentInfo', +'GcsSource', +'GetDefaultBranchRequest', +'GetDefaultBranchResponse', +'GetProductRequest', +'Image', +'ImportCompletionDataRequest', +'ImportCompletionDataResponse', +'ImportErrorsConfig', +'ImportMetadata', +'ImportProductsRequest', +'ImportProductsResponse', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'Interval', +'ListCatalogsRequest', +'ListCatalogsResponse', +'ListProductsRequest', +'ListProductsResponse', +'LocalInventory', +'PredictRequest', +'PredictResponse', +'PredictionServiceClient', +'PriceInfo', +'Product', +'ProductDetail', +'ProductInlineSource', +'ProductInputConfig', +'ProductLevelConfig', +'ProductServiceClient', +'Promotion', +'PurchaseTransaction', +'PurgeMetadata', +'PurgeUserEventsRequest', +'PurgeUserEventsResponse', +'Rating', +'RejoinUserEventsMetadata', +'RejoinUserEventsRequest', +'RejoinUserEventsResponse', +'RemoveFulfillmentPlacesMetadata', +'RemoveFulfillmentPlacesRequest', +'RemoveFulfillmentPlacesResponse', +'RemoveLocalInventoriesMetadata', +'RemoveLocalInventoriesRequest', +'RemoveLocalInventoriesResponse', +'SearchRequest', +'SearchResponse', +'SearchServiceClient', +'SetDefaultBranchRequest', +'SetInventoryMetadata', +'SetInventoryRequest', +'SetInventoryResponse', +'UpdateCatalogRequest', +'UpdateProductRequest', +'UserEvent', +'UserEventImportSummary', +'UserEventInlineSource', +'UserEventInputConfig', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json new file mode 100644 index 00000000..9e04aec8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json @@ -0,0 +1,333 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.retail_v2", + "protoPackage": "google.cloud.retail.v2", + "schema": "1.0", + "services": { + "CatalogService": { + "clients": { + "grpc": { + "libraryClient": "CatalogServiceClient", + "rpcs": { + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CatalogServiceAsyncClient", + "rpcs": { + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + } + } + } + } + }, + "CompletionService": { + "clients": { + "grpc": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CompletionServiceAsyncClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + } + } + }, + "PredictionService": { + "clients": { + "grpc": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionServiceAsyncClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + } + } + }, + "ProductService": { + "clients": { + "grpc": { + "libraryClient": "ProductServiceClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductServiceAsyncClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + } + } + }, + "SearchService": { + "clients": { + "grpc": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SearchServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/py.typed b/owl-bot-staging/v2/google/cloud/retail_v2/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py new file mode 100644 index 00000000..d276b897 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CatalogServiceClient +from .async_client import CatalogServiceAsyncClient + +__all__ = ( + 'CatalogServiceClient', + 'CatalogServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py new file mode 100644 index 00000000..b0a1b99e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py @@ -0,0 +1,653 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.services.catalog_service import pagers +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport +from .client import CatalogServiceClient + + +class CatalogServiceAsyncClient: + """Service for managing catalog configuration.""" + + _client: CatalogServiceClient + + DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(CatalogServiceClient.branch_path) + parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) + catalog_path = staticmethod(CatalogServiceClient.catalog_path) + parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) + common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CatalogServiceClient.common_project_path) + parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) + common_location_path = staticmethod(CatalogServiceClient.common_location_path) + parse_common_location_path = staticmethod(CatalogServiceClient.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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CatalogServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsAsyncPager: + r"""Lists all the [Catalog][google.cloud.retail.v2.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_list_catalogs(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + parent (:class:`str`): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2.Catalog]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.retail_v2.services.catalog_service.pagers.ListCatalogsAsyncPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.ListCatalogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_catalogs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCatalogsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_update_catalog(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] + method. + catalog (:class:`google.cloud.retail_v2.types.Catalog`): + Required. The [Catalog][google.cloud.retail.v2.Catalog] + to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2.Catalog], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_catalog, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_set_default_branch(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (:class:`str`): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.SetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_get_default_branch(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (:class:`str`): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # 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_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py new file mode 100644 index 00000000..e6b97cfd --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py @@ -0,0 +1,861 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.services.catalog_service import pagers +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CatalogServiceGrpcTransport +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +class CatalogServiceClientMeta(type): + """Metaclass for the CatalogService 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[CatalogServiceTransport]] + _transport_registry["grpc"] = CatalogServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CatalogServiceTransport]: + """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): + """Service for managing catalog configuration.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CatalogServiceClient: 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: + CatalogServiceClient: 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) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CatalogServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CatalogServiceTransport): + # transport is a CatalogServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsPager: + r"""Lists all the [Catalog][google.cloud.retail.v2.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_list_catalogs(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2.Catalog]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.retail_v2.services.catalog_service.pagers.ListCatalogsPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ListCatalogsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ListCatalogsRequest): + request = catalog_service.ListCatalogsRequest(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_catalogs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCatalogsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_update_catalog(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] + method. + catalog (google.cloud.retail_v2.types.Catalog): + Required. The [Catalog][google.cloud.retail.v2.Catalog] + to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2.Catalog], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCatalogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCatalogRequest): + request = catalog_service.UpdateCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + 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_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_set_default_branch(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.SetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.SetDefaultBranchRequest): + request = catalog_service.SetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_get_default_branch(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetDefaultBranchRequest): + request = catalog_service.GetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py new file mode 100644 index 00000000..11dd0677 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog_service + + +class ListCatalogsPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.ListCatalogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.ListCatalogsResponse` + 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[..., catalog_service.ListCatalogsResponse], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + for page in self.pages: + yield from page.catalogs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCatalogsAsyncPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.ListCatalogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.ListCatalogsResponse` + 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[catalog_service.ListCatalogsResponse]], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + async def async_generator(): + async for page in self.pages: + for response in page.catalogs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py new file mode 100644 index 00000000..0cffa336 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 CatalogServiceTransport +from .grpc import CatalogServiceGrpcTransport +from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] +_transport_registry['grpc'] = CatalogServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport + +__all__ = ( + 'CatalogServiceTransport', + 'CatalogServiceGrpcTransport', + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py new file mode 100644 index 00000000..5f86e6d3 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CatalogServiceTransport(abc.ABC): + """Abstract transport class for CatalogService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_catalogs: gapic_v1.method.wrap_method( + self.list_catalogs, + default_timeout=None, + client_info=client_info, + ), + self.update_catalog: gapic_v1.method.wrap_method( + self.update_catalog, + default_timeout=None, + client_info=client_info, + ), + self.set_default_branch: gapic_v1.method.wrap_method( + self.set_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_default_branch: gapic_v1.method.wrap_method( + self.get_default_branch, + 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Union[ + catalog_service.ListCatalogsResponse, + Awaitable[catalog_service.ListCatalogsResponse] + ]]: + raise NotImplementedError() + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Union[ + gcr_catalog.Catalog, + Awaitable[gcr_catalog.Catalog] + ]]: + raise NotImplementedError() + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Union[ + catalog_service.GetDefaultBranchResponse, + Awaitable[catalog_service.GetDefaultBranchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CatalogServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py new file mode 100644 index 00000000..e4f36175 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py @@ -0,0 +1,379 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO + + +class CatalogServiceGrpcTransport(CatalogServiceTransport): + """gRPC backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + catalog_service.ListCatalogsResponse]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + ~.ListCatalogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + gcr_catalog.Catalog]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + ~.Catalog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + empty_pb2.Empty]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + ~.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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + catalog_service.GetDefaultBranchResponse]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + ~.GetDefaultBranchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CatalogServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..38344d17 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py @@ -0,0 +1,378 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CatalogServiceGrpcTransport + + +class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): + """gRPC AsyncIO backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Awaitable[catalog_service.ListCatalogsResponse]]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + Awaitable[~.ListCatalogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Awaitable[gcr_catalog.Catalog]]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + Awaitable[~.Catalog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + 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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Awaitable[catalog_service.GetDefaultBranchResponse]]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + Awaitable[~.GetDefaultBranchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py new file mode 100644 index 00000000..b8af95bd --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CompletionServiceClient +from .async_client import CompletionServiceAsyncClient + +__all__ = ( + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py new file mode 100644 index 00000000..9e5d6432 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .client import CompletionServiceClient + + +class CompletionServiceAsyncClient: + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: CompletionServiceClient + + DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(CompletionServiceClient.catalog_path) + parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) + common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CompletionServiceClient.common_project_path) + parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) + common_location_path = staticmethod(CompletionServiceClient.common_location_path) + parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CompletionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_complete_query(): + # Create a client + client = retail_v2.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_query, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_import_completion_data(): + # Create a client + client = retail_v2.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. + 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. + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_completion_data, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py new file mode 100644 index 00000000..95aa31c3 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py @@ -0,0 +1,592 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CompletionServiceGrpcTransport +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +class CompletionServiceClientMeta(type): + """Metaclass for the CompletionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] + _transport_registry["grpc"] = CompletionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CompletionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CompletionServiceClient(metaclass=CompletionServiceClientMeta): + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CompletionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CompletionServiceTransport): + # transport is a CompletionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_complete_query(): + # Create a client + client = retail_v2.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a completion_service.CompleteQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, completion_service.CompleteQueryRequest): + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_import_completion_data(): + # Create a client + client = retail_v2.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. + 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. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportCompletionDataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportCompletionDataRequest): + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_completion_data] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py new file mode 100644 index 00000000..a0c9542f --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CompletionServiceTransport +from .grpc import CompletionServiceGrpcTransport +from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] +_transport_registry['grpc'] = CompletionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport + +__all__ = ( + 'CompletionServiceTransport', + 'CompletionServiceGrpcTransport', + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py new file mode 100644 index 00000000..3cc2b0e8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CompletionServiceTransport(abc.ABC): + """Abstract transport class for CompletionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.complete_query: gapic_v1.method.wrap_method( + self.complete_query, + default_timeout=None, + client_info=client_info, + ), + self.import_completion_data: gapic_v1.method.wrap_method( + self.import_completion_data, + 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Union[ + completion_service.CompleteQueryResponse, + Awaitable[completion_service.CompleteQueryResponse] + ]]: + raise NotImplementedError() + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CompletionServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py new file mode 100644 index 00000000..383f0bf9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py @@ -0,0 +1,323 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO + + +class CompletionServiceGrpcTransport(CompletionServiceTransport): + """gRPC backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + ~.CompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + operations_pb2.Operation]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CompletionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..f945dec1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py @@ -0,0 +1,322 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CompletionServiceGrpcTransport + + +class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): + """gRPC AsyncIO backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Awaitable[completion_service.CompleteQueryResponse]]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + Awaitable[~.CompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + 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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py new file mode 100644 index 00000000..7c079c80 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import PredictionServiceClient +from .async_client import PredictionServiceAsyncClient + +__all__ = ( + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py new file mode 100644 index 00000000..ae9f9c86 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport +from .client import PredictionServiceClient + + +class PredictionServiceAsyncClient: + """Service for making recommendation prediction.""" + + _client: PredictionServiceClient + + DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT + + product_path = staticmethod(PredictionServiceClient.product_path) + parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) + common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(PredictionServiceClient.common_project_path) + parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) + common_location_path = staticmethod(PredictionServiceClient.common_location_path) + parse_common_location_path = staticmethod(PredictionServiceClient.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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PredictionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_predict(): + # Create a client + client = retail_v2.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + request = prediction_service.PredictRequest(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.predict, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py new file mode 100644 index 00000000..51ab0482 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py @@ -0,0 +1,479 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionServiceGrpcTransport +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +class PredictionServiceClientMeta(type): + """Metaclass for the PredictionService 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[PredictionServiceTransport]] + _transport_registry["grpc"] = PredictionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PredictionServiceTransport]: + """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): + """Service for making recommendation prediction.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PredictionServiceClient: 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: + PredictionServiceClient: 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) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PredictionServiceTransport): + # transport is a PredictionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_predict(): + # Create a client + client = retail_v2.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a prediction_service.PredictRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_service.PredictRequest): + request = prediction_service.PredictRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.predict] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py new file mode 100644 index 00000000..bb65c664 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PredictionServiceTransport +from .grpc import PredictionServiceGrpcTransport +from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] +_transport_registry['grpc'] = PredictionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport + +__all__ = ( + 'PredictionServiceTransport', + 'PredictionServiceGrpcTransport', + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py new file mode 100644 index 00000000..4bf1f54d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import prediction_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PredictionServiceTransport(abc.ABC): + """Abstract transport class for PredictionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.predict: gapic_v1.method.wrap_method( + self.predict, + 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + Union[ + prediction_service.PredictResponse, + Awaitable[prediction_service.PredictResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'PredictionServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py new file mode 100644 index 00000000..5b717f9b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO + + +class PredictionServiceGrpcTransport(PredictionServiceTransport): + """gRPC backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + prediction_service.PredictResponse]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + ~.PredictResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'PredictionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..1805223d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import PredictionServiceGrpcTransport + + +class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): + """gRPC AsyncIO backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + Awaitable[prediction_service.PredictResponse]]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + Awaitable[~.PredictResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py new file mode 100644 index 00000000..0fa6330a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ProductServiceClient +from .async_client import ProductServiceAsyncClient + +__all__ = ( + 'ProductServiceClient', + 'ProductServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py new file mode 100644 index 00000000..db29be72 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py @@ -0,0 +1,1701 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.services.product_service import pagers +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.cloud.retail_v2.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport +from .client import ProductServiceClient + + +class ProductServiceAsyncClient: + """Service for ingesting [Product][google.cloud.retail.v2.Product] + information of the customer's website. + """ + + _client: ProductServiceClient + + DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(ProductServiceClient.branch_path) + parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) + product_path = staticmethod(ProductServiceClient.product_path) + parse_product_path = staticmethod(ProductServiceClient.parse_product_path) + common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProductServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProductServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProductServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProductServiceClient.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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ProductServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ProductServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_create_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`google.cloud.retail_v2.types.Product`): + Required. The [Product][google.cloud.retail.v2.Product] + to create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + Required. The ID to use for the + [Product][google.cloud.retail.v2.Product], which will + become the final component of the + [Product.name][google.cloud.retail.v2.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2.Product]s with the same + [parent][google.cloud.retail.v2.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_get_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested + [Product][google.cloud.retail.v2.Product] 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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Gets a list of [Product][google.cloud.retail.v2.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_list_products(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2.Product]s under this + branch, regardless of whether or not this branch exists, + a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.services.product_service.pagers.ListProductsAsyncPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_update_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (:class:`google.cloud.retail_v2.types.Product`): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2.Product] to update. The + immutable and output only fields are NOT supported. If + not set, all supported fields (the fields that are + neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + The attribute key can be updated by setting the mask + path as "attributes.${key_name}". If a key name is + present in the mask but not in the patching product from + the request, this key will be deleted after the update. + + 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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_delete_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2.Product] to delete + can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] with more than + one + [variants][google.cloud.retail.v2.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2.Product]s. + + Request processing may be synchronous. Non-existing items are + created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2.Product]s to be successfully + updated. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_import_products(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2.Product] while respecting the + last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_set_inventory(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2.Product() + inventory.title = "title_value" + + request = retail_v2.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (:class:`google.cloud.retail_v2.types.Product`): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product] named in + [Product.name][google.cloud.retail.v2.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.SetInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_inventory, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + async def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places, + while respecting the last update timestamps of each inventory + field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_add_local_inventories(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.AddLocalInventoriesResponse` Response of the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + API. Currently empty because there is no meaningful + response populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places at + a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_remove_local_inventories(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py new file mode 100644 index 00000000..4a598563 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py @@ -0,0 +1,1903 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.services.product_service import pagers +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.cloud.retail_v2.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductServiceGrpcTransport +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +class ProductServiceClientMeta(type): + """Metaclass for the ProductService 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[ProductServiceTransport]] + _transport_registry["grpc"] = ProductServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ProductServiceTransport]: + """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 ProductServiceClient(metaclass=ProductServiceClientMeta): + """Service for ingesting [Product][google.cloud.retail.v2.Product] + information of the customer's website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProductServiceClient: 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: + ProductServiceClient: 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) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ProductServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProductServiceTransport): + # transport is a ProductServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_create_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (google.cloud.retail_v2.types.Product): + Required. The [Product][google.cloud.retail.v2.Product] + to create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2.Product], which will + become the final component of the + [Product.name][google.cloud.retail.v2.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2.Product]s with the same + [parent][google.cloud.retail.v2.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.CreateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.CreateProductRequest): + request = product_service.CreateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_get_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested + [Product][google.cloud.retail.v2.Product] 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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.GetProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.GetProductRequest): + request = product_service.GetProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Gets a list of [Product][google.cloud.retail.v2.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_list_products(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2.Product]s under this + branch, regardless of whether or not this branch exists, + a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.services.product_service.pagers.ListProductsPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.ListProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.ListProductsRequest): + request = product_service.ListProductsRequest(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_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_update_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (google.cloud.retail_v2.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2.Product] to update. The + immutable and output only fields are NOT supported. If + not set, all supported fields (the fields that are + neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + The attribute key can be updated by setting the mask + path as "attributes.${key_name}". If a key name is + present in the mask but not in the patching product from + the request, this key will be deleted after the update. + + 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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.UpdateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.UpdateProductRequest): + request = product_service.UpdateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + 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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_delete_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2.Product] to delete + can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] with more than + one + [variants][google.cloud.retail.v2.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.DeleteProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.DeleteProductRequest): + request = product_service.DeleteProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2.Product]s. + + Request processing may be synchronous. Non-existing items are + created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2.Product]s to be successfully + updated. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_import_products(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportProductsRequest): + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2.Product] while respecting the + last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_set_inventory(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2.Product() + inventory.title = "title_value" + + request = retail_v2.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (google.cloud.retail_v2.types.Product): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product] named in + [Product.name][google.cloud.retail.v2.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.SetInventoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.SetInventoryRequest): + request = product_service.SetInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_add_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddFulfillmentPlacesRequest): + request = product_service.AddFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): + request = product_service.RemoveFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places, + while respecting the last update timestamps of each inventory + field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_add_local_inventories(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.AddLocalInventoriesResponse` Response of the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + API. Currently empty because there is no meaningful + response populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddLocalInventoriesRequest): + request = product_service.AddLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places at + a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_remove_local_inventories(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveLocalInventoriesRequest): + request = product_service.RemoveLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py new file mode 100644 index 00000000..f9e49958 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product_service + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.ListProductsResponse` + 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[..., product_service.ListProductsResponse], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[product_service.ListProductsResponse]: + 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[product.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.ListProductsResponse` + 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[product_service.ListProductsResponse]], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: + 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[product.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py new file mode 100644 index 00000000..db824dec --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ProductServiceTransport +from .grpc import ProductServiceGrpcTransport +from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] +_transport_registry['grpc'] = ProductServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport + +__all__ = ( + 'ProductServiceTransport', + 'ProductServiceGrpcTransport', + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py new file mode 100644 index 00000000..7d737508 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py @@ -0,0 +1,308 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ProductServiceTransport(abc.ABC): + """Abstract transport class for ProductService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_product: gapic_v1.method.wrap_method( + self.create_product, + default_timeout=None, + client_info=client_info, + ), + self.get_product: gapic_v1.method.wrap_method( + self.get_product, + default_timeout=None, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + default_timeout=None, + client_info=client_info, + ), + self.update_product: gapic_v1.method.wrap_method( + self.update_product, + default_timeout=None, + client_info=client_info, + ), + self.delete_product: gapic_v1.method.wrap_method( + self.delete_product, + default_timeout=None, + client_info=client_info, + ), + self.import_products: gapic_v1.method.wrap_method( + self.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.set_inventory: gapic_v1.method.wrap_method( + self.set_inventory, + default_timeout=None, + client_info=client_info, + ), + self.add_fulfillment_places: gapic_v1.method.wrap_method( + self.add_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.remove_fulfillment_places: gapic_v1.method.wrap_method( + self.remove_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.add_local_inventories: gapic_v1.method.wrap_method( + self.add_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.remove_local_inventories: gapic_v1.method.wrap_method( + self.remove_local_inventories, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Union[ + product.Product, + Awaitable[product.Product] + ]]: + raise NotImplementedError() + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Union[ + product_service.ListProductsResponse, + Awaitable[product_service.ListProductsResponse] + ]]: + raise NotImplementedError() + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProductServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py new file mode 100644 index 00000000..b61a4b0e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py @@ -0,0 +1,678 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO + + +class ProductServiceGrpcTransport(ProductServiceTransport): + """gRPC backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + gcr_product.Product]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.CreateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + product.Product]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + product_service.ListProductsResponse]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + gcr_product.Product]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + ~.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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2.Product]s. + + Request processing may be synchronous. Non-existing items are + created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2.Product]s to be successfully + updated. + + Returns: + Callable[[~.ImportProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + operations_pb2.Operation]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2.Product] while respecting the + last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places, + while respecting the last update timestamps of each inventory + field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places at + a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProductServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..1433a72f --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py @@ -0,0 +1,677 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductServiceGrpcTransport + + +class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): + """gRPC AsyncIO backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.CreateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Awaitable[product.Product]]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Awaitable[product_service.ListProductsResponse]]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + 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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2.Product]s. + + Request processing may be synchronous. Non-existing items are + created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2.Product]s to be successfully + updated. + + Returns: + Callable[[~.ImportProductsRequest], + 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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2.Product] while respecting the + last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + 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 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + 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 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places, + while respecting the last update timestamps of each inventory + field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + 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 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places at + a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + 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 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py new file mode 100644 index 00000000..2f63fc22 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SearchServiceClient +from .async_client import SearchServiceAsyncClient + +__all__ = ( + 'SearchServiceClient', + 'SearchServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py new file mode 100644 index 00000000..c48710b8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.services.search_service import pagers +from google.cloud.retail_v2.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .client import SearchServiceClient + + +class SearchServiceAsyncClient: + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: SearchServiceClient + + DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(SearchServiceClient.branch_path) + parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + product_path = staticmethod(SearchServiceClient.product_path) + parse_product_path = staticmethod(SearchServiceClient.parse_product_path) + common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(SearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SearchServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAsyncPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_search(): + # Create a client + client = retail_v2.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.services.search_service.pagers.SearchAsyncPager: + Response message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py new file mode 100644 index 00000000..aabc6c30 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.services.search_service import pagers +from google.cloud.retail_v2.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SearchServiceGrpcTransport +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +class SearchServiceClientMeta(type): + """Metaclass for the SearchService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] + _transport_registry["grpc"] = SearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SearchServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SearchServiceClient(metaclass=SearchServiceClientMeta): + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SearchServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SearchServiceTransport): + # transport is a SearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_search(): + # Create a client + client = retail_v2.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.services.search_service.pagers.SearchPager: + Response message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a search_service.SearchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py new file mode 100644 index 00000000..524810e2 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2.types import search_service + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py new file mode 100644 index 00000000..7917cd1d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SearchServiceTransport +from .grpc import SearchServiceGrpcTransport +from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] +_transport_registry['grpc'] = SearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport + +__all__ = ( + 'SearchServiceTransport', + 'SearchServiceGrpcTransport', + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py new file mode 100644 index 00000000..4d31461b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import search_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SearchServiceTransport(abc.ABC): + """Abstract transport class for SearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search: gapic_v1.method.wrap_method( + self.search, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Union[ + search_service.SearchResponse, + Awaitable[search_service.SearchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SearchServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py new file mode 100644 index 00000000..0c575b65 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py @@ -0,0 +1,268 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO + + +class SearchServiceGrpcTransport(SearchServiceTransport): + """gRPC backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..84a64ed9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py @@ -0,0 +1,267 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SearchServiceGrpcTransport + + +class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): + """gRPC AsyncIO backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Awaitable[search_service.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py new file mode 100644 index 00000000..5f5171c1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py new file mode 100644 index 00000000..99002514 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py @@ -0,0 +1,730 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on the customer + website. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(UserEventServiceClient.catalog_path) + parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) + product_path = staticmethod(UserEventServiceClient.product_path) + parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_write_user_event(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_collect_user_event(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_purge_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_import_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_rejoin_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py new file mode 100644 index 00000000..8422b4b6 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py @@ -0,0 +1,929 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[UserEventServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on the customer + website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_write_user_event(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_collect_user_event(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_purge_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeUserEventsRequest): + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_import_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_rejoin_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.RejoinUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.RejoinUserEventsRequest): + request = user_event_service.RejoinUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py new file mode 100644 index 00000000..f53ee5d7 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py new file mode 100644 index 00000000..4a2436f6 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.rejoin_user_events: gapic_v1.method.wrap_method( + self.rejoin_user_events, + 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 write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + user_event.UserEvent, + Awaitable[user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py new file mode 100644 index 00000000..cfd04d9b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py @@ -0,0 +1,415 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..94b3b4e5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,414 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + 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 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py new file mode 100644 index 00000000..8e0ea23a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .catalog import ( + Catalog, + ProductLevelConfig, +) +from .catalog_service import ( + GetDefaultBranchRequest, + GetDefaultBranchResponse, + ListCatalogsRequest, + ListCatalogsResponse, + SetDefaultBranchRequest, + UpdateCatalogRequest, +) +from .common import ( + Audience, + ColorInfo, + CustomAttribute, + FulfillmentInfo, + Image, + Interval, + LocalInventory, + PriceInfo, + Rating, + UserInfo, +) +from .completion_service import ( + CompleteQueryRequest, + CompleteQueryResponse, +) +from .import_config import ( + BigQuerySource, + CompletionDataInputConfig, + GcsSource, + ImportCompletionDataRequest, + ImportCompletionDataResponse, + ImportErrorsConfig, + ImportMetadata, + ImportProductsRequest, + ImportProductsResponse, + ImportUserEventsRequest, + ImportUserEventsResponse, + ProductInlineSource, + ProductInputConfig, + UserEventImportSummary, + UserEventInlineSource, + UserEventInputConfig, +) +from .prediction_service import ( + PredictRequest, + PredictResponse, +) +from .product import ( + Product, +) +from .product_service import ( + AddFulfillmentPlacesMetadata, + AddFulfillmentPlacesRequest, + AddFulfillmentPlacesResponse, + AddLocalInventoriesMetadata, + AddLocalInventoriesRequest, + AddLocalInventoriesResponse, + CreateProductRequest, + DeleteProductRequest, + GetProductRequest, + ListProductsRequest, + ListProductsResponse, + RemoveFulfillmentPlacesMetadata, + RemoveFulfillmentPlacesRequest, + RemoveFulfillmentPlacesResponse, + RemoveLocalInventoriesMetadata, + RemoveLocalInventoriesRequest, + RemoveLocalInventoriesResponse, + SetInventoryMetadata, + SetInventoryRequest, + SetInventoryResponse, + UpdateProductRequest, +) +from .promotion import ( + Promotion, +) +from .purge_config import ( + PurgeMetadata, + PurgeUserEventsRequest, + PurgeUserEventsResponse, +) +from .search_service import ( + SearchRequest, + SearchResponse, +) +from .user_event import ( + CompletionDetail, + ProductDetail, + PurchaseTransaction, + UserEvent, +) +from .user_event_service import ( + CollectUserEventRequest, + RejoinUserEventsMetadata, + RejoinUserEventsRequest, + RejoinUserEventsResponse, + WriteUserEventRequest, +) + +__all__ = ( + 'Catalog', + 'ProductLevelConfig', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'SetDefaultBranchRequest', + 'UpdateCatalogRequest', + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py new file mode 100644 index 00000000..47a372fb --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'ProductLevelConfig', + 'Catalog', + }, +) + + +class ProductLevelConfig(proto.Message): + r"""Configures what level the product should be uploaded with + regards to how users will be send events and how predictions + will be made. + + Attributes: + ingestion_product_type (str): + The type of [Product][google.cloud.retail.v2.Product]s + allowed to be ingested into the catalog. Acceptable values + are: + + - ``primary`` (default): You can ingest + [Product][google.cloud.retail.v2.Product]s of all types. + When ingesting a + [Product][google.cloud.retail.v2.Product], its type will + default to + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + if unset. + - ``variant`` (incompatible with Retail Search): You can + only ingest + [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s. This means + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] + cannot be empty. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``variant`` and + [merchant_center_product_id_field][google.cloud.retail.v2.ProductLevelConfig.merchant_center_product_id_field] + is ``itemGroupId``, an INVALID_ARGUMENT error is returned. + + See `Product + levels `__ + for more details. + merchant_center_product_id_field (str): + Which field of `Merchant Center + Product `__ + should be imported as + [Product.id][google.cloud.retail.v2.Product.id]. Acceptable + values are: + + - ``offerId`` (default): Import ``offerId`` as the product + ID. + - ``itemGroupId``: Import ``itemGroupId`` as the product + ID. Notice that Retail API will choose one item from the + ones with the same ``itemGroupId``, and use it to + represent the item group. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``itemGroupId`` and + [ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] + is ``variant``, an INVALID_ARGUMENT error is returned. + + See `Product + levels `__ + for more details. + """ + + ingestion_product_type = proto.Field( + proto.STRING, + number=1, + ) + merchant_center_product_id_field = proto.Field( + proto.STRING, + number=2, + ) + + +class Catalog(proto.Message): + r"""The catalog configuration. + + Attributes: + name (str): + Required. Immutable. The fully qualified + resource name of the catalog. + display_name (str): + Required. Immutable. The catalog display name. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + product_level_config (google.cloud.retail_v2.types.ProductLevelConfig): + Required. The product level configuration. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + product_level_config = proto.Field( + proto.MESSAGE, + number=4, + message='ProductLevelConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py new file mode 100644 index 00000000..721ef858 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'UpdateCatalogRequest', + 'SetDefaultBranchRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + }, +) + + +class ListCatalogsRequest(proto.Message): + r"""Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + + Attributes: + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2.Catalog]s under this + location, regardless of whether or not this location exists, + a PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of [Catalog][google.cloud.retail.v2.Catalog]s + to return. If unspecified, defaults to 50. The maximum + allowed value is 1000. Values above 1000 will be coerced to + 1000. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [ListCatalogsResponse.next_page_token][google.cloud.retail.v2.ListCatalogsResponse.next_page_token], + received from a previous + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCatalogsResponse(proto.Message): + r"""Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + + Attributes: + catalogs (Sequence[google.cloud.retail_v2.types.Catalog]): + All the customer's + [Catalog][google.cloud.retail.v2.Catalog]s. + next_page_token (str): + A token that can be sent as + [ListCatalogsRequest.page_token][google.cloud.retail.v2.ListCatalogsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + catalogs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateCatalogRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] + method. + + Attributes: + catalog (google.cloud.retail_v2.types.Catalog): + Required. The [Catalog][google.cloud.retail.v2.Catalog] to + update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2.Catalog], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2.Catalog] 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 + [Catalog][google.cloud.retail.v2.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + catalog = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class SetDefaultBranchRequest(proto.Message): + r"""Request message to set a specified branch as new default_branch. + + Attributes: + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + branch_id (str): + The final component of the resource name of a branch. + + This field must be one of "0", "1" or "2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If there are no sufficient active products in the targeted + branch and + [force][google.cloud.retail.v2.SetDefaultBranchRequest.force] + is not set, a FAILED_PRECONDITION error is returned. + note (str): + Some note on this request, this can be retrieved by + [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch] + before next valid default branch set occurs. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + force (bool): + If set to true, it permits switching to a branch with + [branch_id][google.cloud.retail.v2.SetDefaultBranchRequest.branch_id] + even if it has no sufficient active products. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + force = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetDefaultBranchRequest(proto.Message): + r"""Request message to show which branch is currently the default + branch. + + Attributes: + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDefaultBranchResponse(proto.Message): + r"""Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. + + Attributes: + branch (str): + Full resource name of the branch id currently + set as default branch. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when this branch is set to default. + note (str): + This corresponds to + [SetDefaultBranchRequest.note][google.cloud.retail.v2.SetDefaultBranchRequest.note] + field, when this branch was set as default. + """ + + branch = proto.Field( + proto.STRING, + number=1, + ) + set_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py new file mode 100644 index 00000000..fe50745a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py @@ -0,0 +1,736 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'LocalInventory', + }, +) + + +class Audience(proto.Message): + r"""An intended audience of the + [Product][google.cloud.retail.v2.Product] for whom it's sold. + + Attributes: + genders (Sequence[str]): + The genders of the audience. Strongly encouraged to use the + standard values: "male", "female", "unisex". + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `gender `__. + Schema.org property + `Product.audience.suggestedGender `__. + age_groups (Sequence[str]): + The age groups of the audience. Strongly encouraged to use + the standard values: "newborn" (up to 3 months old), + "infant" (3–12 months old), "toddler" (1–5 years old), + "kids" (5–13 years old), "adult" (typically teens or older). + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `age_group `__. + Schema.org property + `Product.audience.suggestedMinAge `__ + and + `Product.audience.suggestedMaxAge `__. + """ + + genders = proto.RepeatedField( + proto.STRING, + number=1, + ) + age_groups = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class ColorInfo(proto.Message): + r"""The color information of a + [Product][google.cloud.retail.v2.Product]. + + Attributes: + color_families (Sequence[str]): + The standard color families. Strongly recommended to use the + following standard color groups: "Red", "Pink", "Orange", + "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", + "White", "Gray", "Black" and "Mixed". Normally it is + expected to have only 1 color family. May consider using + single "Mixed" instead of multiple values. + + A maximum of 5 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + colors (Sequence[str]): + The color display names, which may be different from + standard color family names, such as the color aliases used + in the website frontend. Normally it is expected to have + only 1 color. May consider using single "Mixed" instead of + multiple values. + + A maximum of 25 colors are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + """ + + color_families = proto.RepeatedField( + proto.STRING, + number=1, + ) + colors = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in + [Product][google.cloud.retail.v2.Product]. + + Attributes: + text (Sequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an INVALID_ARGUMENT + error is returned. + + Exactly one of + [text][google.cloud.retail.v2.CustomAttribute.text] or + [numbers][google.cloud.retail.v2.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + numbers (Sequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [text][google.cloud.retail.v2.CustomAttribute.text] or + [numbers][google.cloud.retail.v2.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + searchable (bool): + This field is normally ignored unless + [AttributesConfig.attribute_config_level][] of the + [Catalog][google.cloud.retail.v2.Catalog] is set to the + deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For + information about product-level attribute configuration, see + `Configuration + modes `__. + If true, custom attribute values are searchable by text + queries in + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2.UserEvent]. + + Only set if type + [text][google.cloud.retail.v2.CustomAttribute.text] is set. + Otherwise, a INVALID_ARGUMENT error is returned. + + This field is a member of `oneof`_ ``_searchable``. + indexable (bool): + This field is normally ignored unless + [AttributesConfig.attribute_config_level][] of the + [Catalog][google.cloud.retail.v2.Catalog] is set to the + deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For + information about product-level attribute configuration, see + `Configuration + modes `__. + If true, custom attribute values are indexed, so that they + can be filtered, faceted or boosted in + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2.UserEvent]. + + See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter], + [SearchRequest.facet_specs][google.cloud.retail.v2.SearchRequest.facet_specs] + and + [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] + for more details. + + This field is a member of `oneof`_ ``_indexable``. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + searchable = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + indexable = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + +class FulfillmentInfo(proto.Message): + r"""Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + Attributes: + type_ (str): + The fulfillment type, including commonly used types (such as + pickup in store and same day delivery), and custom types. + Customers have to map custom types to their display names + before rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + place_ids (Sequence[str]): + The IDs for this + [type][google.cloud.retail.v2.FulfillmentInfo.type], such as + the store IDs for + [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2.FulfillmentInfo.type] + or the region IDs for + [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2.FulfillmentInfo.type]. + + A maximum of 3000 values are allowed. Each value must be a + string with a length limit of 30 characters, matching the + pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". + Otherwise, an INVALID_ARGUMENT error is returned. + """ + + type_ = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class Image(proto.Message): + r"""[Product][google.cloud.retail.v2.Product] image. Recommendations AI + and Retail Search do not use product images to improve prediction + and search results. However, product images can be returned in + results, and are shown in prediction or search previews in the + console. + + Attributes: + uri (str): + Required. URI of the image. + + This field must be a valid UTF-8 encoded URI with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + height (int): + Height of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + width (int): + Width of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + height = proto.Field( + proto.INT32, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + + +class Interval(proto.Message): + r"""A floating point interval. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum = proto.Field( + proto.DOUBLE, + number=1, + oneof='min', + ) + exclusive_minimum = proto.Field( + proto.DOUBLE, + number=2, + oneof='min', + ) + maximum = proto.Field( + proto.DOUBLE, + number=3, + oneof='max', + ) + exclusive_maximum = proto.Field( + proto.DOUBLE, + number=4, + oneof='max', + ) + + +class PriceInfo(proto.Message): + r"""The price information of a + [Product][google.cloud.retail.v2.Product]. + + Attributes: + currency_code (str): + The 3-letter currency code defined in `ISO + 4217 `__. + + If this field is an unrecognizable currency code, an + INVALID_ARGUMENT error is returned. + + The + [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s with the same + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] + must share the same + [currency_code][google.cloud.retail.v2.PriceInfo.currency_code]. + Otherwise, a FAILED_PRECONDITION error is returned. + price (float): + Price of the product. + + Google Merchant Center property + `price `__. + Schema.org property + `Offer.price `__. + original_price (float): + Price of the product without any discount. If zero, by + default set to be the + [price][google.cloud.retail.v2.PriceInfo.price]. If set, + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + should be greater than or equal to + [price][google.cloud.retail.v2.PriceInfo.price], otherwise + an INVALID_ARGUMENT error is thrown. + cost (float): + The costs associated with the sale of a particular product. + Used for gross profit reporting. + + - Profit = [price][google.cloud.retail.v2.PriceInfo.price] + - [cost][google.cloud.retail.v2.PriceInfo.cost] + + Google Merchant Center property + `cost_of_goods_sold `__. + price_effective_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2.PriceInfo.price] starts to be + effective. This can be set as a future timestamp, and the + [price][google.cloud.retail.v2.PriceInfo.price] is only used + for search after + [price_effective_time][google.cloud.retail.v2.PriceInfo.price_effective_time]. + If so, the + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + is used before + [price_effective_time][google.cloud.retail.v2.PriceInfo.price_effective_time]. + + Do not set if + [price][google.cloud.retail.v2.PriceInfo.price] is always + effective because it will cause additional latency during + search. + price_expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2.PriceInfo.price] stops to be + effective. The + [price][google.cloud.retail.v2.PriceInfo.price] is used for + search before + [price_expire_time][google.cloud.retail.v2.PriceInfo.price_expire_time]. + If this field is set, the + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + is used after + [price_expire_time][google.cloud.retail.v2.PriceInfo.price_expire_time]. + + Do not set if + [price][google.cloud.retail.v2.PriceInfo.price] is always + effective because it will cause additional latency during + search. + price_range (google.cloud.retail_v2.types.PriceInfo.PriceRange): + Output only. The price range of all the child + [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s grouped together + on the + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]. Only populated + for + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]. + Do not set this field in API requests. + """ + + class PriceRange(proto.Message): + r"""The price range of all + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. + + Attributes: + price (google.cloud.retail_v2.types.Interval): + The inclusive + [Product.pricing_info.price][google.cloud.retail.v2.PriceInfo.price] + interval of all + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. + original_price (google.cloud.retail_v2.types.Interval): + The inclusive + [Product.pricing_info.original_price][google.cloud.retail.v2.PriceInfo.original_price] + internal of all + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. + """ + + price = proto.Field( + proto.MESSAGE, + number=1, + message='Interval', + ) + original_price = proto.Field( + proto.MESSAGE, + number=2, + message='Interval', + ) + + currency_code = proto.Field( + proto.STRING, + number=1, + ) + price = proto.Field( + proto.FLOAT, + number=2, + ) + original_price = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + price_effective_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + price_expire_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + price_range = proto.Field( + proto.MESSAGE, + number=7, + message=PriceRange, + ) + + +class Rating(proto.Message): + r"""The rating of a [Product][google.cloud.retail.v2.Product]. + + Attributes: + rating_count (int): + The total number of ratings. This value is independent of + the value of + [rating_histogram][google.cloud.retail.v2.Rating.rating_histogram]. + + This value must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + average_rating (float): + The average rating of the + [Product][google.cloud.retail.v2.Product]. + + The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT + error is returned. + rating_histogram (Sequence[int]): + List of rating counts per rating value (index = rating - 1). + The list is empty if there is no rating. If the list is + non-empty, its size is always 5. Otherwise, an + INVALID_ARGUMENT error is returned. + + For example, [41, 14, 13, 47, 303]. It means that the + [Product][google.cloud.retail.v2.Product] got 41 ratings + with 1 star, 14 ratings with 2 star, and so on. + """ + + rating_count = proto.Field( + proto.INT32, + number=1, + ) + average_rating = proto.Field( + proto.FLOAT, + number=2, + ) + rating_histogram = proto.RepeatedField( + proto.INT32, + number=3, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. Don't set for + anonymous users. + + Always use a hashed value for this ID. + + Don't set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + ip_address (str): + The end user's IP address. This field is used to extract + location information for personalization. + + This field must be either an IPv4 address (e.g. + "104.133.9.80") or an IPv6 address (e.g. + "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an + INVALID_ARGUMENT error is returned. + + This should not be set when: + + - setting + [SearchRequest.user_info][google.cloud.retail.v2.SearchRequest.user_info]. + - using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request] + is set. + user_agent (str): + User agent as included in the HTTP header. Required for + getting + [SearchResponse.sponsored_results][google.cloud.retail.v2.SearchResponse.sponsored_results]. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request] + is set. + direct_user_request (bool): + True if the request is made directly from the end user, in + which case the + [ip_address][google.cloud.retail.v2.UserInfo.ip_address] and + [user_agent][google.cloud.retail.v2.UserInfo.user_agent] can + be populated from the HTTP request. This flag should be set + only if the API request is made directly from the end user + such as a mobile app (and not if a gateway or a server is + processing and pushing the user events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent]. + """ + + user_id = proto.Field( + proto.STRING, + number=1, + ) + ip_address = proto.Field( + proto.STRING, + number=2, + ) + user_agent = proto.Field( + proto.STRING, + number=3, + ) + direct_user_request = proto.Field( + proto.BOOL, + number=4, + ) + + +class LocalInventory(proto.Message): + r"""The inventory information at a place (e.g. a store) + identified by a place ID. + + Attributes: + place_id (str): + The place ID for the current set of inventory + information. + price_info (google.cloud.retail_v2.types.PriceInfo): + Product price and cost information. + + Google Merchant Center property + `price `__. + attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): + Additional local inventory attributes, for example, store + name, promotion tags, etc. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - At most 30 attributes are allowed. + - The key must be a UTF-8 encoded string with a length + limit of 32 characters. + - The key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis + or KEY_1_LIKE_THIS. + - The attribute values must be of the same type (text or + number). + - Only 1 value is allowed for each attribute. + - For text values, the length limit is 256 UTF-8 + characters. + - The attribute does not support search. The ``searchable`` + field should be unset or set to false. + - The max summed total bytes of custom attribute keys and + values per product is 5MiB. + fulfillment_types (Sequence[str]): + Input only. Supported fulfillment types. Valid fulfillment + type values include commonly used types (such as pickup in + store and same day delivery), and custom types. Customers + have to map custom types to their display names before + rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + All the elements must be distinct. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + place_id = proto.Field( + proto.STRING, + number=1, + ) + price_info = proto.Field( + proto.MESSAGE, + number=2, + message='PriceInfo', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='CustomAttribute', + ) + fulfillment_types = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py new file mode 100644 index 00000000..421cc1c0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'CompleteQueryRequest', + 'CompleteQueryResponse', + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Auto-complete parameters. + + Attributes: + catalog (str): + Required. Catalog for which the completion is performed. + + Full resource name of catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + query (str): + Required. The query used to generate + suggestions. + The maximum number of allowed characters is 255. + visitor_id (str): + Required field. A unique identifier for tracking visitors. + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + language_codes (Sequence[str]): + The language filters applied to the output suggestions. If + set, it should contain the language of the query. If not + set, suggestions are returned without considering language + restrictions. This is the BCP-47 language code, such as + "en-US" or "sr-Latn". For more information, see `Tags for + Identifying + Languages `__. The + maximum number of language codes is 3. + device_type (str): + The device type context for completion suggestions. It is + useful to apply different suggestions on different device + types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the + suggestions are across all device types. + + Supported formats: + + - ``UNKNOWN_DEVICE_TYPE`` + + - ``DESKTOP`` + + - ``MOBILE`` + + - A customized string starts with ``OTHER_``, e.g. + ``OTHER_IPHONE``. + dataset (str): + Determines which dataset to use for fetching completion. + "user-data" will use the imported dataset through + [CompletionService.ImportCompletionData][google.cloud.retail.v2.CompletionService.ImportCompletionData]. + "cloud-retail" will use the dataset generated by cloud + retail based on user events. If leave empty, it will use the + "user-data". + + Current supported values: + + - user-data + + - cloud-retail: This option requires enabling auto-learning + function first. See + `guidelines `__. + max_suggestions (int): + Completion max suggestions. If left unset or set to 0, then + will fallback to the configured value + [CompletionConfig.max_suggestions][]. + + The maximum allowed max suggestions is 20. If it is set + higher, it will be capped by 20. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + visitor_id = proto.Field( + proto.STRING, + number=7, + ) + language_codes = proto.RepeatedField( + proto.STRING, + number=3, + ) + device_type = proto.Field( + proto.STRING, + number=4, + ) + dataset = proto.Field( + proto.STRING, + number=6, + ) + max_suggestions = proto.Field( + proto.INT32, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response of the auto-complete query. + + Attributes: + completion_results (Sequence[google.cloud.retail_v2.types.CompleteQueryResponse.CompletionResult]): + Results of the matching suggestions. The + result list is ordered and the first result is + top suggestion. + attribution_token (str): + A unique complete token. This should be included in the + [UserEvent.completion_detail][google.cloud.retail.v2.UserEvent.completion_detail] + for search events resulting from this completion, which + enables accurate attribution of complete model performance. + recent_search_results (Sequence[google.cloud.retail_v2.types.CompleteQueryResponse.RecentSearchResult]): + Matched recent searches of this user. The maximum number of + recent searches is 10. This field is a restricted feature. + Contact Retail Search support team if you are interested in + enabling it. + + This feature is only available when + [CompleteQueryRequest.visitor_id][google.cloud.retail.v2.CompleteQueryRequest.visitor_id] + field is set and + [UserEvent][google.cloud.retail.v2.UserEvent] is imported. + The recent searches satisfy the follow rules: + + - They are ordered from latest to oldest. + + - They are matched with + [CompleteQueryRequest.query][google.cloud.retail.v2.CompleteQueryRequest.query] + case insensitively. + + - They are transformed to lower cases. + + - They are UTF-8 safe. + + Recent searches are deduplicated. More recent searches will + be reserved when duplication happens. + """ + + class CompletionResult(proto.Message): + r"""Resource that represents completion results. + + Attributes: + suggestion (str): + The suggestion for the query. + attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): + Custom attributes for the suggestion term. + + - For "user-data", the attributes are additional custom + attributes ingested through BigQuery. + + - For "cloud-retail", the attributes are product attributes + generated by Cloud Retail. This is an experimental + feature. Contact Retail Search support team if you are + interested in enabling it. + """ + + suggestion = proto.Field( + proto.STRING, + number=1, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=common.CustomAttribute, + ) + + class RecentSearchResult(proto.Message): + r"""Recent search of this user. + + Attributes: + recent_search (str): + The recent search query. + """ + + recent_search = proto.Field( + proto.STRING, + number=1, + ) + + completion_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=CompletionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + recent_search_results = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=RecentSearchResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py new file mode 100644 index 00000000..983e15df --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py @@ -0,0 +1,697 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import user_event +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'GcsSource', + 'BigQuerySource', + 'ProductInlineSource', + 'UserEventInlineSource', + 'ImportErrorsConfig', + 'ImportProductsRequest', + 'ImportUserEventsRequest', + 'ImportCompletionDataRequest', + 'ProductInputConfig', + 'UserEventInputConfig', + 'CompletionDataInputConfig', + 'ImportMetadata', + 'ImportProductsResponse', + 'ImportUserEventsResponse', + 'UserEventImportSummary', + 'ImportCompletionDataResponse', + }, +) + + +class GcsSource(proto.Message): + r"""Google Cloud Storage location for input content. + format. + + Attributes: + input_uris (Sequence[str]): + Required. Google Cloud Storage URIs to input files. URI can + be up to 2000 characters long. URIs can match the full + object path (for example, + ``gs://bucket/directory/object.json``) or a pattern matching + one or more files, such as ``gs://bucket/directory/*.json``. + A request can contain at most 100 files, and each file can + be up to 2 GB. See `Importing product + information `__ + for the expected file format and setup instructions. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2.Product] per line. Each + product must have a valid + [Product.id][google.cloud.retail.v2.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2.UserEvent] per line. + - ``user_event_ga360``: Using + https://support.google.com/analytics/answer/3437719. + + Supported values for control imports: + + - 'control' (default): One JSON [Control][] per line. + + Supported values for catalog attribute imports: + + - 'catalog_attribute' (default): One CSV + [CatalogAttribute][] per line. + """ + + input_uris = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID (can be project # or ID) that + the BigQuery source is in with a length limit of + 128 characters. If not specified, inherits the + project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2.Product] per line. Each + product must have a valid + [Product.id][google.cloud.retail.v2.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2.UserEvent] per line. + - ``user_event_ga360``: The schema is available here: + https://support.google.com/analytics/answer/3437719. + - ``user_event_ga4``: This feature is in private preview. + Please contact the support team for importing Google + Analytics 4 events. The schema is available here: + https://support.google.com/analytics/answer/7029846. + + Supported values for auto-completion imports: + + - ``suggestions`` (default): One JSON completion suggestion + per line. + - ``denylist``: One JSON deny suggestion per line. + - ``allowlist``: One JSON allow suggestion per line. + """ + + partition_date = proto.Field( + proto.MESSAGE, + number=6, + oneof='partition', + message=date_pb2.Date, + ) + project_id = proto.Field( + proto.STRING, + number=5, + ) + dataset_id = proto.Field( + proto.STRING, + number=1, + ) + table_id = proto.Field( + proto.STRING, + number=2, + ) + gcs_staging_dir = proto.Field( + proto.STRING, + number=3, + ) + data_schema = proto.Field( + proto.STRING, + number=4, + ) + + +class ProductInlineSource(proto.Message): + r"""The inline source for the input config for ImportProducts + method. + + Attributes: + products (Sequence[google.cloud.retail_v2.types.Product]): + Required. A list of products to update/create. Each product + must have a valid + [Product.id][google.cloud.retail.v2.Product.id]. Recommended + max of 100 items. + """ + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=product.Product, + ) + + +class UserEventInlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (Sequence[google.cloud.retail_v2.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + +class ImportErrorsConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage prefix for import errors. This must be + an empty, existing Cloud Storage directory. Import errors + will be written to sharded files in this directory, one per + line, as a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportProductsRequest(proto.Message): + r"""Request message for Import methods. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` + + If no updateMask is specified, requires products.create + permission. If updateMask is specified, requires + products.update permission. + request_id (str): + Deprecated. This field has no effect. + input_config (google.cloud.retail_v2.types.ProductInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported 'products' to update. If not set, will + by default update all fields. + reconciliation_mode (google.cloud.retail_v2.types.ImportProductsRequest.ReconciliationMode): + The mode of reconciliation between existing products and the + products to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. + notification_pubsub_topic (str): + Full Pub/Sub topic name for receiving notification. If this + field is set, when the import is finished, a notification + will be sent to specified Pub/Sub topic. The message data + will be JSON string of a + [Operation][google.longrunning.Operation]. + + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. It has to be within + the same project as + [ImportProductsRequest.parent][google.cloud.retail.v2.ImportProductsRequest.parent]. + Make sure that both + ``cloud-retail-customer-data-access@system.gserviceaccount.com`` + and + ``service-@gcp-sa-retail.iam.gserviceaccount.com`` + have the ``pubsub.topics.publish`` IAM permission on the + topic. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + """ + class ReconciliationMode(proto.Enum): + r"""Indicates how imported products are reconciled with the + existing products created or imported before. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + request_id = proto.Field( + proto.STRING, + number=6, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='ProductInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + reconciliation_mode = proto.Field( + proto.ENUM, + number=5, + enum=ReconciliationMode, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=7, + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + input_config (google.cloud.retail_v2.types.UserEventInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='UserEventInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + + +class ImportCompletionDataRequest(proto.Message): + r"""Request message for ImportCompletionData methods. + + Attributes: + parent (str): + Required. The catalog which the suggestions dataset belongs + to. + + Format: + ``projects/1234/locations/global/catalogs/default_catalog``. + input_config (google.cloud.retail_v2.types.CompletionDataInputConfig): + Required. The desired input location of the + data. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='CompletionDataInputConfig', + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=3, + ) + + +class ProductInputConfig(proto.Message): + r"""The input config source for products. + + 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: + product_inline_source (google.cloud.retail_v2.types.ProductInlineSource): + The Inline source for the input content for + products. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2.types.GcsSource): + Google Cloud Storage location for the input + content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + product_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='ProductInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class UserEventInputConfig(proto.Message): + r"""The input config source for user events. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user_event_inline_source (google.cloud.retail_v2.types.UserEventInlineSource): + Required. The Inline source for the input + content for UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2.types.GcsSource): + Required. Google Cloud Storage location for + the input content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2.types.BigQuerySource): + Required. BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + user_event_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='UserEventInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class CompletionDataInputConfig(proto.Message): + r"""The input config source for completion data. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + big_query_source (google.cloud.retail_v2.types.BigQuerySource): + Required. BigQuery input source. + Add the IAM permission "BigQuery Data Viewer" + for + cloud-retail-customer-data-access@system.gserviceaccount.com + before using this feature otherwise an error is + thrown. + + This field is a member of `oneof`_ ``source``. + """ + + big_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='BigQuerySource', + ) + + +class ImportMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + request_id (str): + Deprecated. This field is never set. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=3, + ) + failure_count = proto.Field( + proto.INT64, + number=4, + ) + request_id = proto.Field( + proto.STRING, + number=5, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=6, + ) + + +class ImportProductsResponse(proto.Message): + r"""Response of the + [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + import_summary (google.cloud.retail_v2.types.UserEventImportSummary): + Aggregated statistics of user event import + status. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + import_summary = proto.Field( + proto.MESSAGE, + number=3, + message='UserEventImportSummary', + ) + + +class UserEventImportSummary(proto.Message): + r"""A summary of import result. The UserEventImportSummary + summarizes the import status for user events. + + Attributes: + joined_events_count (int): + Count of user events imported with complete + existing catalog information. + unjoined_events_count (int): + Count of user events imported, but with + catalog information not found in the imported + catalog. + """ + + joined_events_count = proto.Field( + proto.INT64, + number=1, + ) + unjoined_events_count = proto.Field( + proto.INT64, + number=2, + ) + + +class ImportCompletionDataResponse(proto.Message): + r"""Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. + 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 (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py new file mode 100644 index 00000000..68e8c74b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py @@ -0,0 +1,275 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import user_event as gcr_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'PredictRequest', + 'PredictResponse', + }, +) + + +class PredictRequest(proto.Message): + r"""Request message for Predict method. + + Attributes: + placement (str): + Required. Full resource name of the format: + {name=projects/*/locations/global/catalogs/default_catalog/placements/*} + The ID of the Recommendations AI placement. Before you can + request predictions from your model, you must create at + least one placement for it. For more information, see + `Managing + placements `__. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements + user_event (google.cloud.retail_v2.types.UserEvent): + Required. Context about the user, what they are looking at + and what action they took to trigger the predict request. + Note that this user event detail won't be ingested to + userEvent logs. Thus, a separate userEvent write request is + required for event logging. + + Don't set + [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] + or + [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] + to the same fixed ID for different users. If you are trying + to receive non-personalized recommendations (not + recommended; this can negatively impact model performance), + instead set + [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] + to a random unique ID and leave + [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] + unset. + page_size (int): + Maximum number of results to return per page. + Set this property to the number of prediction + results needed. If zero, the service will choose + a reasonable default. The maximum allowed value + is 100. Values above 100 will be coerced to 100. + page_token (str): + The previous PredictResponse.next_page_token. + filter (str): + Filter for restricting prediction results with a length + limit of 5,000 characters. Accepts values for tags and the + ``filterOutOfStockItems`` flag. + + - Tag expressions. Restricts predictions to products that + match all of the specified tags. Boolean operators ``OR`` + and ``NOT`` are supported if the expression is enclosed + in parentheses, and must be separated from the tag values + by a space. ``-"tagA"`` is also supported and is + equivalent to ``NOT "tagA"``. Tag values must be double + quoted UTF-8 encoded strings with a size limit of 1,000 + characters. + + Note: "Recently viewed" models don't support tag + filtering at the moment. + + - filterOutOfStockItems. Restricts predictions to products + that do not have a stockState value of OUT_OF_STOCK. + + Examples: + + - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT + "promotional") + - filterOutOfStockItems tag=(-"promotional") + - filterOutOfStockItems + + If your filter blocks all prediction results, the API will + return generic (unfiltered) popular products. If you only + want results strictly matching the filters, set + ``strictFiltering`` to True in ``PredictRequest.params`` to + receive empty results instead. Note that the API will never + return items with storageStatus of "EXPIRED" or "DELETED" + regardless of filter choices. + validate_only (bool): + Use validate only mode for this prediction + query. If set to true, a dummy model will be + used that returns arbitrary products. Note that + the validate only mode should only be used for + testing the API, or if the model is not ready. + params (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific parameters for the predictions. + + Allowed values: + + - ``returnProduct``: Boolean. If set to true, the + associated product object will be returned in the + ``results.metadata`` field in the prediction response. + - ``returnScore``: Boolean. If set to true, the prediction + 'score' corresponding to each returned product will be + set in the ``results.metadata`` field in the prediction + response. The given 'score' indicates the probability of + an product being clicked/purchased given the user's + context and history. + - ``strictFiltering``: Boolean. True by default. If set to + false, the service will return generic (unfiltered) + popular products instead of empty if your filter blocks + all prediction results. + - ``priceRerankLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of + {'no-price-reranking', 'low-price-reranking', + 'medium-price-reranking', 'high-price-reranking'}. This + gives request-level control and adjusts prediction + results based on product price. + - ``diversityLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of {'no-diversity', + 'low-diversity', 'medium-diversity', 'high-diversity', + 'auto-diversity'}. This gives request-level control and + adjusts prediction results based on product category. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + placement = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + filter = proto.Field( + proto.STRING, + number=5, + ) + validate_only = proto.Field( + proto.BOOL, + number=6, + ) + params = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class PredictResponse(proto.Message): + r"""Response message for predict method. + + Attributes: + results (Sequence[google.cloud.retail_v2.types.PredictResponse.PredictionResult]): + A list of recommended products. The order + represents the ranking (from the most relevant + product to the least). + attribution_token (str): + A unique attribution token. This should be included in the + [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting + from this recommendation, which enables accurate attribution + of recommendation model performance. + missing_ids (Sequence[str]): + IDs of products in the request that were + missing from the inventory. + validate_only (bool): + True if the validateOnly property was set in + the request. + """ + + class PredictionResult(proto.Message): + r"""PredictionResult represents the recommendation prediction + results. + + Attributes: + id (str): + ID of the recommended product + metadata (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional product metadata / annotations. + + Possible values: + + - ``product``: JSON representation of the product. Is set + if ``returnProduct`` is set to true in + ``PredictRequest.params``. + - ``score``: Prediction score in double value. Is set if + ``returnScore`` is set to true in + ``PredictRequest.params``. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + metadata = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=PredictionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + missing_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py new file mode 100644 index 00000000..bff41d83 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py @@ -0,0 +1,701 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'Product', + }, +) + + +class Product(proto.Message): + r"""Product captures all metadata information of items to be + recommended or searched. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this product becomes unavailable for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + + If it is set, the [Product][google.cloud.retail.v2.Product] + is not available for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + after + [expire_time][google.cloud.retail.v2.Product.expire_time]. + However, the product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + [expire_time][google.cloud.retail.v2.Product.expire_time] + must be later than + [available_time][google.cloud.retail.v2.Product.available_time] + and + [publish_time][google.cloud.retail.v2.Product.publish_time], + otherwise an INVALID_ARGUMENT error is thrown. + + Corresponding properties: Google Merchant Center property + `expiration_date `__. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Input only. The TTL (time to live) of the product. + + If it is set, it must be a non-negative value, and + [expire_time][google.cloud.retail.v2.Product.expire_time] is + set as current timestamp plus + [ttl][google.cloud.retail.v2.Product.ttl]. The derived + [expire_time][google.cloud.retail.v2.Product.expire_time] is + returned in the output and + [ttl][google.cloud.retail.v2.Product.ttl] is left blank when + retrieving the [Product][google.cloud.retail.v2.Product]. + + If it is set, the product is not available for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + after current timestamp plus + [ttl][google.cloud.retail.v2.Product.ttl]. However, the + product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This field is a member of `oneof`_ ``expiration``. + name (str): + Immutable. Full resource name of the product, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. + id (str): + Immutable. [Product][google.cloud.retail.v2.Product] + identifier, which is the final component of + [name][google.cloud.retail.v2.Product.name]. For example, + this field is "id_1", if + [name][google.cloud.retail.v2.Product.name] is + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `id `__. + Schema.org property + `Product.sku `__. + type_ (google.cloud.retail_v2.types.Product.Type): + Immutable. The type of the product. Default to + [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] + if unset. + primary_product_id (str): + Variant group identifier. Must be an + [id][google.cloud.retail.v2.Product.id], with the same + parent branch with this product. Otherwise, an error is + thrown. + + For + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]s, this field can + only be empty or set to the same value as + [id][google.cloud.retail.v2.Product.id]. + + For VARIANT [Product][google.cloud.retail.v2.Product]s, this + field cannot be empty. A maximum of 2,000 products are + allowed to share the same + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `item_group_id `__. + Schema.org property + `Product.inProductGroupWithID `__. + collection_member_ids (Sequence[str]): + The [id][google.cloud.retail.v2.Product.id] of the + collection members when + [type][google.cloud.retail.v2.Product.type] is + [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]. + + Non-existent product ids are allowed. The + [type][google.cloud.retail.v2.Product.type] of the members + must be either + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + or + [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + otherwise and INVALID_ARGUMENT error is thrown. Should not + set it for other types. A maximum of 1000 values are + allowed. Otherwise, an INVALID_ARGUMENT error is return. + gtin (str): + The Global Trade Item Number (GTIN) of the product. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This field must be a Unigram. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `gtin `__. + Schema.org property + `Product.isbn `__, + `Product.gtin8 `__, + `Product.gtin12 `__, + `Product.gtin13 `__, or + `Product.gtin14 `__. + + If the value is not a valid GTIN, an INVALID_ARGUMENT error + is returned. + categories (Sequence[str]): + Product categories. This field is repeated for supporting + one product belonging to several parallel categories. + Strongly recommended using the full path for better search / + recommendation quality. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + For example, if a shoes product belongs to both ["Shoes & + Accessories" -> "Shoes"] and ["Sports & Fitness" -> + "Athletic Clothing" -> "Shoes"], it could be represented as: + + :: + + "categories": [ + "Shoes & Accessories > Shoes", + "Sports & Fitness > Athletic Clothing > Shoes" + ] + + Must be set for + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] otherwise an + INVALID_ARGUMENT error is returned. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2.Product]. Empty values are + not allowed. Each value must be a UTF-8 encoded string with + a length limit of 5,000 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `google_product_category `__. + Schema.org property [Product.category] + (https://schema.org/category). + title (str): + Required. Product title. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `title `__. + Schema.org property + `Product.name `__. + brands (Sequence[str]): + The brands of the product. + + A maximum of 30 brands are allowed. Each brand must be a + UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `brand `__. + Schema.org property + `Product.brand `__. + description (str): + Product description. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `description `__. + Schema.org property + `Product.description `__. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. + + For product prediction, this field is ignored and the model + automatically detects the text language. The + [Product][google.cloud.retail.v2.Product] can include text + in different languages, but duplicating + [Product][google.cloud.retail.v2.Product]s to provide text + in multiple languages can result in degraded model + performance. + + For product search this field is in use. It defaults to + "en-US" if unset. + attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): + Highly encouraged. Extra product attributes to be included. + For example, for products, this could include the store + name, vendor, style, color, etc. These are very strong + signals for recommendation model, thus we highly recommend + providing the attributes here. + + Features that can take on one of a limited number of + possible values. Two types of features can be set are: + + Textual features. some examples would be the brand/maker of + a product, or country of a customer. Numerical features. + Some examples would be the height/weight of a product, or + age of a customer. + + For example: + ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - Max entries count: 200. + - The key must be a UTF-8 encoded string with a length + limit of 128 characters. + - For indexable attribute, the key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, + ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a + non-empty UTF-8 encoded string with a length limit of 256 + characters. + - For number attributes, at most 400 values are allowed. + tags (Sequence[str]): + Custom tags associated with the product. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2.Product]. This value must + be a UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This tag can be used for filtering recommendation results by + passing the tag as part of the + [PredictRequest.filter][google.cloud.retail.v2.PredictRequest.filter]. + + Corresponding properties: Google Merchant Center property + `custom_label_0–4 `__. + price_info (google.cloud.retail_v2.types.PriceInfo): + Product price and cost information. + + Corresponding properties: Google Merchant Center property + `price `__. + rating (google.cloud.retail_v2.types.Rating): + The rating of this product. + available_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this + [Product][google.cloud.retail.v2.Product] becomes available + for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + availability (google.cloud.retail_v2.types.Product.Availability): + The online availability of the + [Product][google.cloud.retail.v2.Product]. Default to + [Availability.IN_STOCK][google.cloud.retail.v2.Product.Availability.IN_STOCK]. + + Corresponding properties: Google Merchant Center property + `availability `__. + Schema.org property + `Offer.availability `__. + available_quantity (google.protobuf.wrappers_pb2.Int32Value): + The available quantity of the item. + fulfillment_info (Sequence[google.cloud.retail_v2.types.FulfillmentInfo]): + Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + All the elements must have distinct + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type]. + Otherwise, an INVALID_ARGUMENT error is returned. + uri (str): + Canonical URL directly linking to the product detail page. + + It is strongly recommended to provide a valid uri for the + product, otherwise the service performance could be + significantly degraded. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `link `__. + Schema.org property `Offer.url `__. + images (Sequence[google.cloud.retail_v2.types.Image]): + Product images for the product. We highly recommend putting + the main image first. + + A maximum of 300 images are allowed. + + Corresponding properties: Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + audience (google.cloud.retail_v2.types.Audience): + The target group associated with a given + audience (e.g. male, veterans, car owners, + musicians, etc.) of the product. + color_info (google.cloud.retail_v2.types.ColorInfo): + The color of the product. + + Corresponding properties: Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + sizes (Sequence[str]): + The size of the product. To represent different size systems + or size types, consider using this format: + [[[size_system:]size_type:]size_value]. + + For example, in "US:MENS:M", "US" represents size system; + "MENS" represents size type; "M" represents size value. In + "GIRLS:27", size system is empty; "GIRLS" represents size + type; "27" represents size value. In "32 inches", both size + system and size type are empty, while size value is "32 + inches". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2.Product]. Each value must + be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `size `__, + `size_type `__, + and + `size_system `__. + Schema.org property + `Product.size `__. + materials (Sequence[str]): + The material of the product. For example, "leather", + "wooden". + + A maximum of 20 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 200 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `material `__. + Schema.org property + `Product.material `__. + patterns (Sequence[str]): + The pattern or graphic print of the product. For example, + "striped", "polka dot", "paisley". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2.Product]. Each value must + be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `pattern `__. + Schema.org property + `Product.pattern `__. + conditions (Sequence[str]): + The condition of the product. Strongly encouraged to use the + standard values: "new", "refurbished", "used". + + A maximum of 1 value is allowed per + [Product][google.cloud.retail.v2.Product]. Each value must + be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `condition `__. + Schema.org property + `Offer.itemCondition `__. + promotions (Sequence[google.cloud.retail_v2.types.Promotion]): + The promotions applied to the product. A maximum of 10 + values are allowed per + [Product][google.cloud.retail.v2.Product]. Only + [Promotion.promotion_id][google.cloud.retail.v2.Promotion.promotion_id] + will be used, other fields will be ignored if set. + publish_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the product is published by the retailer + for the first time, which indicates the freshness of the + products. Note that this field is different from + [available_time][google.cloud.retail.v2.Product.available_time], + given it purely describes product freshness regardless of + when it is available on search and recommendation. + retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the + [Product][google.cloud.retail.v2.Product]s are returned in + [SearchResponse][google.cloud.retail.v2.SearchResponse]. + + Supported fields for all + [type][google.cloud.retail.v2.Product.type]s: + + - [audience][google.cloud.retail.v2.Product.audience] + - [availability][google.cloud.retail.v2.Product.availability] + - [brands][google.cloud.retail.v2.Product.brands] + - [color_info][google.cloud.retail.v2.Product.color_info] + - [conditions][google.cloud.retail.v2.Product.conditions] + - [gtin][google.cloud.retail.v2.Product.gtin] + - [materials][google.cloud.retail.v2.Product.materials] + - [name][google.cloud.retail.v2.Product.name] + - [patterns][google.cloud.retail.v2.Product.patterns] + - [price_info][google.cloud.retail.v2.Product.price_info] + - [rating][google.cloud.retail.v2.Product.rating] + - [sizes][google.cloud.retail.v2.Product.sizes] + - [title][google.cloud.retail.v2.Product.title] + - [uri][google.cloud.retail.v2.Product.uri] + + Supported fields only for + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]: + + - [categories][google.cloud.retail.v2.Product.categories] + - [description][google.cloud.retail.v2.Product.description] + - [images][google.cloud.retail.v2.Product.images] + + Supported fields only for + [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT]: + + - Only the first image in + [images][google.cloud.retail.v2.Product.images] + + To mark + [attributes][google.cloud.retail.v2.Product.attributes] as + retrievable, include paths of the form "attributes.key" + where "key" is the key of a custom attribute, as specified + in [attributes][google.cloud.retail.v2.Product.attributes]. + + For + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION], + the following fields are always returned in + [SearchResponse][google.cloud.retail.v2.SearchResponse] by + default: + + - [name][google.cloud.retail.v2.Product.name] + + For + [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT], + the following fields are always returned in by default: + + - [name][google.cloud.retail.v2.Product.name] + - [color_info][google.cloud.retail.v2.Product.color_info] + + The maximum number of paths is 30. Otherwise, an + INVALID_ARGUMENT error is returned. + + Note: Returning more fields in + [SearchResponse][google.cloud.retail.v2.SearchResponse] can + increase response payload size and serving latency. + variants (Sequence[google.cloud.retail_v2.types.Product]): + Output only. Product variants grouped together on primary + product which share similar product attributes. It's + automatically grouped by + [primary_product_id][google.cloud.retail.v2.Product.primary_product_id] + for all the product variants. Only populated for + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]. + Do not set this field in API requests. + """ + class Type(proto.Enum): + r"""The type of this product.""" + TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + VARIANT = 2 + COLLECTION = 3 + + class Availability(proto.Enum): + r"""Product availability. If this field is unspecified, the + product is assumed to be in stock. + """ + AVAILABILITY_UNSPECIFIED = 0 + IN_STOCK = 1 + OUT_OF_STOCK = 2 + PREORDER = 3 + BACKORDER = 4 + + expire_time = proto.Field( + proto.MESSAGE, + number=16, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl = proto.Field( + proto.MESSAGE, + number=17, + oneof='expiration', + message=duration_pb2.Duration, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + type_ = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + primary_product_id = proto.Field( + proto.STRING, + number=4, + ) + collection_member_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + gtin = proto.Field( + proto.STRING, + number=6, + ) + categories = proto.RepeatedField( + proto.STRING, + number=7, + ) + title = proto.Field( + proto.STRING, + number=8, + ) + brands = proto.RepeatedField( + proto.STRING, + number=9, + ) + description = proto.Field( + proto.STRING, + number=10, + ) + language_code = proto.Field( + proto.STRING, + number=11, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message=common.CustomAttribute, + ) + tags = proto.RepeatedField( + proto.STRING, + number=13, + ) + price_info = proto.Field( + proto.MESSAGE, + number=14, + message=common.PriceInfo, + ) + rating = proto.Field( + proto.MESSAGE, + number=15, + message=common.Rating, + ) + available_time = proto.Field( + proto.MESSAGE, + number=18, + message=timestamp_pb2.Timestamp, + ) + availability = proto.Field( + proto.ENUM, + number=19, + enum=Availability, + ) + available_quantity = proto.Field( + proto.MESSAGE, + number=20, + message=wrappers_pb2.Int32Value, + ) + fulfillment_info = proto.RepeatedField( + proto.MESSAGE, + number=21, + message=common.FulfillmentInfo, + ) + uri = proto.Field( + proto.STRING, + number=22, + ) + images = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=common.Image, + ) + audience = proto.Field( + proto.MESSAGE, + number=24, + message=common.Audience, + ) + color_info = proto.Field( + proto.MESSAGE, + number=25, + message=common.ColorInfo, + ) + sizes = proto.RepeatedField( + proto.STRING, + number=26, + ) + materials = proto.RepeatedField( + proto.STRING, + number=27, + ) + patterns = proto.RepeatedField( + proto.STRING, + number=28, + ) + conditions = proto.RepeatedField( + proto.STRING, + number=29, + ) + promotions = proto.RepeatedField( + proto.MESSAGE, + number=34, + message=promotion.Promotion, + ) + publish_time = proto.Field( + proto.MESSAGE, + number=33, + message=timestamp_pb2.Timestamp, + ) + retrievable_fields = proto.Field( + proto.MESSAGE, + number=30, + message=field_mask_pb2.FieldMask, + ) + variants = proto.RepeatedField( + proto.MESSAGE, + number=31, + message='Product', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py new file mode 100644 index 00000000..ce4d5c3e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py @@ -0,0 +1,858 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'CreateProductRequest', + 'GetProductRequest', + 'UpdateProductRequest', + 'DeleteProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'SetInventoryRequest', + 'SetInventoryMetadata', + 'SetInventoryResponse', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesResponse', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesResponse', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesResponse', + }, +) + + +class CreateProductRequest(proto.Message): + r"""Request message for [CreateProduct][] method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + product (google.cloud.retail_v2.types.Product): + Required. The [Product][google.cloud.retail.v2.Product] to + create. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2.Product], which will become + the final component of the + [Product.name][google.cloud.retail.v2.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2.Product]s with the same + [parent][google.cloud.retail.v2.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + product_id = proto.Field( + proto.STRING, + number=3, + ) + + +class GetProductRequest(proto.Message): + r"""Request message for [GetProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested [Product][google.cloud.retail.v2.Product] + does not exist, a NOT_FOUND error is returned. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateProductRequest(proto.Message): + r"""Request message for [UpdateProduct][] method. + + Attributes: + product (google.cloud.retail_v2.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to update + does not exist and + [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Product][google.cloud.retail.v2.Product] to update. The + immutable and output only fields are NOT supported. If not + set, all supported fields (the fields that are neither + immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + The attribute key can be updated by setting the mask path as + "attributes.${key_name}". If a key name is present in the + mask but not in the patching product from the request, this + key will be deleted after the update. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, a + new [Product][google.cloud.retail.v2.Product] will be + created. In this situation, ``update_mask`` is ignored. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteProductRequest(proto.Message): + r"""Request message for [DeleteProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to delete + does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2.Product] to delete can + neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] with more than one + [variants][google.cloud.retail.v2.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2.Product] will be deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProductsRequest(proto.Message): + r"""Request message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list products + under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2.Product]s under this + branch, regardless of whether or not this branch exists, a + PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of [Product][google.cloud.retail.v2.Product]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 + [ListProductsResponse.next_page_token][google.cloud.retail.v2.ListProductsResponse.next_page_token], + received from a previous + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + filter (str): + A filter to apply on the list results. Supported features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2.ListProductsRequest.filter] + is unset. + - List + [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s sharing the + same + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]. For example: + ``primary_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2.Product]s bundled + in a + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product]. For example: + ``collection_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2.Product]s with a + partibular type. For example: ``type = "PRIMARY"`` + ``type = "VARIANT"`` ``type = "COLLECTION"`` + + If the field is unrecognizable, an INVALID_ARGUMENT error is + returned. + + If the specified + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] or + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product] does not exist, a + NOT_FOUND error is returned. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields of [Product][google.cloud.retail.v2.Product] to + return in the responses. If not set or empty, the following + fields are returned: + + - [Product.name][google.cloud.retail.v2.Product.name] + - [Product.id][google.cloud.retail.v2.Product.id] + - [Product.title][google.cloud.retail.v2.Product.title] + - [Product.uri][google.cloud.retail.v2.Product.uri] + - [Product.images][google.cloud.retail.v2.Product.images] + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.brands][google.cloud.retail.v2.Product.brands] + + If "*" is provided, all fields are returned. + [Product.name][google.cloud.retail.v2.Product.name] is + always returned no matter what mask is set. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class ListProductsResponse(proto.Message): + r"""Response message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + + Attributes: + products (Sequence[google.cloud.retail_v2.types.Product]): + The [Product][google.cloud.retail.v2.Product]s. + next_page_token (str): + A token that can be sent as + [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class SetInventoryRequest(proto.Message): + r"""Request message for [SetInventory][] method. + + Attributes: + inventory (google.cloud.retail_v2.types.Product): + Required. The inventory information to update. The allowable + fields to update are: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product] named in + [Product.name][google.cloud.retail.v2.Product.name], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Product][google.cloud.retail.v2.Product] to update + does not have existing inventory information, the provided + inventory information will be inserted. + + If the [Product][google.cloud.retail.v2.Product] to update + has existing inventory information, the provided inventory + information will be merged while respecting the last update + time for each inventory field, using the provided or default + value for + [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of fulfillment + types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear in + [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types have + empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following inventory + fields: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + + If a full overwrite of inventory information while ignoring + timestamps is needed, [UpdateProduct][] should be invoked + instead. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the request is issued, used to + prevent out-of-order updates on inventory fields + with the last update time recorded. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] with name + [Product.name][google.cloud.retail.v2.Product.name] is not + found, the inventory update will still be processed and + retained for at most 1 day until the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + inventory = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + set_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + set_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=4, + ) + + +class SetInventoryMetadata(proto.Message): + r"""Metadata related to the progress of the SetInventory operation. + Currently empty because there is no meaningful metadata populated + from the [SetInventory][] method. + + """ + + +class SetInventoryResponse(proto.Message): + r"""Response of the SetInventoryRequest. Currently empty because there + is no meaningful response populated from the [SetInventory][] + method. + + """ + + +class AddFulfillmentPlacesRequest(proto.Message): + r"""Request message for + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery" to be added for this + [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type]. + Duplicate IDs will be automatically ignored. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If the total number of place IDs exceeds 2000 for this + [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type] + after adding, then the update will be rejected. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, the + fulfillment information will still be processed and retained + for at most 1 day and processed once the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + add_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class AddFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the AddFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + """ + + +class AddFulfillmentPlacesResponse(proto.Message): + r"""Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + """ + + +class AddLocalInventoriesRequest(proto.Message): + r"""Request message for + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + local_inventories (Sequence[google.cloud.retail_v2.types.LocalInventory]): + Required. A list of inventory information at + difference places. Each place is identified by + its place ID. At most 3000 inventories are + allowed per request. + add_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided list of + [LocalInventory][google.cloud.retail.v2.LocalInventory] to + update. The field is updated to the provided value. + + If a field is set while the place does not have a previous + local inventory, the local inventory at that store is + created. + + If a field is set while the value of that field is not + provided, the original field value, if it exists, is + deleted. + + If the mask is not set or set with empty paths, all + inventory fields will be updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory updates are + issued. Used to prevent out-of-order updates on + local inventory fields. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, the + local inventory will still be processed and retained for at + most 1 day and processed once the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + local_inventories = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.LocalInventory, + ) + add_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + add_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=6, + ) + + +class AddLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the AddLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + """ + + +class AddLocalInventoriesResponse(proto.Message): + r"""Response of the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + API. Currently empty because there is no meaningful response + populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + """ + + +class RemoveLocalInventoriesRequest(proto.Message): + r"""Request message for [RemoveLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + place_ids (Sequence[str]): + Required. A list of place IDs to have their + inventory deleted. At most 3000 place IDs are + allowed per request. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory deletions are + issued. Used to prevent out-of-order updates and + deletions on local inventory fields. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, the + local inventory removal request will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class RemoveLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesResponse(proto.Message): + r"""Response of the [RemoveLocalInventories][] API. Currently empty + because there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + + +class RemoveFulfillmentPlacesRequest(proto.Message): + r"""Request message for [RemoveFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][google.cloud.retail.v2.FulfillmentInfo.type]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery", to be removed for this + [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type]. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, the + fulfillment information will still be processed and retained + for at most 1 day and processed once the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class RemoveFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveFulfillmentPlaces][] method. + + """ + + +class RemoveFulfillmentPlacesResponse(proto.Message): + r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty + because there is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py new file mode 100644 index 00000000..e8d80a4e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'Promotion', + }, +) + + +class Promotion(proto.Message): + r"""Promotion information. + + Attributes: + promotion_id (str): + ID of the promotion. For example, "free gift". + + The value must be a UTF-8 encoded string with a length limit + of 128 characters, and match the pattern: + ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or + ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is + returned. + + Google Merchant Center property + `promotion `__. + """ + + promotion_id = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py new file mode 100644 index 00000000..b8159aa6 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + }, +) + + +class PurgeMetadata(proto.Message): + r"""Metadata related to the progress of the Purge operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + """ + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + + Attributes: + parent (str): + Required. The resource name of the catalog under which the + events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}`` + filter (str): + Required. The filter string to specify the events to be + deleted with a length limit of 5,000 characters. Empty + string filter is not allowed. The eligible fields for + filtering are: + + - ``eventType``: Double quoted + [UserEvent.event_type][google.cloud.retail.v2.UserEvent.event_type] + string. + - ``eventTime``: in ISO 8601 "zulu" format. + - ``visitorId``: Double quoted string. Specifying this will + delete all events associated with a visitor. + - ``userId``: Double quoted string. Specifying this will + delete all events associated with a user. + + Examples: + + - Deleting all events in a time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + - Deleting specific eventType in time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + - Deleting all events for a specific visitor: + ``visitorId = "visitor1024"`` + + The filtering fields are assumed to have an implicit AND. + force (bool): + Actually perform the purge. If ``force`` is set to false, + the method will return the expected purge count without + deleting any user events. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsResponse(proto.Message): + r"""Response of the PurgeUserEventsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purged_events_count (int): + The total count of events purged as a result + of the operation. + """ + + purged_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py new file mode 100644 index 00000000..e6274278 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py @@ -0,0 +1,1150 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'SearchRequest', + 'SearchResponse', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + + Attributes: + placement (str): + Required. The resource name of the search engine placement, + such as + ``projects/*/locations/global/catalogs/default_catalog/placements/default_search``. + This field is used to identify the serving configuration + name and the set of models that will be used to make the + search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + + Use "default_branch" as the branch ID or leave this field + empty, to search products under the default branch. + query (str): + Raw search query. + + If this field is empty, the request is considered a category + browsing request and returned results are based on + [filter][google.cloud.retail.v2.SearchRequest.filter] and + [page_categories][google.cloud.retail.v2.SearchRequest.page_categories]. + visitor_id (str): + Required. A unique identifier for tracking visitors. For + example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + This should be the same identifier as + [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2.types.UserInfo): + User information. + page_size (int): + Maximum number of [Product][google.cloud.retail.v2.Product]s + to return. If unspecified, defaults to a reasonable value. + The maximum allowed value is 120. Values above 120 will be + coerced to 120. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [SearchResponse.next_page_token][google.cloud.retail.v2.SearchResponse.next_page_token], + received from a previous + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Product][google.cloud.retail.v2.Product]s deemed by the API + as relevant) in search results. This field is only + considered if + [page_token][google.cloud.retail.v2.SearchRequest.page_token] + is unset. + + If this field is negative, an INVALID_ARGUMENT is returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. Filter expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + canonical_filter (str): + The default filter that is applied when a user performs a + search without checking any filters on the search page. + + The filter applied to every search request when quality + improvement such as query expansion is needed. For example, + if a query does not have enough results, an expanded query + with + [SearchRequest.canonical_filter][google.cloud.retail.v2.SearchRequest.canonical_filter] + will be returned as a supplement of the original query. This + field is strongly recommended to achieve high search + quality. + + See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] + for more details about filter syntax. + order_by (str): + The order in which products are returned. Products can be + ordered by a field in an + [Product][google.cloud.retail.v2.Product] object. Leave it + unset if ordered by relevance. OrderBy expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + facet_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + dynamic_facet_spec (google.cloud.retail_v2.types.SearchRequest.DynamicFacetSpec): + Deprecated. Refer to + https://cloud.google.com/retail/docs/configs#dynamic + to enable dynamic facets. Do not set this field. + The specification for dynamically generated + facets. Notice that only textual facets can be + dynamically generated. + boost_spec (google.cloud.retail_v2.types.SearchRequest.BoostSpec): + Boost specification to boost certain products. See more + details at this `user + guide `__. + + Notice that if both [ServingConfig.boost_control_ids][] and + [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] + are set, the boost conditions from both places are + evaluated. If a search request matches multiple boost + conditions, the final boost score is equal to the sum of the + boost scores from all matched boost conditions. + query_expansion_spec (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that specifies the + conditions under which query expansion will occur. See more + details at this `user + guide `__. + variant_rollup_keys (Sequence[str]): + The keys to fetch and rollup the matching + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s attributes, + [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo] or + [LocalInventory][google.cloud.retail.v2.LocalInventory]s + attributes. The attributes from all the matching + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s or + [LocalInventory][google.cloud.retail.v2.LocalInventory]s are + merged and de-duplicated. Notice that rollup attributes will + lead to extra query latency. Maximum number of keys is 30. + + For + [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], a + fulfillment type and a fulfillment ID must be provided in + the format of "fulfillmentType.fulfillmentId". E.g., in + "pickupInStore.store123", "pickupInStore" is fulfillment + type and "store123" is the store ID. + + Supported keys are: + + - colorFamilies + - price + - originalPrice + - discount + - variantId + - inventory(place_id,price) + - inventory(place_id,original_price) + - inventory(place_id,attributes.key), where key is any key + in the + [Product.local_inventories.attributes][google.cloud.retail.v2.LocalInventory.attributes] + map. + - attributes.key, where key is any key in the + [Product.attributes][google.cloud.retail.v2.Product.attributes] + map. + - pickupInStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "pickup-in-store". + - shipToStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "ship-to-store". + - sameDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "same-day-delivery". + - nextDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "next-day-delivery". + - customFulfillment1.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-1". + - customFulfillment2.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-2". + - customFulfillment3.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-3". + - customFulfillment4.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-4". + - customFulfillment5.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-5". + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. Required for + category navigation queries to achieve good search quality. + The format should be the same as + [UserEvent.page_categories][google.cloud.retail.v2.UserEvent.page_categories]; + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + search_mode (google.cloud.retail_v2.types.SearchRequest.SearchMode): + The search mode of the search request. If not + specified, a single search request triggers both + product search and faceted search. + personalization_spec (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec): + The specification for personalization. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + spell_correction_spec (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec): + The spell correction specification that + specifies the mode under which spell correction + will take effect. + + This field is a member of `oneof`_ ``_spell_correction_spec``. + """ + class SearchMode(proto.Enum): + r"""The search mode of each search request.""" + SEARCH_MODE_UNSPECIFIED = 0 + PRODUCT_SEARCH_ONLY = 1 + FACETED_SEARCH_ONLY = 2 + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.retail_v2.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum of facet values that should be returned for this + facet. If unspecified, defaults to 20. The maximum allowed + value is 300. Values above 300 will be coerced to 300. + + If this field is negative, an INVALID_ARGUMENT is returned. + excluded_filter_keys (Sequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + Listing a facet key in this field allows its values to + appear as facet results, even when they are filtered out of + search results. Using this field does not affect what search + results are returned. + + For example, suppose there are 100 products with the color + facet "Red" and 200 products with the color facet "Blue". A + query containing the filter "colorFamilies:ANY("Red")" and + having "colorFamilies" as + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + would by default return only "Red" products in the search + results, and also return "Red" with count 100 as the only + color facet. Although there are also blue products + available, "Blue" would not be shown as an available facet + value. + + If "colorFamilies" is listed in "excludedFilterKeys", then + the query returns the facet values "Red" with count 100 and + "Blue" with count 200, because the "colorFamilies" key is + now excluded from the filter. Because this field doesn't + affect search results, the search results are still + correctly filtered to return only "Red" products. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined by Google Retail Search. It will be ordered + together with dynamic facets if dynamic facets is enabled. + If set to false, the position of this facet in the response + will be the same as in the request, and it will be ranked + before the facets with dynamic position enable and all + dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response will be determined by Google Retail + Search. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enable, which will + generate a facet 'gender'. Then the final order of the + facets in the response can be ("price", "brands", "rating", + "gender") or ("price", "brands", "gender", "rating") depends + on how Google Retail Search orders "gender" and "rating" + facets. However, notice that "price" and "brands" will + always be ranked at 1st and 2nd position since their + enable_dynamic_position are false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Product][google.cloud.retail.v2.Product] object, over which + the facet values are computed. Facet key is case-sensitive. + + Allowed facet keys when + [FacetKey.query][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.query] + is not specified: + + - textual_field = + + - "brands" + - "categories" + - "genders" + - "ageGroups" + - "availability" + - "colorFamilies" + - "colors" + - "sizes" + - "materials" + - "patterns" + - "conditions" + - "attributes.key" + - "pickupInStore" + - "shipToStore" + - "sameDayDelivery" + - "nextDayDelivery" + - "customFulfillment1" + - "customFulfillment2" + - "customFulfillment3" + - "customFulfillment4" + - "customFulfillment5" + - "inventory(place_id,attributes.key)" + + - numerical_field = + + - "price" + - "discount" + - "rating" + - "ratingCount" + - "attributes.key" + - "inventory(place_id,price)" + - "inventory(place_id,original_price)" + - "inventory(place_id,attributes.key)". + intervals (Sequence[google.cloud.retail_v2.types.Interval]): + Set only if values should be bucketized into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (Sequence[str]): + Only get facet for the given restricted values. For example, + when using "pickupInStore" as key and set restricted values + to ["store123", "store456"], only facets for "store123" and + "store456" are returned. Only supported on predefined + textual fields, custom textual attributes and fulfillments. + Maximum is 20. + + Must be set for the fulfillment facet keys: + + - pickupInStore + + - shipToStore + + - sameDayDelivery + + - nextDayDelivery + + - customFulfillment1 + + - customFulfillment2 + + - customFulfillment3 + + - customFulfillment4 + + - customFulfillment5 + prefixes (Sequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "categories" has three values "Women > Shoe", + "Women > Dress" and "Men > Shoe". If set + "prefixes" to "Women", the "categories" facet + will give only "Women > Shoe" and "Women > + Dress". Only supported on textual fields. + Maximum is 10. + contains (Sequence[str]): + Only get facet values that contains the given + strings. For example, suppose "categories" has + three values "Women > Shoe", "Women > Dress" and + "Men > Shoe". If set "contains" to "Shoe", the + "categories" facet will give only "Women > Shoe" + and "Men > Shoe". Only supported on textual + fields. Maximum is 10. + order_by (str): + The order in which [Facet.values][] are returned. + + Allowed values are: + + - "count desc", which means order by + [Facet.FacetValue.count][] descending. + + - "value desc", which means order by + [Facet.FacetValue.value][] descending. Only applies to + textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.intervals]; + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + are sorted in the order given by + [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.restricted_values]. + query (str): + The query that is used to compute facet for the given facet + key. When provided, it will override the default behavior of + facet computation. The query syntax is the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] + for detail syntax and limitations. Notice that there is no + limitation on + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + when query is specified. + + In the response, [FacetValue.value][] will be always "1" and + [FacetValue.count][] will be the number of results that + matches the query. + + For example, you can set a customized facet for + "shipToStore", where + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + is "customizedShipToStore", and + [FacetKey.query][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.query] + is "availability: ANY("IN_STOCK") AND shipToStore: + ANY("123")". Then the facet will count the products that are + both in stock and ship to store "123". + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + intervals = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes = proto.RepeatedField( + proto.STRING, + number=8, + ) + contains = proto.RepeatedField( + proto.STRING, + number=9, + ) + order_by = proto.Field( + proto.STRING, + number=4, + ) + query = proto.Field( + proto.STRING, + number=5, + ) + + facet_key = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.FacetSpec.FacetKey', + ) + limit = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position = proto.Field( + proto.BOOL, + number=4, + ) + + class DynamicFacetSpec(proto.Message): + r"""The specifications of dynamically generated facets. + + Attributes: + mode (google.cloud.retail_v2.types.SearchRequest.DynamicFacetSpec.Mode): + Mode of the DynamicFacet feature. Defaults to + [Mode.DISABLED][google.cloud.retail.v2.SearchRequest.DynamicFacetSpec.Mode.DISABLED] + if it's unset. + """ + class Mode(proto.Enum): + r"""Enum to control DynamicFacet mode""" + MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.DynamicFacetSpec.Mode', + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain items. + + Attributes: + condition_boost_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a product + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 20. + skip_boost_spec_validation (bool): + Whether to skip boostspec validation. If this field is set + to true, invalid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] + will be ignored and valid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] + will still be applied. + + This field is a member of `oneof`_ ``_skip_boost_spec_validation``. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to products which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": + + - (id: ANY("product_1", "product_2")) AND + (colorFamilies: ANY("Red","Blue")) + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition = proto.Field( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + skip_boost_spec_validation = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.retail.v2.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 3 + + condition = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.QueryExpansionSpec.Condition', + ) + pin_unexpanded_results = proto.Field( + proto.BOOL, + number=2, + ) + + class PersonalizationSpec(proto.Message): + r"""The specification for personalization. + + Attributes: + mode (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec.Mode): + Defaults to + [Mode.AUTO][google.cloud.retail.v2.SearchRequest.PersonalizationSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""The personalization mode of each search request.""" + MODE_UNSPECIFIED = 0 + AUTO = 1 + DISABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.PersonalizationSpec.Mode', + ) + + class SpellCorrectionSpec(proto.Message): + r"""The specification for query spell correction. + + Attributes: + mode (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec.Mode): + The mode under which spell correction should take effect to + replace the original search query. Default to + [Mode.AUTO][google.cloud.retail.v2.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""Enum describing under which mode spell correction should + occur. + """ + MODE_UNSPECIFIED = 0 + SUGGESTION_ONLY = 1 + AUTO = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.SpellCorrectionSpec.Mode', + ) + + placement = proto.Field( + proto.STRING, + number=1, + ) + branch = proto.Field( + proto.STRING, + number=2, + ) + query = proto.Field( + proto.STRING, + number=3, + ) + visitor_id = proto.Field( + proto.STRING, + number=4, + ) + user_info = proto.Field( + proto.MESSAGE, + number=5, + message=common.UserInfo, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + offset = proto.Field( + proto.INT32, + number=9, + ) + filter = proto.Field( + proto.STRING, + number=10, + ) + canonical_filter = proto.Field( + proto.STRING, + number=28, + ) + order_by = proto.Field( + proto.STRING, + number=11, + ) + facet_specs = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=FacetSpec, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=21, + message=DynamicFacetSpec, + ) + boost_spec = proto.Field( + proto.MESSAGE, + number=13, + message=BoostSpec, + ) + query_expansion_spec = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionSpec, + ) + variant_rollup_keys = proto.RepeatedField( + proto.STRING, + number=17, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=23, + ) + search_mode = proto.Field( + proto.ENUM, + number=31, + enum=SearchMode, + ) + personalization_spec = proto.Field( + proto.MESSAGE, + number=32, + message=PersonalizationSpec, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=34, + ) + spell_correction_spec = proto.Field( + proto.MESSAGE, + number=35, + optional=True, + message=SpellCorrectionSpec, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + + Attributes: + results (Sequence[google.cloud.retail_v2.types.SearchResponse.SearchResult]): + A list of matched items. The order represents + the ranking. + facets (Sequence[google.cloud.retail_v2.types.SearchResponse.Facet]): + Results of facets requested by user. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.retail.v2.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.retail.v2.SearchResponse.total_size] + that matches. + corrected_query (str): + Contains the spell corrected query, if found. If the spell + correction type is AUTOMATIC, then the search results are + based on corrected_query. Otherwise the original query will + be used for search. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting + from this search, which enables accurate attribution of + search model performance. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.retail.v2.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + query_expansion_info (google.cloud.retail_v2.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search is performed, and only + [redirect_uri][google.cloud.retail.v2.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] + are set in the response. + applied_controls (Sequence[str]): + The fully qualified resource name of applied + `controls `__. + invalid_condition_boost_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + The invalid + [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] + that are not applied during serving. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Product.id][google.cloud.retail.v2.Product.id] of the + searched [Product][google.cloud.retail.v2.Product]. + product (google.cloud.retail_v2.types.Product): + The product data snippet in the search response. Only + [Product.name][google.cloud.retail.v2.Product.name] is + guaranteed to be populated. + + [Product.variants][google.cloud.retail.v2.Product.variants] + contains the product variants that match the search query. + If there are multiple product variants matching the query, + top 5 most relevant product variants are returned and + ordered by relevancy. + + If relevancy can be deternmined, use + [matching_variant_fields][google.cloud.retail.v2.SearchResponse.SearchResult.matching_variant_fields] + to look up matched product variants fields. If relevancy + cannot be determined, e.g. when searching "shoe" all + products in a shoe product can be a match, 5 product + variants are returned but order is meaningless. + matching_variant_count (int): + The count of matched + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s. + matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): + If a [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] matches the search + query, this map indicates which + [Product][google.cloud.retail.v2.Product] fields are + matched. The key is the + [Product.name][google.cloud.retail.v2.Product.name], the + value is a field mask of the matched + [Product][google.cloud.retail.v2.Product] fields. If matched + attributes cannot be determined, this map will be empty. + + For example, a key "sku1" with field mask + "products.color_info" indicates there is a match between + "sku1" [ColorInfo][google.cloud.retail.v2.ColorInfo] and the + query. + variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): + The rollup matching + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] attributes. The + key is one of the + [SearchRequest.variant_rollup_keys][google.cloud.retail.v2.SearchRequest.variant_rollup_keys]. + The values are the merged and de-duplicated + [Product][google.cloud.retail.v2.Product] attributes. Notice + that the rollup values are respect filter. For example, when + filtering by "colorFamilies:ANY("red")" and rollup + "colorFamilies", only "red" is returned. + + For textual and numerical attributes, the rollup values is a + list of string or double values with type + [google.protobuf.ListValue][google.protobuf.ListValue]. For + example, if there are two variants with colors "red" and + "blue", the rollup values are + + :: + + { key: "colorFamilies" + value { + list_value { + values { string_value: "red" } + values { string_value: "blue" } + } + } + } + + For + [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], + the rollup values is a double value with type + [google.protobuf.Value][google.protobuf.Value]. For example, + ``{key: "pickupInStore.store1" value { number_value: 10 }}`` + means a there are 10 variants in this product are available + in the store "store1". + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + matching_variant_count = proto.Field( + proto.INT32, + number=3, + ) + matching_variant_fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + variant_rollup_values = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. E.g., "colorFamilies" + or "price" or "attributes.attr1". + values (Sequence[google.cloud.retail_v2.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Text value of a facet, such as "Black" for + facet "colorFamilies". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.retail_v2.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value = proto.Field( + proto.STRING, + number=1, + oneof='facet_value', + ) + interval = proto.Field( + proto.MESSAGE, + number=2, + oneof='facet_value', + message=common.Interval, + ) + count = proto.Field( + proto.INT64, + number=3, + ) + + key = proto.Field( + proto.STRING, + number=1, + ) + values = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SearchResponse.Facet.FacetValue', + ) + dynamic_facet = proto.Field( + proto.BOOL, + number=3, + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count = proto.Field( + proto.INT64, + number=2, + ) + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + corrected_query = proto.Field( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + next_page_token = proto.Field( + proto.STRING, + number=6, + ) + query_expansion_info = proto.Field( + proto.MESSAGE, + number=7, + message=QueryExpansionInfo, + ) + redirect_uri = proto.Field( + proto.STRING, + number=10, + ) + applied_controls = proto.RepeatedField( + proto.STRING, + number=12, + ) + invalid_condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py new file mode 100644 index 00000000..0d6b6823 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py @@ -0,0 +1,508 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import product as gcr_product +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'UserEvent', + 'ProductDetail', + 'CompletionDetail', + 'PurchaseTransaction', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Retail API needs + to know about how end users interact with customers' website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + - ``add-to-cart``: Products being added to cart. + - ``category-page-view``: Special pages such as sale or + promotion pages viewed. + - ``detail-page-view``: Products detail page viewed. + - ``home-page-view``: Homepage viewed. + - ``promotion-offered``: Promotion is offered to a user. + - ``promotion-not-offered``: Promotion is not offered to a + user. + - ``purchase-complete``: User finishing a purchase. + - ``search``: Product search. + - ``shopping-cart-page-view``: User viewing a shopping + cart. + visitor_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + Don't set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + The field should not contain PII or user-data. We recommend + to use Google Analytics `Client + ID `__ + for this field. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the sesion_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add visitor_id as prefix. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.retail.v2.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + experiment_ids (Sequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups + (e.g. using Retail API, using different + recommendation models). + attribution_token (str): + Highly recommended for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]. + This field enables accurate attribution of recommendation + model performance. + + The value must be a valid + [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] + for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]. + The value must be a valid + [SearchResponse.attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] + for user events that are the result of + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + + This token enables us to accurately attribute page view or + purchase back to the event and the particular predict + response containing this clicked/purchased product. If user + clicks on product K in the recommendation results, pass + [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] + as a URL parameter to product K's page. When recording + events on product K's page, log the + [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] + to this field. + product_details (Sequence[google.cloud.retail_v2.types.ProductDetail]): + The main product details related to the event. + + This field is optional except for the following event types: + + - ``add-to-cart`` + - ``detail-page-view`` + - ``purchase-complete`` + + In a ``search`` event, this field represents the products + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [product_details][google.cloud.retail.v2.UserEvent.product_details] + is desired. The end user may have not finished browsing the + whole page yet. + completion_detail (google.cloud.retail_v2.types.CompletionDetail): + The main auto-completion details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Retail API use those + custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - The key must be a UTF-8 encoded string with a length + limit of 5,000 characters. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a UTF-8 + encoded string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is traffic_channel, which is how a user arrives + at the site. Users can arrive at the site by coming to the + site directly, coming through Google search, or in other + ways. + cart_id (str): + The ID or name of the associated shopping cart. This ID is + used to associate multiple items added or present in the + cart before purchase. + + This can only be set for ``add-to-cart``, + ``purchase-complete``, or ``shopping-cart-page-view`` + events. + purchase_transaction (google.cloud.retail_v2.types.PurchaseTransaction): + A transaction represents the entire purchase transaction. + + Required for ``purchase-complete`` events. Other event types + should not set this field. Otherwise, an INVALID_ARGUMENT + error is returned. + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.retail.v2.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + At least one of + [search_query][google.cloud.retail.v2.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. + + See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + order_by (str): + The order in which products are returned. + + See + [SearchRequest.order_by][google.cloud.retail.v2.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.retail.v2.SearchRequest.offset] + for definition. + + If this field is negative, an INVALID_ARGUMENT is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + + Required for ``category-page-view`` events. At least one of + [search_query][google.cloud.retail.v2.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2.types.UserInfo): + User information. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. + page_view_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageViewId`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + """ + + event_type = proto.Field( + proto.STRING, + number=1, + ) + visitor_id = proto.Field( + proto.STRING, + number=2, + ) + session_id = proto.Field( + proto.STRING, + number=21, + ) + event_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + experiment_ids = proto.RepeatedField( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + product_details = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ProductDetail', + ) + completion_detail = proto.Field( + proto.MESSAGE, + number=22, + message='CompletionDetail', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=common.CustomAttribute, + ) + cart_id = proto.Field( + proto.STRING, + number=8, + ) + purchase_transaction = proto.Field( + proto.MESSAGE, + number=9, + message='PurchaseTransaction', + ) + search_query = proto.Field( + proto.STRING, + number=10, + ) + filter = proto.Field( + proto.STRING, + number=16, + ) + order_by = proto.Field( + proto.STRING, + number=17, + ) + offset = proto.Field( + proto.INT32, + number=18, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=11, + ) + user_info = proto.Field( + proto.MESSAGE, + number=12, + message=common.UserInfo, + ) + uri = proto.Field( + proto.STRING, + number=13, + ) + referrer_uri = proto.Field( + proto.STRING, + number=14, + ) + page_view_id = proto.Field( + proto.STRING, + number=15, + ) + + +class ProductDetail(proto.Message): + r"""Detailed product information associated with a user event. + + Attributes: + product (google.cloud.retail_v2.types.Product): + Required. [Product][google.cloud.retail.v2.Product] + information. + + Required field(s): + + - [Product.id][google.cloud.retail.v2.Product.id] + + Optional override field(s): + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + + If any supported optional fields are provided, we will treat + them as a full override when looking up product information + from the catalog. Thus, it is important to ensure that the + overriding fields are accurate and complete. + + All other product fields are ignored and instead populated + via catalog lookup after event ingestion. + quantity (google.protobuf.wrappers_pb2.Int32Value): + Quantity of the product associated with the user event. + + For example, this field will be 2 if two products are added + to the shopping cart for ``purchase-complete`` event. + Required for ``add-to-cart`` and ``purchase-complete`` event + types. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + quantity = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +class CompletionDetail(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + completion_attribution_token (str): + Completion attribution token in + [CompleteQueryResponse.attribution_token][google.cloud.retail.v2.CompleteQueryResponse.attribution_token]. + selected_suggestion (str): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2.CompleteQueryResponse.CompletionResult.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2.CompleteQueryResponse.CompletionResult.suggestion] + position, starting from 0. + """ + + completion_attribution_token = proto.Field( + proto.STRING, + number=1, + ) + selected_suggestion = proto.Field( + proto.STRING, + number=2, + ) + selected_position = proto.Field( + proto.INT32, + number=3, + ) + + +class PurchaseTransaction(proto.Message): + r"""A transaction represents the entire purchase transaction. + + Attributes: + id (str): + The transaction ID with a length limit of 128 + characters. + revenue (float): + Required. Total non-zero revenue or grand + total associated with the transaction. This + value include shipping, tax, or other + adjustments to total revenue that you want to + include as part of your revenue calculations. + tax (float): + All the taxes associated with the + transaction. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [revenue][google.cloud.retail.v2.PurchaseTransaction.revenue] + - [tax][google.cloud.retail.v2.PurchaseTransaction.tax] - + [cost][google.cloud.retail.v2.PurchaseTransaction.cost] + currency_code (str): + Required. Currency code. Use three-character + ISO-4217 code. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + revenue = proto.Field( + proto.FLOAT, + number=2, + ) + tax = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + currency_code = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py new file mode 100644 index 00000000..fcfc46d7 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import user_event as gcr_user_event + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'WriteUserEventRequest', + 'CollectUserEventRequest', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'RejoinUserEventsMetadata', + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (google.cloud.retail_v2.types.UserEvent): + Required. User event to write. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for 3rd party requests. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.STRING, + number=2, + ) + uri = proto.Field( + proto.STRING, + number=3, + ) + ets = proto.Field( + proto.INT64, + number=4, + ) + + +class RejoinUserEventsRequest(proto.Message): + r"""Request message for RejoinUserEvents method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event_rejoin_scope (google.cloud.retail_v2.types.RejoinUserEventsRequest.UserEventRejoinScope): + The type of the user event rejoin to define the scope and + range of the user events to be rejoined with the latest + product catalog. Defaults to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not + set, or set to an invalid integer value. + """ + class UserEventRejoinScope(proto.Enum): + r"""The scope of user events to be rejoined with the latest product + catalog. If the rejoining aims at reducing number of unjoined + events, set UserEventRejoinScope to UNJOINED_EVENTS. If the + rejoining aims at correcting product catalog information in joined + events, set UserEventRejoinScope to JOINED_EVENTS. If all events + needs to be rejoined, set UserEventRejoinScope to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. + """ + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 + JOINED_EVENTS = 1 + UNJOINED_EVENTS = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event_rejoin_scope = proto.Field( + proto.ENUM, + number=2, + enum=UserEventRejoinScope, + ) + + +class RejoinUserEventsResponse(proto.Message): + r"""Response message for RejoinUserEvents method. + + Attributes: + rejoined_user_events_count (int): + Number of user events that were joined with + latest product catalog. + """ + + rejoined_user_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +class RejoinUserEventsMetadata(proto.Message): + r"""Metadata for RejoinUserEvents method. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py new file mode 100644 index 00000000..e7ab4118 --- /dev/null +++ b/owl-bot-staging/v2/noxfile.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.6", + "3.7", + "3.8", + "3.9", + "3.10", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==19.10b0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.9" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/retail_v2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py new file mode 100644 index 00000000..fb30eae6 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_GetDefaultBranch_async] +from google.cloud import retail_v2 + + +async def sample_get_default_branch(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py new file mode 100644 index 00000000..0af0ece9 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_GetDefaultBranch_sync] +from google.cloud import retail_v2 + + +def sample_get_default_branch(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py new file mode 100644 index 00000000..2a0930de --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_ListCatalogs_async] +from google.cloud import retail_v2 + + +async def sample_list_catalogs(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py new file mode 100644 index 00000000..2671a121 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_ListCatalogs_sync] +from google.cloud import retail_v2 + + +def sample_list_catalogs(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py new file mode 100644 index 00000000..f85e3ed8 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_SetDefaultBranch_async] +from google.cloud import retail_v2 + + +async def sample_set_default_branch(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + +# [END retail_v2_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py new file mode 100644 index 00000000..34371062 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_SetDefaultBranch_sync] +from google.cloud import retail_v2 + + +def sample_set_default_branch(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + +# [END retail_v2_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py new file mode 100644 index 00000000..2a2b3dde --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_UpdateCatalog_async] +from google.cloud import retail_v2 + + +async def sample_update_catalog(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py new file mode 100644 index 00000000..bf721cba --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_UpdateCatalog_sync] +from google.cloud import retail_v2 + + +def sample_update_catalog(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py new file mode 100644 index 00000000..c72ecfdf --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CompletionService_CompleteQuery_async] +from google.cloud import retail_v2 + + +async def sample_complete_query(): + # Create a client + client = retail_v2.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py new file mode 100644 index 00000000..30b10016 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CompletionService_CompleteQuery_sync] +from google.cloud import retail_v2 + + +def sample_complete_query(): + # Create a client + client = retail_v2.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py new file mode 100644 index 00000000..75f45f91 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CompletionService_ImportCompletionData_async] +from google.cloud import retail_v2 + + +async def sample_import_completion_data(): + # Create a client + client = retail_v2.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py new file mode 100644 index 00000000..cc31057e --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CompletionService_ImportCompletionData_sync] +from google.cloud import retail_v2 + + +def sample_import_completion_data(): + # Create a client + client = retail_v2.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py new file mode 100644 index 00000000..f46819c5 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_PredictionService_Predict_async] +from google.cloud import retail_v2 + + +async def sample_predict(): + # Create a client + client = retail_v2.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py new file mode 100644 index 00000000..ad37063f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_PredictionService_Predict_sync] +from google.cloud import retail_v2 + + +def sample_predict(): + # Create a client + client = retail_v2.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py new file mode 100644 index 00000000..ceea2869 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_AddFulfillmentPlaces_async] +from google.cloud import retail_v2 + + +async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py new file mode 100644 index 00000000..1739ec91 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_AddFulfillmentPlaces_sync] +from google.cloud import retail_v2 + + +def sample_add_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py new file mode 100644 index 00000000..6155d5ce --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_AddLocalInventories_async] +from google.cloud import retail_v2 + + +async def sample_add_local_inventories(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py new file mode 100644 index 00000000..b57dce2f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_AddLocalInventories_sync] +from google.cloud import retail_v2 + + +def sample_add_local_inventories(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py new file mode 100644 index 00000000..fe1cb991 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_CreateProduct_async] +from google.cloud import retail_v2 + + +async def sample_create_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py new file mode 100644 index 00000000..9cc154d9 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_CreateProduct_sync] +from google.cloud import retail_v2 + + +def sample_create_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py new file mode 100644 index 00000000..33318da7 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_DeleteProduct_async] +from google.cloud import retail_v2 + + +async def sample_delete_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + +# [END retail_v2_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py new file mode 100644 index 00000000..797690c6 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_DeleteProduct_sync] +from google.cloud import retail_v2 + + +def sample_delete_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + +# [END retail_v2_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py new file mode 100644 index 00000000..32ba279d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_GetProduct_async] +from google.cloud import retail_v2 + + +async def sample_get_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py new file mode 100644 index 00000000..62805768 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_GetProduct_sync] +from google.cloud import retail_v2 + + +def sample_get_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py new file mode 100644 index 00000000..390f0977 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_ImportProducts_async] +from google.cloud import retail_v2 + + +async def sample_import_products(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py new file mode 100644 index 00000000..fcd8c82f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_ImportProducts_sync] +from google.cloud import retail_v2 + + +def sample_import_products(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py new file mode 100644 index 00000000..5e85f948 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_ListProducts_async] +from google.cloud import retail_v2 + + +async def sample_list_products(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py new file mode 100644 index 00000000..30f7fd1f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_ListProducts_sync] +from google.cloud import retail_v2 + + +def sample_list_products(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py new file mode 100644 index 00000000..08172bf4 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async] +from google.cloud import retail_v2 + + +async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py new file mode 100644 index 00000000..37f86ba9 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync] +from google.cloud import retail_v2 + + +def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py new file mode 100644 index 00000000..762dab6d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_RemoveLocalInventories_async] +from google.cloud import retail_v2 + + +async def sample_remove_local_inventories(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py new file mode 100644 index 00000000..7aa52d5d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_RemoveLocalInventories_sync] +from google.cloud import retail_v2 + + +def sample_remove_local_inventories(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py new file mode 100644 index 00000000..62a24100 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_SetInventory_async] +from google.cloud import retail_v2 + + +async def sample_set_inventory(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2.Product() + inventory.title = "title_value" + + request = retail_v2.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py new file mode 100644 index 00000000..aa5a0539 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_SetInventory_sync] +from google.cloud import retail_v2 + + +def sample_set_inventory(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2.Product() + inventory.title = "title_value" + + request = retail_v2.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py new file mode 100644 index 00000000..9ea76295 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_UpdateProduct_async] +from google.cloud import retail_v2 + + +async def sample_update_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py new file mode 100644 index 00000000..866c7e7c --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_UpdateProduct_sync] +from google.cloud import retail_v2 + + +def sample_update_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py new file mode 100644 index 00000000..ddebd9e8 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_SearchService_Search_async] +from google.cloud import retail_v2 + + +async def sample_search(): + # Create a client + client = retail_v2.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py new file mode 100644 index 00000000..fc20bb3d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_SearchService_Search_sync] +from google.cloud import retail_v2 + + +def sample_search(): + # Create a client + client = retail_v2.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 00000000..b8bb6a81 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_CollectUserEvent_async] +from google.cloud import retail_v2 + + +async def sample_collect_user_event(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 00000000..10b302e3 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_CollectUserEvent_sync] +from google.cloud import retail_v2 + + +def sample_collect_user_event(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py new file mode 100644 index 00000000..55ad399a --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_ImportUserEvents_async] +from google.cloud import retail_v2 + + +async def sample_import_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 00000000..835edec6 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_ImportUserEvents_sync] +from google.cloud import retail_v2 + + +def sample_import_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py new file mode 100644 index 00000000..1da1d39d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_PurgeUserEvents_async] +from google.cloud import retail_v2 + + +async def sample_purge_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py new file mode 100644 index 00000000..48814171 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_PurgeUserEvents_sync] +from google.cloud import retail_v2 + + +def sample_purge_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py new file mode 100644 index 00000000..a2617cfe --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_RejoinUserEvents_async] +from google.cloud import retail_v2 + + +async def sample_rejoin_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py new file mode 100644 index 00000000..eb8ed62c --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_RejoinUserEvents_sync] +from google.cloud import retail_v2 + + +def sample_rejoin_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py new file mode 100644 index 00000000..82afc25a --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_WriteUserEvent_async] +from google.cloud import retail_v2 + + +async def sample_write_user_event(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 00000000..62336b25 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_WriteUserEvent_sync] +from google.cloud import retail_v2 + + +def sample_write_user_event(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json new file mode 100644 index 00000000..c6a55bd4 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json @@ -0,0 +1,3826 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.retail.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-cloud-retail" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2_generated_catalog_service_get_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_GetDefaultBranch_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_get_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2_generated_catalog_service_get_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_GetDefaultBranch_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_get_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ListCatalogsRequest" + }, + { + "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.retail_v2.services.catalog_service.pagers.ListCatalogsAsyncPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2_generated_catalog_service_list_catalogs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_ListCatalogs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_list_catalogs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ListCatalogsRequest" + }, + { + "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.retail_v2.services.catalog_service.pagers.ListCatalogsPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2_generated_catalog_service_list_catalogs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_ListCatalogs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_list_catalogs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2_generated_catalog_service_set_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_SetDefaultBranch_async", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_set_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2_generated_catalog_service_set_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_SetDefaultBranch_sync", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_set_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2.types.Catalog" + }, + { + "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.retail_v2.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2_generated_catalog_service_update_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_UpdateCatalog_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_update_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2.types.Catalog" + }, + { + "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.retail_v2.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2_generated_catalog_service_update_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_UpdateCatalog_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_update_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2_generated_completion_service_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CompletionService_CompleteQuery_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_completion_service_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2.CompletionServiceClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2_generated_completion_service_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CompletionService_CompleteQuery_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_completion_service_complete_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2_generated_completion_service_import_completion_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CompletionService_ImportCompletionData_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_completion_service_import_completion_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2.CompletionServiceClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2_generated_completion_service_import_completion_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CompletionService_ImportCompletionData_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_completion_service_import_completion_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.PredictionServiceAsyncClient", + "shortName": "PredictionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.PredictionServiceAsyncClient.predict", + "method": { + "fullName": "google.cloud.retail.v2.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2_generated_prediction_service_predict_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_PredictionService_Predict_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_prediction_service_predict_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.PredictionServiceClient", + "shortName": "PredictionServiceClient" + }, + "fullName": "google.cloud.retail_v2.PredictionServiceClient.predict", + "method": { + "fullName": "google.cloud.retail.v2.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2_generated_prediction_service_predict_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_PredictionService_Predict_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_prediction_service_predict_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2_generated_product_service_add_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_AddFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_add_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2_generated_product_service_add_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_AddFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_add_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2_generated_product_service_add_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_AddLocalInventories_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_add_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2_generated_product_service_add_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_AddLocalInventories_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_add_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "name": "product_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.retail_v2.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2_generated_product_service_create_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_CreateProduct_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_create_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "name": "product_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.retail_v2.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2_generated_product_service_create_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_CreateProduct_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_create_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2_generated_product_service_delete_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_DeleteProduct_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_delete_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2_generated_product_service_delete_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_DeleteProduct_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_delete_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.GetProductRequest" + }, + { + "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.retail_v2.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2_generated_product_service_get_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_GetProduct_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_get_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.GetProductRequest" + }, + { + "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.retail_v2.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2_generated_product_service_get_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_GetProduct_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_get_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2_generated_product_service_import_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_ImportProducts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_import_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2_generated_product_service_import_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_ImportProducts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_import_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ListProductsRequest" + }, + { + "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.retail_v2.services.product_service.pagers.ListProductsAsyncPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2_generated_product_service_list_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_ListProducts_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_list_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ListProductsRequest" + }, + { + "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.retail_v2.services.product_service.pagers.ListProductsPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2_generated_product_service_list_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_ListProducts_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_list_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2_generated_product_service_remove_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_remove_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2_generated_product_service_remove_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_remove_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2_generated_product_service_remove_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_RemoveLocalInventories_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_remove_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2_generated_product_service_remove_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_RemoveLocalInventories_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_remove_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2_generated_product_service_set_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_SetInventory_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_set_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2_generated_product_service_set_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_SetInventory_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_set_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "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.retail_v2.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2_generated_product_service_update_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_UpdateProduct_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_update_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "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.retail_v2.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2_generated_product_service_update_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_UpdateProduct_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_update_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.SearchServiceAsyncClient.search", + "method": { + "fullName": "google.cloud.retail.v2.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2_generated_search_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_SearchService_Search_async", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_search_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.SearchServiceClient", + "shortName": "SearchServiceClient" + }, + "fullName": "google.cloud.retail_v2.SearchServiceClient.search", + "method": { + "fullName": "google.cloud.retail.v2.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.services.search_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2_generated_search_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_SearchService_Search_sync", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_search_service_search_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_CollectUserEvent_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_CollectUserEvent_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_ImportUserEvents_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_ImportUserEvents_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2_generated_user_event_service_purge_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_PurgeUserEvents_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_purge_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2_generated_user_event_service_purge_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_PurgeUserEvents_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_purge_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2_generated_user_event_service_rejoin_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_RejoinUserEvents_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_rejoin_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2_generated_user_event_service_rejoin_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_RejoinUserEvents_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_rejoin_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_WriteUserEvent_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_WriteUserEvent_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py new file mode 100644 index 00000000..9ed9d278 --- /dev/null +++ b/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py @@ -0,0 +1,199 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class retailCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), + 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'delete_product': ('name', ), + 'get_default_branch': ('catalog', ), + 'get_product': ('name', ), + 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), + 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), + 'import_user_events': ('parent', 'input_config', 'errors_config', ), + 'list_catalogs': ('parent', 'page_size', 'page_token', ), + 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', ), + 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), + 'purge_user_events': ('parent', 'filter', 'force', ), + 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), + 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), + 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), + 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', 'labels', 'spell_correction_spec', ), + 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), + 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), + 'update_catalog': ('catalog', 'update_mask', ), + 'update_product': ('product', 'update_mask', 'allow_missing', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=retailCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the retail client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2/setup.py b/owl-bot-staging/v2/setup.py new file mode 100644 index 00000000..3d49d09f --- /dev/null +++ b/owl-bot-staging/v2/setup.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-retail', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-retail", + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.31.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'googleapis-common-protos >= 1.55.0, <2.0.0dev', + 'proto-plus >= 1.19.7', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py new file mode 100644 index 00000000..23c5a2f7 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py @@ -0,0 +1,2267 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.catalog_service import CatalogServiceAsyncClient +from google.cloud.retail_v2.services.catalog_service import CatalogServiceClient +from google.cloud.retail_v2.services.catalog_service import pagers +from google.cloud.retail_v2.services.catalog_service import transports +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CatalogServiceClient._get_default_mtls_endpoint(None) is None + assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CatalogServiceGrpcTransport, "grpc"), + (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_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", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_catalog_service_client_get_transport_class(): + transport = CatalogServiceClient.get_transport_class() + available_transports = [ + transports.CatalogServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CatalogServiceClient.get_transport_class("grpc") + assert transport == transports.CatalogServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + CatalogServiceClient, CatalogServiceAsyncClient +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_catalog_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CatalogServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ListCatalogsRequest, + dict, +]) +def test_list_catalogs(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_catalogs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalogs), + '__call__') as call: + client.list_catalogs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + +@pytest.mark.asyncio +async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_catalogs_async_from_dict(): + await test_list_catalogs_async(request_type=dict) + + +def test_list_catalogs_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = catalog_service.ListCatalogsResponse() + client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_catalogs( + 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_catalogs_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_catalogs_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_catalogs( + 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_catalogs_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + + +def test_list_catalogs_pager(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_catalogs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, catalog.Catalog) + for i in results) +def test_list_catalogs_pages(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = list(client.list_catalogs(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_catalogs_async_pager(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_catalogs(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, catalog.Catalog) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_catalogs_async_pages(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCatalogRequest, + dict, +]) +def test_update_catalog(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + ) + response = client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_catalog_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalog), + '__call__') as call: + client.update_catalog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + +@pytest.mark.asyncio +async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_catalog_async_from_dict(): + await test_update_catalog_async(request_type=dict) + + +def test_update_catalog_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = gcr_catalog.Catalog() + client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_catalog_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +def test_update_catalog_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_catalog_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.SetDefaultBranchRequest, + dict, +]) +def test_set_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_set_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + client.set_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_set_default_branch_async_from_dict(): + await test_set_default_branch_async(request_type=dict) + + +def test_set_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = None + client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_set_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_set_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetDefaultBranchRequest, + dict, +]) +def test_get_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + ) + response = client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +def test_get_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_default_branch), + '__call__') as call: + client.get_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + )) + response = await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +@pytest.mark.asyncio +async def test_get_default_branch_async_from_dict(): + await test_get_default_branch_async(request_type=dict) + + +def test_get_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = catalog_service.GetDefaultBranchResponse() + client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_get_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_get_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CatalogServiceClient.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 = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CatalogServiceGrpcTransport, + ) + +def test_catalog_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_catalog_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_catalogs', + 'update_catalog', + 'set_default_branch', + 'get_default_branch', + ) + 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_catalog_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.retail_v2.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport( + 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_catalog_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.retail_v2.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport() + adc.assert_called_once() + + +def test_catalog_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) + CatalogServiceClient() + 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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +def test_catalog_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,grpc_helpers", + [ + (transports.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_catalog_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_no_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_with_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_catalog_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcTransport( + 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_catalog_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcAsyncIOTransport( + 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_branch_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = CatalogServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = CatalogServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_branch_path(path) + assert expected == actual + +def test_catalog_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + } + path = CatalogServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CatalogServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = CatalogServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = CatalogServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CatalogServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CatalogServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CatalogServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = CatalogServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CatalogServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CatalogServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CatalogServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py new file mode 100644 index 00000000..35085390 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py @@ -0,0 +1,1451 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.completion_service import CompletionServiceAsyncClient +from google.cloud.retail_v2.services.completion_service import CompletionServiceClient +from google.cloud.retail_v2.services.completion_service import transports +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CompletionServiceClient._get_default_mtls_endpoint(None) is None + assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CompletionServiceGrpcTransport, "grpc"), + (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_completion_service_client_get_transport_class(): + transport = CompletionServiceClient.get_transport_class() + available_transports = [ + transports.CompletionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CompletionServiceClient.get_transport_class("grpc") + assert transport == transports.CompletionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + CompletionServiceClient, CompletionServiceAsyncClient +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_completion_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CompletionServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + ) + response = client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +def test_complete_query_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + client.complete_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + +@pytest.mark.asyncio +async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + )) + response = await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +@pytest.mark.asyncio +async def test_complete_query_async_from_dict(): + await test_complete_query_async(request_type=dict) + + +def test_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) + await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportCompletionDataRequest, + dict, +]) +def test_import_completion_data(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_completion_data_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + client.import_completion_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + +@pytest.mark.asyncio +async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_completion_data_async_from_dict(): + await test_import_completion_data_async(request_type=dict) + + +def test_import_completion_data_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # 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_completion_data_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CompletionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CompletionServiceGrpcTransport, + ) + +def test_completion_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_completion_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'complete_query', + 'import_completion_data', + ) + 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_completion_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_completion_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport() + adc.assert_called_once() + + +def test_completion_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CompletionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionServiceGrpcTransport, grpc_helpers), + (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_completion_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_no_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_with_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_completion_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_completion_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_completion_service_grpc_lro_client(): + client = CompletionServiceClient( + 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_completion_service_grpc_lro_async_client(): + client = CompletionServiceAsyncClient( + 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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CompletionServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CompletionServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CompletionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CompletionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = CompletionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CompletionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CompletionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CompletionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = CompletionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CompletionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CompletionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CompletionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CompletionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py new file mode 100644 index 00000000..0e982c21 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py @@ -0,0 +1,1279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.prediction_service import PredictionServiceAsyncClient +from google.cloud.retail_v2.services.prediction_service import PredictionServiceClient +from google.cloud.retail_v2.services.prediction_service import transports +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import prediction_service +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import promotion +from google.cloud.retail_v2.types import user_event +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PredictionServiceClient._get_default_mtls_endpoint(None) is None + assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionServiceGrpcTransport, "grpc"), + (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_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", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_prediction_service_client_get_transport_class(): + transport = PredictionServiceClient.get_transport_class() + available_transports = [ + transports.PredictionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = PredictionServiceClient.get_transport_class("grpc") + assert transport == transports.PredictionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + PredictionServiceClient, PredictionServiceAsyncClient +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_prediction_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PredictionServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_service.PredictRequest, + dict, +]) +def test_predict(request_type, transport: str = 'grpc'): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + response = client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_predict_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + client.predict() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + +@pytest.mark.asyncio +async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + )) + response = await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +@pytest.mark.asyncio +async def test_predict_async_from_dict(): + await test_predict_async(request_type=dict) + + +def test_predict_field_headers(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_predict_field_headers_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) + await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = PredictionServiceClient.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 = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'predict', + ) + 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport( + 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport() + adc.assert_called_once() + + +def test_prediction_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) + PredictionServiceClient() + 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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +def test_prediction_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,grpc_helpers", + [ + (transports.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_prediction_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_no_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_with_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_prediction_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcTransport( + 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_prediction_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcAsyncIOTransport( + 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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_product_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + product = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + "branch": "winkle", + "product": "nautilus", + } + path = PredictionServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PredictionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = PredictionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = PredictionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = PredictionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PredictionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = PredictionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = PredictionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = PredictionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = PredictionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PredictionServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py new file mode 100644 index 00000000..9d91f54b --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py @@ -0,0 +1,4085 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.product_service import ProductServiceAsyncClient +from google.cloud.retail_v2.services.product_service import ProductServiceClient +from google.cloud.retail_v2.services.product_service import pagers +from google.cloud.retail_v2.services.product_service import transports +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.cloud.retail_v2.types import promotion +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProductServiceClient._get_default_mtls_endpoint(None) is None + assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProductServiceGrpcTransport, "grpc"), + (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_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", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_product_service_client_get_transport_class(): + transport = ProductServiceClient.get_transport_class() + available_transports = [ + transports.ProductServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ProductServiceClient.get_transport_class("grpc") + assert transport == transports.ProductServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_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(ProductServiceClient, '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(ProductServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + ProductServiceClient, ProductServiceAsyncClient +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_product_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProductServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.CreateProductRequest, + dict, +]) +def test_create_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_create_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.create_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + +@pytest.mark.asyncio +async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_create_product_async_from_dict(): + await test_create_product_async(request_type=dict) + + +def test_create_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + + +def test_create_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + +@pytest.mark.asyncio +async def test_create_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_get_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.get_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + +@pytest.mark.asyncio +async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_get_product_async_from_dict(): + await test_get_product_async(request_type=dict) + + +def test_get_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = product.Product() + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.GetProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.GetProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.list_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + +@pytest.mark.asyncio +async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_products_async_from_dict(): + await test_list_products_async(request_type=dict) + + +def test_list_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = product_service.ListProductsResponse() + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products( + 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_products_flattened_error(): + client = ProductServiceClient( + credentials=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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products( + 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_products_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + + +def test_list_products_pager(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_products(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, product.Product) + for i in results) +def test_list_products_pages(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(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_products_async_pager(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(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, product.Product) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_products(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + product_service.UpdateProductRequest, + dict, +]) +def test_update_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_update_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.update_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + +@pytest.mark.asyncio +async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_update_product_async_from_dict(): + await test_update_product_async(request_type=dict) + + +def test_update_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +def test_update_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.DeleteProductRequest, + dict, +]) +def test_delete_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.delete_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + +@pytest.mark.asyncio +async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_product_async_from_dict(): + await test_delete_product_async(request_type=dict) + + +def test_delete_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = None + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportProductsRequest, + dict, +]) +def test_import_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.import_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + +@pytest.mark.asyncio +async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__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_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_products_async_from_dict(): + await test_import_products_async(request_type=dict) + + +def test_import_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + product_service.SetInventoryRequest, + dict, +]) +def test_set_inventory(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_inventory_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + client.set_inventory() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + +@pytest.mark.asyncio +async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_set_inventory_async_from_dict(): + await test_set_inventory_async(request_type=dict) + + +def test_set_inventory_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_inventory_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +def test_set_inventory_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_set_inventory_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_set_inventory_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_inventory_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddFulfillmentPlacesRequest, + dict, +]) +def test_add_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + client.add_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async_from_dict(): + await test_add_fulfillment_places_async(request_type=dict) + + +def test_add_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveFulfillmentPlacesRequest, + dict, +]) +def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + client.remove_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async_from_dict(): + await test_remove_fulfillment_places_async(request_type=dict) + + +def test_remove_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddLocalInventoriesRequest, + dict, +]) +def test_add_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + client.add_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_local_inventories_async_from_dict(): + await test_add_local_inventories_async(request_type=dict) + + +def test_add_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveLocalInventoriesRequest, + dict, +]) +def test_remove_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + client.remove_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_local_inventories_async_from_dict(): + await test_remove_local_inventories_async(request_type=dict) + + +def test_remove_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ProductServiceClient.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 = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProductServiceGrpcTransport, + ) + +def test_product_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_product_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.product_service.transports.ProductServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_product', + 'get_product', + 'list_products', + 'update_product', + 'delete_product', + 'import_products', + 'set_inventory', + 'add_fulfillment_places', + 'remove_fulfillment_places', + 'add_local_inventories', + 'remove_local_inventories', + ) + 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_product_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.retail_v2.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport( + 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_product_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.retail_v2.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport() + adc.assert_called_once() + + +def test_product_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) + ProductServiceClient() + 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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + ], +) +def test_product_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,grpc_helpers", + [ + (transports.ProductServiceGrpcTransport, grpc_helpers), + (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_product_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_no_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_with_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_product_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcTransport( + 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_product_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcAsyncIOTransport( + 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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_product_service_grpc_lro_client(): + client = ProductServiceClient( + 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_product_service_grpc_lro_async_client(): + client = ProductServiceAsyncClient( + 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" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = ProductServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = ProductServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = ProductServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = ProductServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProductServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ProductServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProductServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ProductServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProductServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ProductServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ProductServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ProductServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ProductServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ProductServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ProductServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py new file mode 100644 index 00000000..a9c77623 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py @@ -0,0 +1,1496 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.search_service import SearchServiceAsyncClient +from google.cloud.retail_v2.services.search_service import SearchServiceClient +from google.cloud.retail_v2.services.search_service import pagers +from google.cloud.retail_v2.services.search_service import transports +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import search_service +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SearchServiceClient._get_default_mtls_endpoint(None) is None + assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SearchServiceGrpcTransport, "grpc"), + (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_search_service_client_get_transport_class(): + transport = SearchServiceClient.get_transport_class() + available_transports = [ + transports.SearchServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SearchServiceClient.get_transport_class("grpc") + assert transport == transports.SearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + SearchServiceClient, SearchServiceAsyncClient +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SearchServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + search_service.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + + +def test_search_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = search_service.SearchResponse() + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_search_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('placement', ''), + )), + ) + pager = client.search(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_async_pager(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = SearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_search_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_search_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport() + adc.assert_called_once() + + +def test_search_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SearchServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SearchServiceGrpcTransport, grpc_helpers), + (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_search_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_no_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_with_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_branch_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = SearchServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = SearchServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = SearchServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = SearchServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py new file mode 100644 index 00000000..80f41751 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py @@ -0,0 +1,1988 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.retail_v2.services.user_event_service import UserEventServiceClient +from google.cloud.retail_v2.services.user_event_service import transports +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import promotion +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + ) + response = client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +def test_write_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) + await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeUserEventsRequest, + dict, +]) +def test_purge_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + client.purge_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + +@pytest.mark.asyncio +async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_user_events_async_from_dict(): + await test_purge_user_events_async(request_type=dict) + + +def test_purge_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_purge_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.RejoinUserEventsRequest, + dict, +]) +def test_rejoin_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_rejoin_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + client.rejoin_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + +@pytest.mark.asyncio +async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_rejoin_user_events_async_from_dict(): + await test_rejoin_user_events_async(request_type=dict) + + +def test_rejoin_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_rejoin_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'purge_user_events', + 'import_user_events', + 'rejoin_user_events', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_user_event_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_user_event_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +def test_user_event_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + UserEventServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = UserEventServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = UserEventServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_product_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + product = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + "branch": "whelk", + "product": "octopus", + } + path = UserEventServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2alpha/.coveragerc b/owl-bot-staging/v2alpha/.coveragerc new file mode 100644 index 00000000..a8b114f0 --- /dev/null +++ b/owl-bot-staging/v2alpha/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/retail/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2alpha/.flake8 b/owl-bot-staging/v2alpha/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v2alpha/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v2alpha/MANIFEST.in b/owl-bot-staging/v2alpha/MANIFEST.in new file mode 100644 index 00000000..3ee710cc --- /dev/null +++ b/owl-bot-staging/v2alpha/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/retail *.py +recursive-include google/cloud/retail_v2alpha *.py diff --git a/owl-bot-staging/v2alpha/README.rst b/owl-bot-staging/v2alpha/README.rst new file mode 100644 index 00000000..cb039760 --- /dev/null +++ b/owl-bot-staging/v2alpha/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Retail API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Retail API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2alpha/docs/conf.py b/owl-bot-staging/v2alpha/docs/conf.py new file mode 100644 index 00000000..5be9eb4b --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-retail documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-retail" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-retail-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-retail.tex", + u"google-cloud-retail Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-retail", + u"Google Cloud Retail Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-retail", + u"google-cloud-retail Documentation", + author, + "google-cloud-retail", + "GAPIC library for Google Cloud Retail API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v2alpha/docs/index.rst b/owl-bot-staging/v2alpha/docs/index.rst new file mode 100644 index 00000000..dc0a2096 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + retail_v2alpha/services + retail_v2alpha/types diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst new file mode 100644 index 00000000..745d0cf4 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst @@ -0,0 +1,10 @@ +CatalogService +-------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.catalog_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.catalog_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst new file mode 100644 index 00000000..3a276433 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst @@ -0,0 +1,6 @@ +CompletionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.completion_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst new file mode 100644 index 00000000..36aaf9b6 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst @@ -0,0 +1,10 @@ +ControlService +-------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.control_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.control_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst new file mode 100644 index 00000000..b659cf98 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst @@ -0,0 +1,6 @@ +PredictionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.prediction_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst new file mode 100644 index 00000000..acbb336e --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst @@ -0,0 +1,10 @@ +ProductService +-------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.product_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.product_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst new file mode 100644 index 00000000..ad4c486d --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst @@ -0,0 +1,10 @@ +SearchService +------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst new file mode 100644 index 00000000..edeb8cfc --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst @@ -0,0 +1,13 @@ +Services for Google Cloud Retail v2alpha API +============================================ +.. toctree:: + :maxdepth: 2 + + catalog_service + completion_service + control_service + prediction_service + product_service + search_service + serving_config_service + user_event_service diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst new file mode 100644 index 00000000..c1516860 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst @@ -0,0 +1,10 @@ +ServingConfigService +-------------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.serving_config_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.serving_config_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst new file mode 100644 index 00000000..c1445ad6 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Retail v2alpha API +========================================= + +.. automodule:: google.cloud.retail_v2alpha.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst new file mode 100644 index 00000000..8c56485c --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst @@ -0,0 +1,6 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.user_event_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py new file mode 100644 index 00000000..a17a283b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.retail_v2alpha.services.catalog_service.client import CatalogServiceClient +from google.cloud.retail_v2alpha.services.catalog_service.async_client import CatalogServiceAsyncClient +from google.cloud.retail_v2alpha.services.completion_service.client import CompletionServiceClient +from google.cloud.retail_v2alpha.services.completion_service.async_client import CompletionServiceAsyncClient +from google.cloud.retail_v2alpha.services.control_service.client import ControlServiceClient +from google.cloud.retail_v2alpha.services.control_service.async_client import ControlServiceAsyncClient +from google.cloud.retail_v2alpha.services.prediction_service.client import PredictionServiceClient +from google.cloud.retail_v2alpha.services.prediction_service.async_client import PredictionServiceAsyncClient +from google.cloud.retail_v2alpha.services.product_service.client import ProductServiceClient +from google.cloud.retail_v2alpha.services.product_service.async_client import ProductServiceAsyncClient +from google.cloud.retail_v2alpha.services.search_service.client import SearchServiceClient +from google.cloud.retail_v2alpha.services.search_service.async_client import SearchServiceAsyncClient +from google.cloud.retail_v2alpha.services.serving_config_service.client import ServingConfigServiceClient +from google.cloud.retail_v2alpha.services.serving_config_service.async_client import ServingConfigServiceAsyncClient +from google.cloud.retail_v2alpha.services.user_event_service.client import UserEventServiceClient +from google.cloud.retail_v2alpha.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.retail_v2alpha.types.catalog import AttributesConfig +from google.cloud.retail_v2alpha.types.catalog import Catalog +from google.cloud.retail_v2alpha.types.catalog import CatalogAttribute +from google.cloud.retail_v2alpha.types.catalog import CompletionConfig +from google.cloud.retail_v2alpha.types.catalog import MerchantCenterLink +from google.cloud.retail_v2alpha.types.catalog import MerchantCenterLinkingConfig +from google.cloud.retail_v2alpha.types.catalog import ProductLevelConfig +from google.cloud.retail_v2alpha.types.catalog_service import AddCatalogAttributeRequest +from google.cloud.retail_v2alpha.types.catalog_service import GetAttributesConfigRequest +from google.cloud.retail_v2alpha.types.catalog_service import GetCompletionConfigRequest +from google.cloud.retail_v2alpha.types.catalog_service import GetDefaultBranchRequest +from google.cloud.retail_v2alpha.types.catalog_service import GetDefaultBranchResponse +from google.cloud.retail_v2alpha.types.catalog_service import ListCatalogsRequest +from google.cloud.retail_v2alpha.types.catalog_service import ListCatalogsResponse +from google.cloud.retail_v2alpha.types.catalog_service import RemoveCatalogAttributeRequest +from google.cloud.retail_v2alpha.types.catalog_service import ReplaceCatalogAttributeRequest +from google.cloud.retail_v2alpha.types.catalog_service import SetDefaultBranchRequest +from google.cloud.retail_v2alpha.types.catalog_service import UpdateAttributesConfigRequest +from google.cloud.retail_v2alpha.types.catalog_service import UpdateCatalogRequest +from google.cloud.retail_v2alpha.types.catalog_service import UpdateCompletionConfigRequest +from google.cloud.retail_v2alpha.types.common import Audience +from google.cloud.retail_v2alpha.types.common import ColorInfo +from google.cloud.retail_v2alpha.types.common import Condition +from google.cloud.retail_v2alpha.types.common import CustomAttribute +from google.cloud.retail_v2alpha.types.common import FulfillmentInfo +from google.cloud.retail_v2alpha.types.common import Image +from google.cloud.retail_v2alpha.types.common import Interval +from google.cloud.retail_v2alpha.types.common import LocalInventory +from google.cloud.retail_v2alpha.types.common import PriceInfo +from google.cloud.retail_v2alpha.types.common import Rating +from google.cloud.retail_v2alpha.types.common import Rule +from google.cloud.retail_v2alpha.types.common import UserInfo +from google.cloud.retail_v2alpha.types.common import AttributeConfigLevel +from google.cloud.retail_v2alpha.types.common import SearchSolutionUseCase +from google.cloud.retail_v2alpha.types.common import SolutionType +from google.cloud.retail_v2alpha.types.completion_service import CompleteQueryRequest +from google.cloud.retail_v2alpha.types.completion_service import CompleteQueryResponse +from google.cloud.retail_v2alpha.types.control import Control +from google.cloud.retail_v2alpha.types.control_service import CreateControlRequest +from google.cloud.retail_v2alpha.types.control_service import DeleteControlRequest +from google.cloud.retail_v2alpha.types.control_service import GetControlRequest +from google.cloud.retail_v2alpha.types.control_service import ListControlsRequest +from google.cloud.retail_v2alpha.types.control_service import ListControlsResponse +from google.cloud.retail_v2alpha.types.control_service import UpdateControlRequest +from google.cloud.retail_v2alpha.types.export_config import ExportErrorsConfig +from google.cloud.retail_v2alpha.types.export_config import ExportMetadata +from google.cloud.retail_v2alpha.types.export_config import ExportProductsResponse +from google.cloud.retail_v2alpha.types.export_config import ExportUserEventsResponse +from google.cloud.retail_v2alpha.types.import_config import BigQuerySource +from google.cloud.retail_v2alpha.types.import_config import CompletionDataInputConfig +from google.cloud.retail_v2alpha.types.import_config import GcsSource +from google.cloud.retail_v2alpha.types.import_config import ImportCompletionDataRequest +from google.cloud.retail_v2alpha.types.import_config import ImportCompletionDataResponse +from google.cloud.retail_v2alpha.types.import_config import ImportErrorsConfig +from google.cloud.retail_v2alpha.types.import_config import ImportMetadata +from google.cloud.retail_v2alpha.types.import_config import ImportProductsRequest +from google.cloud.retail_v2alpha.types.import_config import ImportProductsResponse +from google.cloud.retail_v2alpha.types.import_config import ImportUserEventsRequest +from google.cloud.retail_v2alpha.types.import_config import ImportUserEventsResponse +from google.cloud.retail_v2alpha.types.import_config import ProductInlineSource +from google.cloud.retail_v2alpha.types.import_config import ProductInputConfig +from google.cloud.retail_v2alpha.types.import_config import UserEventImportSummary +from google.cloud.retail_v2alpha.types.import_config import UserEventInlineSource +from google.cloud.retail_v2alpha.types.import_config import UserEventInputConfig +from google.cloud.retail_v2alpha.types.prediction_service import PredictRequest +from google.cloud.retail_v2alpha.types.prediction_service import PredictResponse +from google.cloud.retail_v2alpha.types.product import Product +from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesMetadata +from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesRequest +from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesResponse +from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesMetadata +from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesRequest +from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesResponse +from google.cloud.retail_v2alpha.types.product_service import CreateProductRequest +from google.cloud.retail_v2alpha.types.product_service import DeleteProductRequest +from google.cloud.retail_v2alpha.types.product_service import GetProductRequest +from google.cloud.retail_v2alpha.types.product_service import ListProductsRequest +from google.cloud.retail_v2alpha.types.product_service import ListProductsResponse +from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesMetadata +from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesRequest +from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesResponse +from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesMetadata +from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesRequest +from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesResponse +from google.cloud.retail_v2alpha.types.product_service import SetInventoryMetadata +from google.cloud.retail_v2alpha.types.product_service import SetInventoryRequest +from google.cloud.retail_v2alpha.types.product_service import SetInventoryResponse +from google.cloud.retail_v2alpha.types.product_service import UpdateProductRequest +from google.cloud.retail_v2alpha.types.promotion import Promotion +from google.cloud.retail_v2alpha.types.purge_config import PurgeMetadata +from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsMetadata +from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsRequest +from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsResponse +from google.cloud.retail_v2alpha.types.purge_config import PurgeUserEventsRequest +from google.cloud.retail_v2alpha.types.purge_config import PurgeUserEventsResponse +from google.cloud.retail_v2alpha.types.search_service import SearchRequest +from google.cloud.retail_v2alpha.types.search_service import SearchResponse +from google.cloud.retail_v2alpha.types.serving_config import ServingConfig +from google.cloud.retail_v2alpha.types.serving_config_service import AddControlRequest +from google.cloud.retail_v2alpha.types.serving_config_service import CreateServingConfigRequest +from google.cloud.retail_v2alpha.types.serving_config_service import DeleteServingConfigRequest +from google.cloud.retail_v2alpha.types.serving_config_service import GetServingConfigRequest +from google.cloud.retail_v2alpha.types.serving_config_service import ListServingConfigsRequest +from google.cloud.retail_v2alpha.types.serving_config_service import ListServingConfigsResponse +from google.cloud.retail_v2alpha.types.serving_config_service import RemoveControlRequest +from google.cloud.retail_v2alpha.types.serving_config_service import UpdateServingConfigRequest +from google.cloud.retail_v2alpha.types.user_event import CompletionDetail +from google.cloud.retail_v2alpha.types.user_event import ProductDetail +from google.cloud.retail_v2alpha.types.user_event import PurchaseTransaction +from google.cloud.retail_v2alpha.types.user_event import UserEvent +from google.cloud.retail_v2alpha.types.user_event_service import CollectUserEventRequest +from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsMetadata +from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsRequest +from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsResponse +from google.cloud.retail_v2alpha.types.user_event_service import WriteUserEventRequest + +__all__ = ('CatalogServiceClient', + 'CatalogServiceAsyncClient', + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', + 'ControlServiceClient', + 'ControlServiceAsyncClient', + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', + 'ProductServiceClient', + 'ProductServiceAsyncClient', + 'SearchServiceClient', + 'SearchServiceAsyncClient', + 'ServingConfigServiceClient', + 'ServingConfigServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'AttributesConfig', + 'Catalog', + 'CatalogAttribute', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'ProductLevelConfig', + 'AddCatalogAttributeRequest', + 'GetAttributesConfigRequest', + 'GetCompletionConfigRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + 'SetDefaultBranchRequest', + 'UpdateAttributesConfigRequest', + 'UpdateCatalogRequest', + 'UpdateCompletionConfigRequest', + 'Audience', + 'ColorInfo', + 'Condition', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'Rule', + 'UserInfo', + 'AttributeConfigLevel', + 'SearchSolutionUseCase', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Control', + 'CreateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + 'UpdateControlRequest', + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeProductsMetadata', + 'PurgeProductsRequest', + 'PurgeProductsResponse', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'ServingConfig', + 'AddControlRequest', + 'CreateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'RemoveControlRequest', + 'UpdateServingConfigRequest', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail/py.typed b/owl-bot-staging/v2alpha/google/cloud/retail/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py new file mode 100644 index 00000000..e515a173 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.catalog_service import CatalogServiceClient +from .services.catalog_service import CatalogServiceAsyncClient +from .services.completion_service import CompletionServiceClient +from .services.completion_service import CompletionServiceAsyncClient +from .services.control_service import ControlServiceClient +from .services.control_service import ControlServiceAsyncClient +from .services.prediction_service import PredictionServiceClient +from .services.prediction_service import PredictionServiceAsyncClient +from .services.product_service import ProductServiceClient +from .services.product_service import ProductServiceAsyncClient +from .services.search_service import SearchServiceClient +from .services.search_service import SearchServiceAsyncClient +from .services.serving_config_service import ServingConfigServiceClient +from .services.serving_config_service import ServingConfigServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.catalog import AttributesConfig +from .types.catalog import Catalog +from .types.catalog import CatalogAttribute +from .types.catalog import CompletionConfig +from .types.catalog import MerchantCenterLink +from .types.catalog import MerchantCenterLinkingConfig +from .types.catalog import ProductLevelConfig +from .types.catalog_service import AddCatalogAttributeRequest +from .types.catalog_service import GetAttributesConfigRequest +from .types.catalog_service import GetCompletionConfigRequest +from .types.catalog_service import GetDefaultBranchRequest +from .types.catalog_service import GetDefaultBranchResponse +from .types.catalog_service import ListCatalogsRequest +from .types.catalog_service import ListCatalogsResponse +from .types.catalog_service import RemoveCatalogAttributeRequest +from .types.catalog_service import ReplaceCatalogAttributeRequest +from .types.catalog_service import SetDefaultBranchRequest +from .types.catalog_service import UpdateAttributesConfigRequest +from .types.catalog_service import UpdateCatalogRequest +from .types.catalog_service import UpdateCompletionConfigRequest +from .types.common import Audience +from .types.common import ColorInfo +from .types.common import Condition +from .types.common import CustomAttribute +from .types.common import FulfillmentInfo +from .types.common import Image +from .types.common import Interval +from .types.common import LocalInventory +from .types.common import PriceInfo +from .types.common import Rating +from .types.common import Rule +from .types.common import UserInfo +from .types.common import AttributeConfigLevel +from .types.common import SearchSolutionUseCase +from .types.common import SolutionType +from .types.completion_service import CompleteQueryRequest +from .types.completion_service import CompleteQueryResponse +from .types.control import Control +from .types.control_service import CreateControlRequest +from .types.control_service import DeleteControlRequest +from .types.control_service import GetControlRequest +from .types.control_service import ListControlsRequest +from .types.control_service import ListControlsResponse +from .types.control_service import UpdateControlRequest +from .types.export_config import ExportErrorsConfig +from .types.export_config import ExportMetadata +from .types.export_config import ExportProductsResponse +from .types.export_config import ExportUserEventsResponse +from .types.import_config import BigQuerySource +from .types.import_config import CompletionDataInputConfig +from .types.import_config import GcsSource +from .types.import_config import ImportCompletionDataRequest +from .types.import_config import ImportCompletionDataResponse +from .types.import_config import ImportErrorsConfig +from .types.import_config import ImportMetadata +from .types.import_config import ImportProductsRequest +from .types.import_config import ImportProductsResponse +from .types.import_config import ImportUserEventsRequest +from .types.import_config import ImportUserEventsResponse +from .types.import_config import ProductInlineSource +from .types.import_config import ProductInputConfig +from .types.import_config import UserEventImportSummary +from .types.import_config import UserEventInlineSource +from .types.import_config import UserEventInputConfig +from .types.prediction_service import PredictRequest +from .types.prediction_service import PredictResponse +from .types.product import Product +from .types.product_service import AddFulfillmentPlacesMetadata +from .types.product_service import AddFulfillmentPlacesRequest +from .types.product_service import AddFulfillmentPlacesResponse +from .types.product_service import AddLocalInventoriesMetadata +from .types.product_service import AddLocalInventoriesRequest +from .types.product_service import AddLocalInventoriesResponse +from .types.product_service import CreateProductRequest +from .types.product_service import DeleteProductRequest +from .types.product_service import GetProductRequest +from .types.product_service import ListProductsRequest +from .types.product_service import ListProductsResponse +from .types.product_service import RemoveFulfillmentPlacesMetadata +from .types.product_service import RemoveFulfillmentPlacesRequest +from .types.product_service import RemoveFulfillmentPlacesResponse +from .types.product_service import RemoveLocalInventoriesMetadata +from .types.product_service import RemoveLocalInventoriesRequest +from .types.product_service import RemoveLocalInventoriesResponse +from .types.product_service import SetInventoryMetadata +from .types.product_service import SetInventoryRequest +from .types.product_service import SetInventoryResponse +from .types.product_service import UpdateProductRequest +from .types.promotion import Promotion +from .types.purge_config import PurgeMetadata +from .types.purge_config import PurgeProductsMetadata +from .types.purge_config import PurgeProductsRequest +from .types.purge_config import PurgeProductsResponse +from .types.purge_config import PurgeUserEventsRequest +from .types.purge_config import PurgeUserEventsResponse +from .types.search_service import SearchRequest +from .types.search_service import SearchResponse +from .types.serving_config import ServingConfig +from .types.serving_config_service import AddControlRequest +from .types.serving_config_service import CreateServingConfigRequest +from .types.serving_config_service import DeleteServingConfigRequest +from .types.serving_config_service import GetServingConfigRequest +from .types.serving_config_service import ListServingConfigsRequest +from .types.serving_config_service import ListServingConfigsResponse +from .types.serving_config_service import RemoveControlRequest +from .types.serving_config_service import UpdateServingConfigRequest +from .types.user_event import CompletionDetail +from .types.user_event import ProductDetail +from .types.user_event import PurchaseTransaction +from .types.user_event import UserEvent +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import RejoinUserEventsMetadata +from .types.user_event_service import RejoinUserEventsRequest +from .types.user_event_service import RejoinUserEventsResponse +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CatalogServiceAsyncClient', + 'CompletionServiceAsyncClient', + 'ControlServiceAsyncClient', + 'PredictionServiceAsyncClient', + 'ProductServiceAsyncClient', + 'SearchServiceAsyncClient', + 'ServingConfigServiceAsyncClient', + 'UserEventServiceAsyncClient', +'AddCatalogAttributeRequest', +'AddControlRequest', +'AddFulfillmentPlacesMetadata', +'AddFulfillmentPlacesRequest', +'AddFulfillmentPlacesResponse', +'AddLocalInventoriesMetadata', +'AddLocalInventoriesRequest', +'AddLocalInventoriesResponse', +'AttributeConfigLevel', +'AttributesConfig', +'Audience', +'BigQuerySource', +'Catalog', +'CatalogAttribute', +'CatalogServiceClient', +'CollectUserEventRequest', +'ColorInfo', +'CompleteQueryRequest', +'CompleteQueryResponse', +'CompletionConfig', +'CompletionDataInputConfig', +'CompletionDetail', +'CompletionServiceClient', +'Condition', +'Control', +'ControlServiceClient', +'CreateControlRequest', +'CreateProductRequest', +'CreateServingConfigRequest', +'CustomAttribute', +'DeleteControlRequest', +'DeleteProductRequest', +'DeleteServingConfigRequest', +'ExportErrorsConfig', +'ExportMetadata', +'ExportProductsResponse', +'ExportUserEventsResponse', +'FulfillmentInfo', +'GcsSource', +'GetAttributesConfigRequest', +'GetCompletionConfigRequest', +'GetControlRequest', +'GetDefaultBranchRequest', +'GetDefaultBranchResponse', +'GetProductRequest', +'GetServingConfigRequest', +'Image', +'ImportCompletionDataRequest', +'ImportCompletionDataResponse', +'ImportErrorsConfig', +'ImportMetadata', +'ImportProductsRequest', +'ImportProductsResponse', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'Interval', +'ListCatalogsRequest', +'ListCatalogsResponse', +'ListControlsRequest', +'ListControlsResponse', +'ListProductsRequest', +'ListProductsResponse', +'ListServingConfigsRequest', +'ListServingConfigsResponse', +'LocalInventory', +'MerchantCenterLink', +'MerchantCenterLinkingConfig', +'PredictRequest', +'PredictResponse', +'PredictionServiceClient', +'PriceInfo', +'Product', +'ProductDetail', +'ProductInlineSource', +'ProductInputConfig', +'ProductLevelConfig', +'ProductServiceClient', +'Promotion', +'PurchaseTransaction', +'PurgeMetadata', +'PurgeProductsMetadata', +'PurgeProductsRequest', +'PurgeProductsResponse', +'PurgeUserEventsRequest', +'PurgeUserEventsResponse', +'Rating', +'RejoinUserEventsMetadata', +'RejoinUserEventsRequest', +'RejoinUserEventsResponse', +'RemoveCatalogAttributeRequest', +'RemoveControlRequest', +'RemoveFulfillmentPlacesMetadata', +'RemoveFulfillmentPlacesRequest', +'RemoveFulfillmentPlacesResponse', +'RemoveLocalInventoriesMetadata', +'RemoveLocalInventoriesRequest', +'RemoveLocalInventoriesResponse', +'ReplaceCatalogAttributeRequest', +'Rule', +'SearchRequest', +'SearchResponse', +'SearchServiceClient', +'SearchSolutionUseCase', +'ServingConfig', +'ServingConfigServiceClient', +'SetDefaultBranchRequest', +'SetInventoryMetadata', +'SetInventoryRequest', +'SetInventoryResponse', +'SolutionType', +'UpdateAttributesConfigRequest', +'UpdateCatalogRequest', +'UpdateCompletionConfigRequest', +'UpdateControlRequest', +'UpdateProductRequest', +'UpdateServingConfigRequest', +'UserEvent', +'UserEventImportSummary', +'UserEventInlineSource', +'UserEventInputConfig', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json new file mode 100644 index 00000000..543e36d6 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json @@ -0,0 +1,561 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.retail_v2alpha", + "protoPackage": "google.cloud.retail.v2alpha", + "schema": "1.0", + "services": { + "CatalogService": { + "clients": { + "grpc": { + "libraryClient": "CatalogServiceClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "add_catalog_attribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "get_attributes_config" + ] + }, + "GetCompletionConfig": { + "methods": [ + "get_completion_config" + ] + }, + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "remove_catalog_attribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "replace_catalog_attribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "update_attributes_config" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "update_completion_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CatalogServiceAsyncClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "add_catalog_attribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "get_attributes_config" + ] + }, + "GetCompletionConfig": { + "methods": [ + "get_completion_config" + ] + }, + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "remove_catalog_attribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "replace_catalog_attribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "update_attributes_config" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "update_completion_config" + ] + } + } + } + } + }, + "CompletionService": { + "clients": { + "grpc": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CompletionServiceAsyncClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + } + } + }, + "ControlService": { + "clients": { + "grpc": { + "libraryClient": "ControlServiceClient", + "rpcs": { + "CreateControl": { + "methods": [ + "create_control" + ] + }, + "DeleteControl": { + "methods": [ + "delete_control" + ] + }, + "GetControl": { + "methods": [ + "get_control" + ] + }, + "ListControls": { + "methods": [ + "list_controls" + ] + }, + "UpdateControl": { + "methods": [ + "update_control" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ControlServiceAsyncClient", + "rpcs": { + "CreateControl": { + "methods": [ + "create_control" + ] + }, + "DeleteControl": { + "methods": [ + "delete_control" + ] + }, + "GetControl": { + "methods": [ + "get_control" + ] + }, + "ListControls": { + "methods": [ + "list_controls" + ] + }, + "UpdateControl": { + "methods": [ + "update_control" + ] + } + } + } + } + }, + "PredictionService": { + "clients": { + "grpc": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionServiceAsyncClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + } + } + }, + "ProductService": { + "clients": { + "grpc": { + "libraryClient": "ProductServiceClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "PurgeProducts": { + "methods": [ + "purge_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductServiceAsyncClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "PurgeProducts": { + "methods": [ + "purge_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + } + } + }, + "SearchService": { + "clients": { + "grpc": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SearchServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + }, + "ServingConfigService": { + "clients": { + "grpc": { + "libraryClient": "ServingConfigServiceClient", + "rpcs": { + "AddControl": { + "methods": [ + "add_control" + ] + }, + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, + "RemoveControl": { + "methods": [ + "remove_control" + ] + }, + "UpdateServingConfig": { + "methods": [ + "update_serving_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServingConfigServiceAsyncClient", + "rpcs": { + "AddControl": { + "methods": [ + "add_control" + ] + }, + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, + "RemoveControl": { + "methods": [ + "remove_control" + ] + }, + "UpdateServingConfig": { + "methods": [ + "update_serving_config" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py new file mode 100644 index 00000000..d276b897 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CatalogServiceClient +from .async_client import CatalogServiceAsyncClient + +__all__ = ( + 'CatalogServiceClient', + 'CatalogServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py new file mode 100644 index 00000000..e828ae6f --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py @@ -0,0 +1,1352 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.catalog_service import pagers +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport +from .client import CatalogServiceClient + + +class CatalogServiceAsyncClient: + """Service for managing catalog configuration.""" + + _client: CatalogServiceClient + + DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT + + attributes_config_path = staticmethod(CatalogServiceClient.attributes_config_path) + parse_attributes_config_path = staticmethod(CatalogServiceClient.parse_attributes_config_path) + branch_path = staticmethod(CatalogServiceClient.branch_path) + parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) + catalog_path = staticmethod(CatalogServiceClient.catalog_path) + parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) + completion_config_path = staticmethod(CatalogServiceClient.completion_config_path) + parse_completion_config_path = staticmethod(CatalogServiceClient.parse_completion_config_path) + common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CatalogServiceClient.common_project_path) + parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) + common_location_path = staticmethod(CatalogServiceClient.common_location_path) + parse_common_location_path = staticmethod(CatalogServiceClient.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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CatalogServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsAsyncPager: + r"""Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_list_catalogs(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + parent (:class:`str`): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2alpha.Catalog]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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsAsyncPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.ListCatalogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_catalogs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCatalogsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_catalog(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2alpha.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2alpha.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] + method. + catalog (:class:`google.cloud.retail_v2alpha.types.Catalog`): + Required. The + [Catalog][google.cloud.retail.v2alpha.Catalog] to + update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2alpha.Catalog], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Catalog][google.cloud.retail.v2alpha.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2alpha.Catalog] to + update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_catalog, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_set_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (:class:`str`): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.SetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (:class:`str`): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # 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_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_completion_config(self, + request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Gets a + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] + method. + name (:class:`str`): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + + 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.retail_v2alpha.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetCompletionConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_completion_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_completion_config(self, + request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, + *, + completion_config: catalog.CompletionConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Updates the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + completion_config = retail_v2alpha.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2alpha.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = await client.update_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] + method. + completion_config (:class:`google.cloud.retail_v2alpha.types.CompletionConfig`): + Required. The + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``completion_config`` 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 + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([completion_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCompletionConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if completion_config is not None: + request.completion_config = completion_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_completion_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("completion_config.name", request.completion_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_attributes_config(self, + request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Gets an + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] + method. + name (:class:`str`): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + + 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.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetAttributesConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_attributes_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_attributes_config(self, + request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, + *, + attributes_config: catalog.AttributesConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Updates the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + attributes_config = retail_v2alpha.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2alpha.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = await client.update_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] + method. + attributes_config (:class:`google.cloud.retail_v2alpha.types.AttributesConfig`): + Required. The + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. + + This corresponds to the ``attributes_config`` 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 + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attributes_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateAttributesConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attributes_config is not None: + request.attributes_config = attributes_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_attributes_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config.name", request.attributes_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_catalog_attribute(self, + request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Adds the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_add_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.AddCatalogAttributeRequest(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.add_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_catalog_attribute(self, + request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Removes the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = await client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.RemoveCatalogAttributeRequest(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.remove_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def replace_catalog_attribute(self, + request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Replaces the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.ReplaceCatalogAttributeRequest(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.replace_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py new file mode 100644 index 00000000..19946bec --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py @@ -0,0 +1,1581 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.catalog_service import pagers +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CatalogServiceGrpcTransport +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +class CatalogServiceClientMeta(type): + """Metaclass for the CatalogService 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[CatalogServiceTransport]] + _transport_registry["grpc"] = CatalogServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CatalogServiceTransport]: + """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): + """Service for managing catalog configuration.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CatalogServiceClient: 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: + CatalogServiceClient: 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) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def attributes_config_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified attributes_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_attributes_config_path(path: str) -> Dict[str,str]: + """Parses a attributes_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/attributesConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def completion_config_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified completion_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_completion_config_path(path: str) -> Dict[str,str]: + """Parses a completion_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/completionConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CatalogServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CatalogServiceTransport): + # transport is a CatalogServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsPager: + r"""Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_list_catalogs(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2alpha.Catalog]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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ListCatalogsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ListCatalogsRequest): + request = catalog_service.ListCatalogsRequest(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_catalogs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCatalogsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_catalog(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2alpha.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2alpha.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] + method. + catalog (google.cloud.retail_v2alpha.types.Catalog): + Required. The + [Catalog][google.cloud.retail.v2alpha.Catalog] to + update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2alpha.Catalog], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Catalog][google.cloud.retail.v2alpha.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2alpha.Catalog] to + update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCatalogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCatalogRequest): + request = catalog_service.UpdateCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + 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_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_set_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.SetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.SetDefaultBranchRequest): + request = catalog_service.SetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetDefaultBranchRequest): + request = catalog_service.GetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_completion_config(self, + request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Gets a + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] + method. + name (str): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + + 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.retail_v2alpha.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetCompletionConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetCompletionConfigRequest): + request = catalog_service.GetCompletionConfigRequest(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_completion_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_completion_config(self, + request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, + *, + completion_config: catalog.CompletionConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Updates the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + completion_config = retail_v2alpha.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2alpha.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = client.update_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] + method. + completion_config (google.cloud.retail_v2alpha.types.CompletionConfig): + Required. The + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``completion_config`` 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 + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([completion_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCompletionConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCompletionConfigRequest): + request = catalog_service.UpdateCompletionConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if completion_config is not None: + request.completion_config = completion_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_completion_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("completion_config.name", request.completion_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_attributes_config(self, + request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Gets an + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] + method. + name (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + + 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.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetAttributesConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetAttributesConfigRequest): + request = catalog_service.GetAttributesConfigRequest(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_attributes_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_attributes_config(self, + request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, + *, + attributes_config: catalog.AttributesConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Updates the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + attributes_config = retail_v2alpha.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2alpha.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = client.update_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] + method. + attributes_config (google.cloud.retail_v2alpha.types.AttributesConfig): + Required. The + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. + + This corresponds to the ``attributes_config`` 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 + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attributes_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateAttributesConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateAttributesConfigRequest): + request = catalog_service.UpdateAttributesConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attributes_config is not None: + request.attributes_config = attributes_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_attributes_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config.name", request.attributes_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_catalog_attribute(self, + request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Adds the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_add_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.AddCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.AddCatalogAttributeRequest): + request = catalog_service.AddCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_catalog_attribute(self, + request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Removes the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.RemoveCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.RemoveCatalogAttributeRequest): + request = catalog_service.RemoveCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def replace_catalog_attribute(self, + request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Replaces the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ReplaceCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ReplaceCatalogAttributeRequest): + request = catalog_service.ReplaceCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.replace_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py new file mode 100644 index 00000000..f78d4bfa --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog_service + + +class ListCatalogsPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` + 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[..., catalog_service.ListCatalogsResponse], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2alpha.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + for page in self.pages: + yield from page.catalogs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCatalogsAsyncPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` + 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[catalog_service.ListCatalogsResponse]], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2alpha.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + async def async_generator(): + async for page in self.pages: + for response in page.catalogs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py new file mode 100644 index 00000000..0cffa336 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 CatalogServiceTransport +from .grpc import CatalogServiceGrpcTransport +from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] +_transport_registry['grpc'] = CatalogServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport + +__all__ = ( + 'CatalogServiceTransport', + 'CatalogServiceGrpcTransport', + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py new file mode 100644 index 00000000..f64dcf11 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py @@ -0,0 +1,293 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CatalogServiceTransport(abc.ABC): + """Abstract transport class for CatalogService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_catalogs: gapic_v1.method.wrap_method( + self.list_catalogs, + default_timeout=None, + client_info=client_info, + ), + self.update_catalog: gapic_v1.method.wrap_method( + self.update_catalog, + default_timeout=None, + client_info=client_info, + ), + self.set_default_branch: gapic_v1.method.wrap_method( + self.set_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_default_branch: gapic_v1.method.wrap_method( + self.get_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_completion_config: gapic_v1.method.wrap_method( + self.get_completion_config, + default_timeout=None, + client_info=client_info, + ), + self.update_completion_config: gapic_v1.method.wrap_method( + self.update_completion_config, + default_timeout=None, + client_info=client_info, + ), + self.get_attributes_config: gapic_v1.method.wrap_method( + self.get_attributes_config, + default_timeout=None, + client_info=client_info, + ), + self.update_attributes_config: gapic_v1.method.wrap_method( + self.update_attributes_config, + default_timeout=None, + client_info=client_info, + ), + self.add_catalog_attribute: gapic_v1.method.wrap_method( + self.add_catalog_attribute, + default_timeout=None, + client_info=client_info, + ), + self.remove_catalog_attribute: gapic_v1.method.wrap_method( + self.remove_catalog_attribute, + default_timeout=None, + client_info=client_info, + ), + self.replace_catalog_attribute: gapic_v1.method.wrap_method( + self.replace_catalog_attribute, + 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Union[ + catalog_service.ListCatalogsResponse, + Awaitable[catalog_service.ListCatalogsResponse] + ]]: + raise NotImplementedError() + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Union[ + gcr_catalog.Catalog, + Awaitable[gcr_catalog.Catalog] + ]]: + raise NotImplementedError() + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Union[ + catalog_service.GetDefaultBranchResponse, + Awaitable[catalog_service.GetDefaultBranchResponse] + ]]: + raise NotImplementedError() + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + Union[ + catalog.CompletionConfig, + Awaitable[catalog.CompletionConfig] + ]]: + raise NotImplementedError() + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + Union[ + catalog.CompletionConfig, + Awaitable[catalog.CompletionConfig] + ]]: + raise NotImplementedError() + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CatalogServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py new file mode 100644 index 00000000..29c4a6cd --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py @@ -0,0 +1,598 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO + + +class CatalogServiceGrpcTransport(CatalogServiceTransport): + """gRPC backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + catalog_service.ListCatalogsResponse]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + ~.ListCatalogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + gcr_catalog.Catalog]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + ~.Catalog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + empty_pb2.Empty]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + ~.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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + catalog_service.GetDefaultBranchResponse]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + ~.GetDefaultBranchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + catalog.CompletionConfig]: + r"""Return a callable for the get completion config method over gRPC. + + Gets a + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. + + Returns: + Callable[[~.GetCompletionConfigRequest], + ~.CompletionConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetCompletionConfig', + request_serializer=catalog_service.GetCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['get_completion_config'] + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + catalog.CompletionConfig]: + r"""Return a callable for the update completion config method over gRPC. + + Updates the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. + + Returns: + Callable[[~.UpdateCompletionConfigRequest], + ~.CompletionConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateCompletionConfig', + request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['update_completion_config'] + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + catalog.AttributesConfig]: + r"""Return a callable for the get attributes config method over gRPC. + + Gets an + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + Returns: + Callable[[~.GetAttributesConfigRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetAttributesConfig', + request_serializer=catalog_service.GetAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['get_attributes_config'] + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + catalog.AttributesConfig]: + r"""Return a callable for the update attributes config method over gRPC. + + Updates the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + Returns: + Callable[[~.UpdateAttributesConfigRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateAttributesConfig', + request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['update_attributes_config'] + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the add catalog attribute method over gRPC. + + Adds the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.AddCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_catalog_attribute' not in self._stubs: + self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/AddCatalogAttribute', + request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['add_catalog_attribute'] + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the remove catalog attribute method over gRPC. + + Removes the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.RemoveCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_catalog_attribute' not in self._stubs: + self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/RemoveCatalogAttribute', + request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['remove_catalog_attribute'] + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the replace catalog attribute method over gRPC. + + Replaces the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.ReplaceCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_catalog_attribute' not in self._stubs: + self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/ReplaceCatalogAttribute', + request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['replace_catalog_attribute'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CatalogServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..980169e6 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py @@ -0,0 +1,597 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CatalogServiceGrpcTransport + + +class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): + """gRPC AsyncIO backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Awaitable[catalog_service.ListCatalogsResponse]]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + Awaitable[~.ListCatalogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Awaitable[gcr_catalog.Catalog]]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + Awaitable[~.Catalog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + 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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Awaitable[catalog_service.GetDefaultBranchResponse]]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + Awaitable[~.GetDefaultBranchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + Awaitable[catalog.CompletionConfig]]: + r"""Return a callable for the get completion config method over gRPC. + + Gets a + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. + + Returns: + Callable[[~.GetCompletionConfigRequest], + Awaitable[~.CompletionConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetCompletionConfig', + request_serializer=catalog_service.GetCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['get_completion_config'] + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + Awaitable[catalog.CompletionConfig]]: + r"""Return a callable for the update completion config method over gRPC. + + Updates the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. + + Returns: + Callable[[~.UpdateCompletionConfigRequest], + Awaitable[~.CompletionConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateCompletionConfig', + request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['update_completion_config'] + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the get attributes config method over gRPC. + + Gets an + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + Returns: + Callable[[~.GetAttributesConfigRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetAttributesConfig', + request_serializer=catalog_service.GetAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['get_attributes_config'] + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the update attributes config method over gRPC. + + Updates the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + Returns: + Callable[[~.UpdateAttributesConfigRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateAttributesConfig', + request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['update_attributes_config'] + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the add catalog attribute method over gRPC. + + Adds the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.AddCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_catalog_attribute' not in self._stubs: + self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/AddCatalogAttribute', + request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['add_catalog_attribute'] + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the remove catalog attribute method over gRPC. + + Removes the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.RemoveCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_catalog_attribute' not in self._stubs: + self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/RemoveCatalogAttribute', + request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['remove_catalog_attribute'] + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the replace catalog attribute method over gRPC. + + Replaces the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.ReplaceCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_catalog_attribute' not in self._stubs: + self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/ReplaceCatalogAttribute', + request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['replace_catalog_attribute'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py new file mode 100644 index 00000000..b8af95bd --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CompletionServiceClient +from .async_client import CompletionServiceAsyncClient + +__all__ = ( + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py new file mode 100644 index 00000000..74888568 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .client import CompletionServiceClient + + +class CompletionServiceAsyncClient: + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: CompletionServiceClient + + DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(CompletionServiceClient.catalog_path) + parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) + common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CompletionServiceClient.common_project_path) + parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) + common_location_path = staticmethod(CompletionServiceClient.common_location_path) + parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CompletionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_complete_query(): + # Create a client + client = retail_v2alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_query, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_import_completion_data(): + # Create a client + client = retail_v2alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2alpha.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. + 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. + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_completion_data, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py new file mode 100644 index 00000000..e6906cf6 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py @@ -0,0 +1,592 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CompletionServiceGrpcTransport +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +class CompletionServiceClientMeta(type): + """Metaclass for the CompletionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] + _transport_registry["grpc"] = CompletionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CompletionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CompletionServiceClient(metaclass=CompletionServiceClientMeta): + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CompletionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CompletionServiceTransport): + # transport is a CompletionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_complete_query(): + # Create a client + client = retail_v2alpha.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a completion_service.CompleteQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, completion_service.CompleteQueryRequest): + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_import_completion_data(): + # Create a client + client = retail_v2alpha.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2alpha.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. + 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. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportCompletionDataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportCompletionDataRequest): + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_completion_data] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py new file mode 100644 index 00000000..a0c9542f --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CompletionServiceTransport +from .grpc import CompletionServiceGrpcTransport +from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] +_transport_registry['grpc'] = CompletionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport + +__all__ = ( + 'CompletionServiceTransport', + 'CompletionServiceGrpcTransport', + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py new file mode 100644 index 00000000..e7d6bf06 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CompletionServiceTransport(abc.ABC): + """Abstract transport class for CompletionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.complete_query: gapic_v1.method.wrap_method( + self.complete_query, + default_timeout=None, + client_info=client_info, + ), + self.import_completion_data: gapic_v1.method.wrap_method( + self.import_completion_data, + 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Union[ + completion_service.CompleteQueryResponse, + Awaitable[completion_service.CompleteQueryResponse] + ]]: + raise NotImplementedError() + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CompletionServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py new file mode 100644 index 00000000..6cab5b09 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py @@ -0,0 +1,323 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO + + +class CompletionServiceGrpcTransport(CompletionServiceTransport): + """gRPC backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + ~.CompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + operations_pb2.Operation]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CompletionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..62e55fcb --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py @@ -0,0 +1,322 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CompletionServiceGrpcTransport + + +class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): + """gRPC AsyncIO backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Awaitable[completion_service.CompleteQueryResponse]]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + Awaitable[~.CompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + 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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py new file mode 100644 index 00000000..e9a7be2f --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ControlServiceClient +from .async_client import ControlServiceAsyncClient + +__all__ = ( + 'ControlServiceClient', + 'ControlServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py new file mode 100644 index 00000000..e32d838b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py @@ -0,0 +1,744 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.control_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.cloud.retail_v2alpha.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport +from .client import ControlServiceClient + + +class ControlServiceAsyncClient: + """Service for modifying Control.""" + + _client: ControlServiceClient + + DEFAULT_ENDPOINT = ControlServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ControlServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(ControlServiceClient.catalog_path) + parse_catalog_path = staticmethod(ControlServiceClient.parse_catalog_path) + control_path = staticmethod(ControlServiceClient.control_path) + parse_control_path = staticmethod(ControlServiceClient.parse_control_path) + common_billing_account_path = staticmethod(ControlServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ControlServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ControlServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ControlServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ControlServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ControlServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ControlServiceClient.common_project_path) + parse_common_project_path = staticmethod(ControlServiceClient.parse_common_project_path) + common_location_path = staticmethod(ControlServiceClient.common_location_path) + parse_common_location_path = staticmethod(ControlServiceClient.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: + ControlServiceAsyncClient: The constructed client. + """ + return ControlServiceClient.from_service_account_info.__func__(ControlServiceAsyncClient, 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: + ControlServiceAsyncClient: The constructed client. + """ + return ControlServiceClient.from_service_account_file.__func__(ControlServiceAsyncClient, 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 variabel 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 ControlServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ControlServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ControlServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ControlServiceClient).get_transport_class, type(ControlServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ControlServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the control service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ControlServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ControlServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_control(self, + request: Union[control_service.CreateControlRequest, dict] = None, + *, + parent: str = None, + control: gcr_control.Control = None, + control_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Creates a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_create_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = await client.create_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateControlRequest, dict]): + The request object. Request for CreateControl method. + parent (:class:`str`): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control (:class:`google.cloud.retail_v2alpha.types.Control`): + Required. The Control to create. + This corresponds to the ``control`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control_id (:class:`str`): + Required. The ID to use for the Control, which will + become the final component of the Control's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``control_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.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, control, control_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.CreateControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if control is not None: + request.control = control + if control_id is not None: + request.control_id = control_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_control(self, + request: Union[control_service.DeleteControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_delete_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteControlRequest( + name="name_value", + ) + + # Make the request + await client.delete_control(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteControlRequest, dict]): + The request object. Request for DeleteControl method. + name (:class:`str`): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.DeleteControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_control(self, + request: Union[control_service.UpdateControlRequest, dict] = None, + *, + control: gcr_control.Control = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Updates a Control. + + [Control][google.cloud.retail.v2alpha.Control] cannot be set to + a different oneof field, if so an INVALID_ARGUMENT is returned. + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.UpdateControlRequest( + control=control, + ) + + # Make the request + response = await client.update_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateControlRequest, dict]): + The request object. Request for UpdateControl method. + control (:class:`google.cloud.retail_v2alpha.types.Control`): + Required. The Control to update. + This corresponds to the ``control`` 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 + [Control][google.cloud.retail.v2alpha.Control] to + update. The following are NOT supported: + + - [Control.name][google.cloud.retail.v2alpha.Control.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([control, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.UpdateControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if control is not None: + request.control = control + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("control.name", request.control.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_control(self, + request: Union[control_service.GetControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> control.Control: + r"""Gets a Control. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetControlRequest( + name="name_value", + ) + + # Make the request + response = await client.get_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetControlRequest, dict]): + The request object. Request for GetControl method. + name (:class:`str`): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.GetControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_controls(self, + request: Union[control_service.ListControlsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListControlsAsyncPager: + r"""Lists all Controls linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_list_controls(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListControlsRequest, dict]): + The request object. Request for ListControls method. + parent (:class:`str`): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.control_service.pagers.ListControlsAsyncPager: + Response for ListControls method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.ListControlsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_controls, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListControlsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ControlServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py new file mode 100644 index 00000000..8b58ebd1 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py @@ -0,0 +1,952 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.control_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.cloud.retail_v2alpha.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ControlServiceGrpcTransport +from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport + + +class ControlServiceClientMeta(type): + """Metaclass for the ControlService 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[ControlServiceTransport]] + _transport_registry["grpc"] = ControlServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ControlServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ControlServiceTransport]: + """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 ControlServiceClient(metaclass=ControlServiceClientMeta): + """Service for modifying Control.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ControlServiceClient: 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: + ControlServiceClient: 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) -> ControlServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ControlServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def control_path(project: str,location: str,catalog: str,control: str,) -> str: + """Returns a fully-qualified control string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) + + @staticmethod + def parse_control_path(path: str) -> Dict[str,str]: + """Parses a control path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/controls/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ControlServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the control service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ControlServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ControlServiceTransport): + # transport is a ControlServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_control(self, + request: Union[control_service.CreateControlRequest, dict] = None, + *, + parent: str = None, + control: gcr_control.Control = None, + control_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Creates a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_create_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = client.create_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateControlRequest, dict]): + The request object. Request for CreateControl method. + parent (str): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control (google.cloud.retail_v2alpha.types.Control): + Required. The Control to create. + This corresponds to the ``control`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control_id (str): + Required. The ID to use for the Control, which will + become the final component of the Control's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``control_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.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, control, control_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.CreateControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.CreateControlRequest): + request = control_service.CreateControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if control is not None: + request.control = control + if control_id is not None: + request.control_id = control_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_control(self, + request: Union[control_service.DeleteControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_delete_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteControlRequest( + name="name_value", + ) + + # Make the request + client.delete_control(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteControlRequest, dict]): + The request object. Request for DeleteControl method. + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.DeleteControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.DeleteControlRequest): + request = control_service.DeleteControlRequest(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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_control(self, + request: Union[control_service.UpdateControlRequest, dict] = None, + *, + control: gcr_control.Control = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Updates a Control. + + [Control][google.cloud.retail.v2alpha.Control] cannot be set to + a different oneof field, if so an INVALID_ARGUMENT is returned. + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.UpdateControlRequest( + control=control, + ) + + # Make the request + response = client.update_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateControlRequest, dict]): + The request object. Request for UpdateControl method. + control (google.cloud.retail_v2alpha.types.Control): + Required. The Control to update. + This corresponds to the ``control`` 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 + [Control][google.cloud.retail.v2alpha.Control] to + update. The following are NOT supported: + + - [Control.name][google.cloud.retail.v2alpha.Control.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([control, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.UpdateControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.UpdateControlRequest): + request = control_service.UpdateControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if control is not None: + request.control = control + 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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("control.name", request.control.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_control(self, + request: Union[control_service.GetControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> control.Control: + r"""Gets a Control. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetControlRequest( + name="name_value", + ) + + # Make the request + response = client.get_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetControlRequest, dict]): + The request object. Request for GetControl method. + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.GetControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.GetControlRequest): + request = control_service.GetControlRequest(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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_controls(self, + request: Union[control_service.ListControlsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListControlsPager: + r"""Lists all Controls linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_list_controls(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListControlsRequest, dict]): + The request object. Request for ListControls method. + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.control_service.pagers.ListControlsPager: + Response for ListControls method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.ListControlsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.ListControlsRequest): + request = control_service.ListControlsRequest(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_controls] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListControlsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ControlServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py new file mode 100644 index 00000000..d1c28748 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control_service + + +class ListControlsPager: + """A pager for iterating through ``list_controls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``controls`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListControls`` requests and continue to iterate + through the ``controls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` + 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[..., control_service.ListControlsResponse], + request: control_service.ListControlsRequest, + response: control_service.ListControlsResponse, + *, + 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.retail_v2alpha.types.ListControlsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListControlsResponse): + 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 = control_service.ListControlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[control_service.ListControlsResponse]: + 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[control.Control]: + for page in self.pages: + yield from page.controls + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListControlsAsyncPager: + """A pager for iterating through ``list_controls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``controls`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListControls`` requests and continue to iterate + through the ``controls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` + 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[control_service.ListControlsResponse]], + request: control_service.ListControlsRequest, + response: control_service.ListControlsResponse, + *, + 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.retail_v2alpha.types.ListControlsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListControlsResponse): + 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 = control_service.ListControlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[control_service.ListControlsResponse]: + 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[control.Control]: + async def async_generator(): + async for page in self.pages: + for response in page.controls: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py new file mode 100644 index 00000000..3622876b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ControlServiceTransport +from .grpc import ControlServiceGrpcTransport +from .grpc_asyncio import ControlServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ControlServiceTransport]] +_transport_registry['grpc'] = ControlServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ControlServiceGrpcAsyncIOTransport + +__all__ = ( + 'ControlServiceTransport', + 'ControlServiceGrpcTransport', + 'ControlServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py new file mode 100644 index 00000000..e6390673 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py @@ -0,0 +1,209 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ControlServiceTransport(abc.ABC): + """Abstract transport class for ControlService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_control: gapic_v1.method.wrap_method( + self.create_control, + default_timeout=None, + client_info=client_info, + ), + self.delete_control: gapic_v1.method.wrap_method( + self.delete_control, + default_timeout=None, + client_info=client_info, + ), + self.update_control: gapic_v1.method.wrap_method( + self.update_control, + default_timeout=None, + client_info=client_info, + ), + self.get_control: gapic_v1.method.wrap_method( + self.get_control, + default_timeout=None, + client_info=client_info, + ), + self.list_controls: gapic_v1.method.wrap_method( + self.list_controls, + 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 create_control(self) -> Callable[ + [control_service.CreateControlRequest], + Union[ + gcr_control.Control, + Awaitable[gcr_control.Control] + ]]: + raise NotImplementedError() + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + Union[ + gcr_control.Control, + Awaitable[gcr_control.Control] + ]]: + raise NotImplementedError() + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + Union[ + control.Control, + Awaitable[control.Control] + ]]: + raise NotImplementedError() + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + Union[ + control_service.ListControlsResponse, + Awaitable[control_service.ListControlsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ControlServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py new file mode 100644 index 00000000..e2e2a244 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py @@ -0,0 +1,380 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO + + +class ControlServiceGrpcTransport(ControlServiceTransport): + """gRPC backend transport for ControlService. + + Service for modifying Control. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_control(self) -> Callable[ + [control_service.CreateControlRequest], + gcr_control.Control]: + r"""Return a callable for the create control method over gRPC. + + Creates a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['create_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/CreateControl', + request_serializer=control_service.CreateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['create_control'] + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete control method over gRPC. + + Deletes a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteControlRequest], + ~.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_control' not in self._stubs: + self._stubs['delete_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/DeleteControl', + request_serializer=control_service.DeleteControlRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_control'] + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + gcr_control.Control]: + r"""Return a callable for the update control method over gRPC. + + Updates a Control. + + [Control][google.cloud.retail.v2alpha.Control] cannot be set to + a different oneof field, if so an INVALID_ARGUMENT is returned. + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['update_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/UpdateControl', + request_serializer=control_service.UpdateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['update_control'] + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + control.Control]: + r"""Return a callable for the get control method over gRPC. + + Gets a Control. + + Returns: + Callable[[~.GetControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['get_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/GetControl', + request_serializer=control_service.GetControlRequest.serialize, + response_deserializer=control.Control.deserialize, + ) + return self._stubs['get_control'] + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + control_service.ListControlsResponse]: + r"""Return a callable for the list controls method over gRPC. + + Lists all Controls linked to this catalog. + + Returns: + Callable[[~.ListControlsRequest], + ~.ListControlsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_controls' not in self._stubs: + self._stubs['list_controls'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/ListControls', + request_serializer=control_service.ListControlsRequest.serialize, + response_deserializer=control_service.ListControlsResponse.deserialize, + ) + return self._stubs['list_controls'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ControlServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..c4edc3e1 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py @@ -0,0 +1,379 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ControlServiceGrpcTransport + + +class ControlServiceGrpcAsyncIOTransport(ControlServiceTransport): + """gRPC AsyncIO backend transport for ControlService. + + Service for modifying Control. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_control(self) -> Callable[ + [control_service.CreateControlRequest], + Awaitable[gcr_control.Control]]: + r"""Return a callable for the create control method over gRPC. + + Creates a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['create_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/CreateControl', + request_serializer=control_service.CreateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['create_control'] + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete control method over gRPC. + + Deletes a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteControlRequest], + 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_control' not in self._stubs: + self._stubs['delete_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/DeleteControl', + request_serializer=control_service.DeleteControlRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_control'] + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + Awaitable[gcr_control.Control]]: + r"""Return a callable for the update control method over gRPC. + + Updates a Control. + + [Control][google.cloud.retail.v2alpha.Control] cannot be set to + a different oneof field, if so an INVALID_ARGUMENT is returned. + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['update_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/UpdateControl', + request_serializer=control_service.UpdateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['update_control'] + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + Awaitable[control.Control]]: + r"""Return a callable for the get control method over gRPC. + + Gets a Control. + + Returns: + Callable[[~.GetControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['get_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/GetControl', + request_serializer=control_service.GetControlRequest.serialize, + response_deserializer=control.Control.deserialize, + ) + return self._stubs['get_control'] + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + Awaitable[control_service.ListControlsResponse]]: + r"""Return a callable for the list controls method over gRPC. + + Lists all Controls linked to this catalog. + + Returns: + Callable[[~.ListControlsRequest], + Awaitable[~.ListControlsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_controls' not in self._stubs: + self._stubs['list_controls'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/ListControls', + request_serializer=control_service.ListControlsRequest.serialize, + response_deserializer=control_service.ListControlsResponse.deserialize, + ) + return self._stubs['list_controls'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ControlServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py new file mode 100644 index 00000000..7c079c80 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import PredictionServiceClient +from .async_client import PredictionServiceAsyncClient + +__all__ = ( + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py new file mode 100644 index 00000000..b9255f77 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport +from .client import PredictionServiceClient + + +class PredictionServiceAsyncClient: + """Service for making recommendation prediction.""" + + _client: PredictionServiceClient + + DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT + + product_path = staticmethod(PredictionServiceClient.product_path) + parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) + common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(PredictionServiceClient.common_project_path) + parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) + common_location_path = staticmethod(PredictionServiceClient.common_location_path) + parse_common_location_path = staticmethod(PredictionServiceClient.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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PredictionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_predict(): + # Create a client + client = retail_v2alpha.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + request = prediction_service.PredictRequest(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.predict, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py new file mode 100644 index 00000000..331c14ce --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py @@ -0,0 +1,479 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionServiceGrpcTransport +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +class PredictionServiceClientMeta(type): + """Metaclass for the PredictionService 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[PredictionServiceTransport]] + _transport_registry["grpc"] = PredictionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PredictionServiceTransport]: + """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): + """Service for making recommendation prediction.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PredictionServiceClient: 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: + PredictionServiceClient: 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) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PredictionServiceTransport): + # transport is a PredictionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_predict(): + # Create a client + client = retail_v2alpha.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a prediction_service.PredictRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_service.PredictRequest): + request = prediction_service.PredictRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.predict] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py new file mode 100644 index 00000000..bb65c664 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PredictionServiceTransport +from .grpc import PredictionServiceGrpcTransport +from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] +_transport_registry['grpc'] = PredictionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport + +__all__ = ( + 'PredictionServiceTransport', + 'PredictionServiceGrpcTransport', + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py new file mode 100644 index 00000000..d46ddac0 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PredictionServiceTransport(abc.ABC): + """Abstract transport class for PredictionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.predict: gapic_v1.method.wrap_method( + self.predict, + 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + Union[ + prediction_service.PredictResponse, + Awaitable[prediction_service.PredictResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'PredictionServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py new file mode 100644 index 00000000..a527b5d9 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO + + +class PredictionServiceGrpcTransport(PredictionServiceTransport): + """gRPC backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + prediction_service.PredictResponse]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + ~.PredictResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'PredictionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..34b77b90 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import PredictionServiceGrpcTransport + + +class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): + """gRPC AsyncIO backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + Awaitable[prediction_service.PredictResponse]]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + Awaitable[~.PredictResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py new file mode 100644 index 00000000..0fa6330a --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ProductServiceClient +from .async_client import ProductServiceAsyncClient + +__all__ = ( + 'ProductServiceClient', + 'ProductServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py new file mode 100644 index 00000000..2933dcb8 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py @@ -0,0 +1,1804 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.services.product_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import purge_config +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport +from .client import ProductServiceClient + + +class ProductServiceAsyncClient: + """Service for ingesting [Product][google.cloud.retail.v2alpha.Product] + information of the customer's website. + """ + + _client: ProductServiceClient + + DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(ProductServiceClient.branch_path) + parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) + product_path = staticmethod(ProductServiceClient.product_path) + parse_product_path = staticmethod(ProductServiceClient.parse_product_path) + common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProductServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProductServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProductServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProductServiceClient.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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ProductServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ProductServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_create_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`google.cloud.retail_v2alpha.types.Product`): + Required. The + [Product][google.cloud.retail.v2alpha.Product] to + create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + Required. The ID to use for the + [Product][google.cloud.retail.v2alpha.Product], which + will become the final component of the + [Product.name][google.cloud.retail.v2alpha.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This field must be unique among all + [Product][google.cloud.retail.v2alpha.Product]s with the + same + [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Product][google.cloud.retail.v2alpha.Product] 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.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_list_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2alpha.Product]s under + this branch, regardless of whether or not this branch + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.product_service.pagers.ListProductsAsyncPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (:class:`google.cloud.retail_v2alpha.types.Product`): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2alpha.Product] to + update. The immutable and output only fields are NOT + supported. If not set, all supported fields (the fields + that are neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_delete_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2alpha.Product] to + delete can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product] member + nor a + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] with more + than one + [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2alpha.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def purge_products(self, + request: Union[purge_config.PurgeProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Permanently deletes all selected + [Product][google.cloud.retail.v2alpha.Product]s under a branch. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed offline. Depending on the + number of [Product][google.cloud.retail.v2alpha.Product]s, this + operation could take hours to complete. Before the operation + completes, some [Product][google.cloud.retail.v2alpha.Product]s + may still be returned by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Depending on the number of + [Product][google.cloud.retail.v2alpha.Product]s, this operation + could take hours to complete. To get a sample of + [Product][google.cloud.retail.v2alpha.Product]s that would be + deleted, set + [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] + to false. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_purge_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeProductsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PurgeProductsRequest, dict]): + The request object. Request message for PurgeProducts + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.PurgeProductsResponse` Response of the PurgeProductsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeProductsResponse, + metadata_type=purge_config.PurgeProductsMetadata, + ) + + # Done; return the response. + return response + + async def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2alpha.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2alpha.Product]s to be + successfully updated. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_import_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2alpha.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2alpha.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_set_inventory(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2alpha.Product() + inventory.title = "title_value" + + request = retail_v2alpha.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (:class:`google.cloud.retail_v2alpha.types.Product`): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product] named in + [Product.name][google.cloud.retail.v2alpha.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2alpha.Product] to + update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.SetInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_inventory, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + async def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [AddFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_add_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [AddLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_remove_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py new file mode 100644 index 00000000..fa5e5d85 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py @@ -0,0 +1,2007 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.services.product_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import purge_config +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductServiceGrpcTransport +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +class ProductServiceClientMeta(type): + """Metaclass for the ProductService 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[ProductServiceTransport]] + _transport_registry["grpc"] = ProductServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ProductServiceTransport]: + """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 ProductServiceClient(metaclass=ProductServiceClientMeta): + """Service for ingesting [Product][google.cloud.retail.v2alpha.Product] + information of the customer's website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProductServiceClient: 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: + ProductServiceClient: 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) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ProductServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProductServiceTransport): + # transport is a ProductServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_create_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (google.cloud.retail_v2alpha.types.Product): + Required. The + [Product][google.cloud.retail.v2alpha.Product] to + create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2alpha.Product], which + will become the final component of the + [Product.name][google.cloud.retail.v2alpha.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This field must be unique among all + [Product][google.cloud.retail.v2alpha.Product]s with the + same + [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.CreateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.CreateProductRequest): + request = product_service.CreateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Product][google.cloud.retail.v2alpha.Product] 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.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.GetProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.GetProductRequest): + request = product_service.GetProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_list_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2alpha.Product]s under + this branch, regardless of whether or not this branch + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.product_service.pagers.ListProductsPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.ListProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.ListProductsRequest): + request = product_service.ListProductsRequest(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_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (google.cloud.retail_v2alpha.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2alpha.Product] to + update. The immutable and output only fields are NOT + supported. If not set, all supported fields (the fields + that are neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.UpdateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.UpdateProductRequest): + request = product_service.UpdateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + 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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_delete_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2alpha.Product] to + delete can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product] member + nor a + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] with more + than one + [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2alpha.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.DeleteProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.DeleteProductRequest): + request = product_service.DeleteProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def purge_products(self, + request: Union[purge_config.PurgeProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Permanently deletes all selected + [Product][google.cloud.retail.v2alpha.Product]s under a branch. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed offline. Depending on the + number of [Product][google.cloud.retail.v2alpha.Product]s, this + operation could take hours to complete. Before the operation + completes, some [Product][google.cloud.retail.v2alpha.Product]s + may still be returned by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Depending on the number of + [Product][google.cloud.retail.v2alpha.Product]s, this operation + could take hours to complete. To get a sample of + [Product][google.cloud.retail.v2alpha.Product]s that would be + deleted, set + [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] + to false. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_purge_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeProductsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PurgeProductsRequest, dict]): + The request object. Request message for PurgeProducts + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.PurgeProductsResponse` Response of the PurgeProductsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeProductsRequest): + request = purge_config.PurgeProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeProductsResponse, + metadata_type=purge_config.PurgeProductsMetadata, + ) + + # Done; return the response. + return response + + def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2alpha.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2alpha.Product]s to be + successfully updated. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_import_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2alpha.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportProductsRequest): + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2alpha.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_set_inventory(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2alpha.Product() + inventory.title = "title_value" + + request = retail_v2alpha.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (google.cloud.retail_v2alpha.types.Product): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product] named in + [Product.name][google.cloud.retail.v2alpha.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2alpha.Product] to + update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.SetInventoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.SetInventoryRequest): + request = product_service.SetInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_add_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [AddFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddFulfillmentPlacesRequest): + request = product_service.AddFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): + request = product_service.RemoveFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_add_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [AddLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddLocalInventoriesRequest): + request = product_service.AddLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_remove_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveLocalInventoriesRequest): + request = product_service.RemoveLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py new file mode 100644 index 00000000..5e235009 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product_service + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` + 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[..., product_service.ListProductsResponse], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2alpha.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[product_service.ListProductsResponse]: + 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[product.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` + 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[product_service.ListProductsResponse]], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2alpha.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: + 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[product.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py new file mode 100644 index 00000000..db824dec --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ProductServiceTransport +from .grpc import ProductServiceGrpcTransport +from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] +_transport_registry['grpc'] = ProductServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport + +__all__ = ( + 'ProductServiceTransport', + 'ProductServiceGrpcTransport', + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py new file mode 100644 index 00000000..25f3f28f --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py @@ -0,0 +1,323 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import purge_config +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ProductServiceTransport(abc.ABC): + """Abstract transport class for ProductService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_product: gapic_v1.method.wrap_method( + self.create_product, + default_timeout=None, + client_info=client_info, + ), + self.get_product: gapic_v1.method.wrap_method( + self.get_product, + default_timeout=None, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + default_timeout=None, + client_info=client_info, + ), + self.update_product: gapic_v1.method.wrap_method( + self.update_product, + default_timeout=None, + client_info=client_info, + ), + self.delete_product: gapic_v1.method.wrap_method( + self.delete_product, + default_timeout=None, + client_info=client_info, + ), + self.purge_products: gapic_v1.method.wrap_method( + self.purge_products, + default_timeout=None, + client_info=client_info, + ), + self.import_products: gapic_v1.method.wrap_method( + self.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.set_inventory: gapic_v1.method.wrap_method( + self.set_inventory, + default_timeout=None, + client_info=client_info, + ), + self.add_fulfillment_places: gapic_v1.method.wrap_method( + self.add_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.remove_fulfillment_places: gapic_v1.method.wrap_method( + self.remove_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.add_local_inventories: gapic_v1.method.wrap_method( + self.add_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.remove_local_inventories: gapic_v1.method.wrap_method( + self.remove_local_inventories, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Union[ + product.Product, + Awaitable[product.Product] + ]]: + raise NotImplementedError() + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Union[ + product_service.ListProductsResponse, + Awaitable[product_service.ListProductsResponse] + ]]: + raise NotImplementedError() + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def purge_products(self) -> Callable[ + [purge_config.PurgeProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProductServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py new file mode 100644 index 00000000..2457b578 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py @@ -0,0 +1,724 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import purge_config +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO + + +class ProductServiceGrpcTransport(ProductServiceTransport): + """gRPC backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2alpha.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + gcr_product.Product]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.CreateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + product.Product]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + product_service.ListProductsResponse]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + gcr_product.Product]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + ~.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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def purge_products(self) -> Callable[ + [purge_config.PurgeProductsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge products method over gRPC. + + Permanently deletes all selected + [Product][google.cloud.retail.v2alpha.Product]s under a branch. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed offline. Depending on the + number of [Product][google.cloud.retail.v2alpha.Product]s, this + operation could take hours to complete. Before the operation + completes, some [Product][google.cloud.retail.v2alpha.Product]s + may still be returned by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Depending on the number of + [Product][google.cloud.retail.v2alpha.Product]s, this operation + could take hours to complete. To get a sample of + [Product][google.cloud.retail.v2alpha.Product]s that would be + deleted, set + [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] + to false. + + Returns: + Callable[[~.PurgeProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_products' not in self._stubs: + self._stubs['purge_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/PurgeProducts', + request_serializer=purge_config.PurgeProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_products'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2alpha.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2alpha.Product]s to be + successfully updated. + + Returns: + Callable[[~.ImportProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + operations_pb2.Operation]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2alpha.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProductServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..4b04ce78 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py @@ -0,0 +1,723 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import purge_config +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductServiceGrpcTransport + + +class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): + """gRPC AsyncIO backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2alpha.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.CreateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Awaitable[product.Product]]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Awaitable[product_service.ListProductsResponse]]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + 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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def purge_products(self) -> Callable[ + [purge_config.PurgeProductsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge products method over gRPC. + + Permanently deletes all selected + [Product][google.cloud.retail.v2alpha.Product]s under a branch. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed offline. Depending on the + number of [Product][google.cloud.retail.v2alpha.Product]s, this + operation could take hours to complete. Before the operation + completes, some [Product][google.cloud.retail.v2alpha.Product]s + may still be returned by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Depending on the number of + [Product][google.cloud.retail.v2alpha.Product]s, this operation + could take hours to complete. To get a sample of + [Product][google.cloud.retail.v2alpha.Product]s that would be + deleted, set + [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] + to false. + + Returns: + Callable[[~.PurgeProductsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_products' not in self._stubs: + self._stubs['purge_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/PurgeProducts', + request_serializer=purge_config.PurgeProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_products'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2alpha.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2alpha.Product]s to be + successfully updated. + + Returns: + Callable[[~.ImportProductsRequest], + 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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2alpha.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + 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 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + 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 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + 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 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + 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 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py new file mode 100644 index 00000000..2f63fc22 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SearchServiceClient +from .async_client import SearchServiceAsyncClient + +__all__ = ( + 'SearchServiceClient', + 'SearchServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py new file mode 100644 index 00000000..d39b3203 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.search_service import pagers +from google.cloud.retail_v2alpha.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .client import SearchServiceClient + + +class SearchServiceAsyncClient: + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: SearchServiceClient + + DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(SearchServiceClient.branch_path) + parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + product_path = staticmethod(SearchServiceClient.product_path) + parse_product_path = staticmethod(SearchServiceClient.parse_product_path) + common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(SearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SearchServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAsyncPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_search(): + # Create a client + client = retail_v2alpha.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.search_service.pagers.SearchAsyncPager: + Response message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py new file mode 100644 index 00000000..c732b39b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.search_service import pagers +from google.cloud.retail_v2alpha.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SearchServiceGrpcTransport +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +class SearchServiceClientMeta(type): + """Metaclass for the SearchService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] + _transport_registry["grpc"] = SearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SearchServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SearchServiceClient(metaclass=SearchServiceClientMeta): + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SearchServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SearchServiceTransport): + # transport is a SearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_search(): + # Create a client + client = retail_v2alpha.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.search_service.pagers.SearchPager: + Response message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a search_service.SearchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py new file mode 100644 index 00000000..7487beee --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import search_service + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2alpha.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2alpha.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py new file mode 100644 index 00000000..7917cd1d --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SearchServiceTransport +from .grpc import SearchServiceGrpcTransport +from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] +_transport_registry['grpc'] = SearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport + +__all__ = ( + 'SearchServiceTransport', + 'SearchServiceGrpcTransport', + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py new file mode 100644 index 00000000..8713b735 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import search_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SearchServiceTransport(abc.ABC): + """Abstract transport class for SearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search: gapic_v1.method.wrap_method( + self.search, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Union[ + search_service.SearchResponse, + Awaitable[search_service.SearchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SearchServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py new file mode 100644 index 00000000..1bdd51d4 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py @@ -0,0 +1,268 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO + + +class SearchServiceGrpcTransport(SearchServiceTransport): + """gRPC backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..12a83cc7 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py @@ -0,0 +1,267 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SearchServiceGrpcTransport + + +class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): + """gRPC AsyncIO backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Awaitable[search_service.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py new file mode 100644 index 00000000..d1a0a023 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ServingConfigServiceClient +from .async_client import ServingConfigServiceAsyncClient + +__all__ = ( + 'ServingConfigServiceClient', + 'ServingConfigServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py new file mode 100644 index 00000000..4f047853 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py @@ -0,0 +1,954 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.serving_config_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport +from .client import ServingConfigServiceClient + + +class ServingConfigServiceAsyncClient: + """Service for modifying ServingConfig.""" + + _client: ServingConfigServiceClient + + DEFAULT_ENDPOINT = ServingConfigServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ServingConfigServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(ServingConfigServiceClient.catalog_path) + parse_catalog_path = staticmethod(ServingConfigServiceClient.parse_catalog_path) + serving_config_path = staticmethod(ServingConfigServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(ServingConfigServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(ServingConfigServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ServingConfigServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ServingConfigServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ServingConfigServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ServingConfigServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ServingConfigServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ServingConfigServiceClient.common_project_path) + parse_common_project_path = staticmethod(ServingConfigServiceClient.parse_common_project_path) + common_location_path = staticmethod(ServingConfigServiceClient.common_location_path) + parse_common_location_path = staticmethod(ServingConfigServiceClient.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: + ServingConfigServiceAsyncClient: The constructed client. + """ + return ServingConfigServiceClient.from_service_account_info.__func__(ServingConfigServiceAsyncClient, 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: + ServingConfigServiceAsyncClient: The constructed client. + """ + return ServingConfigServiceClient.from_service_account_file.__func__(ServingConfigServiceAsyncClient, 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 variabel 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 ServingConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ServingConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ServingConfigServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ServingConfigServiceClient).get_transport_class, type(ServingConfigServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ServingConfigServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the serving config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ServingConfigServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ServingConfigServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_serving_config(self, + request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, + *, + parent: str = None, + serving_config: gcr_serving_config.ServingConfig = None, + serving_config_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_create_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = await client.create_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateServingConfigRequest, dict]): + The request object. Request for CreateServingConfig + method. + parent (:class:`str`): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config (:class:`google.cloud.retail_v2alpha.types.ServingConfig`): + Required. The ServingConfig to + create. + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config_id (:class:`str`): + Required. The ID to use for the ServingConfig, which + will become the final component of the ServingConfig's + resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``serving_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, serving_config, serving_config_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.CreateServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if serving_config is not None: + request.serving_config = serving_config + if serving_config_id is not None: + request.serving_config_id = serving_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_serving_config(self, + request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_delete_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_serving_config(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteServingConfigRequest, dict]): + The request object. Request for DeleteServingConfig + method. + name (:class:`str`): + Required. The resource name of the ServingConfig to + delete. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.DeleteServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_serving_config(self, + request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, + *, + serving_config: gcr_serving_config.ServingConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Updates a ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = await client.update_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateServingConfigRequest, dict]): + The request object. Request for UpdateServingConfig + method. + serving_config (:class:`google.cloud.retail_v2alpha.types.ServingConfig`): + Required. The ServingConfig to + update. + + This corresponds to the ``serving_config`` 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 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.UpdateServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config.name", request.serving_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_serving_config(self, + request: Union[serving_config_service.GetServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> serving_config.ServingConfig: + r"""Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetServingConfigRequest, dict]): + The request object. Request for GetServingConfig method. + name (:class:`str`): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.GetServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_serving_configs(self, + request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServingConfigsAsyncPager: + r"""Lists all ServingConfigs linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_list_serving_configs(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListServingConfigsRequest, dict]): + The request object. Request for ListServingConfigs + method. + parent (:class:`str`): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsAsyncPager: + Response for ListServingConfigs + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.ListServingConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_serving_configs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServingConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_control(self, + request: Union[serving_config_service.AddControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_add_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.add_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddControlRequest, dict]): + The request object. Request for AddControl method. + serving_config (:class:`str`): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.AddControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_control(self, + request: Union[serving_config_service.RemoveControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_remove_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.remove_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveControlRequest, dict]): + The request object. Request for RemoveControl method. + serving_config (:class:`str`): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.RemoveControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServingConfigServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py new file mode 100644 index 00000000..26637bf0 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py @@ -0,0 +1,1162 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.serving_config_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ServingConfigServiceGrpcTransport +from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport + + +class ServingConfigServiceClientMeta(type): + """Metaclass for the ServingConfigService 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[ServingConfigServiceTransport]] + _transport_registry["grpc"] = ServingConfigServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ServingConfigServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ServingConfigServiceTransport]: + """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 ServingConfigServiceClient(metaclass=ServingConfigServiceClientMeta): + """Service for modifying ServingConfig.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServingConfigServiceClient: 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: + ServingConfigServiceClient: 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) -> ServingConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ServingConfigServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,catalog: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ServingConfigServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the serving config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ServingConfigServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ServingConfigServiceTransport): + # transport is a ServingConfigServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_serving_config(self, + request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, + *, + parent: str = None, + serving_config: gcr_serving_config.ServingConfig = None, + serving_config_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_create_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = client.create_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateServingConfigRequest, dict]): + The request object. Request for CreateServingConfig + method. + parent (str): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config (google.cloud.retail_v2alpha.types.ServingConfig): + Required. The ServingConfig to + create. + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config_id (str): + Required. The ID to use for the ServingConfig, which + will become the final component of the ServingConfig's + resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``serving_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, serving_config, serving_config_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.CreateServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.CreateServingConfigRequest): + request = serving_config_service.CreateServingConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if serving_config is not None: + request.serving_config = serving_config + if serving_config_id is not None: + request.serving_config_id = serving_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_serving_config(self, + request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_delete_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_serving_config(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteServingConfigRequest, dict]): + The request object. Request for DeleteServingConfig + method. + name (str): + Required. The resource name of the ServingConfig to + delete. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.DeleteServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.DeleteServingConfigRequest): + request = serving_config_service.DeleteServingConfigRequest(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_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_serving_config(self, + request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, + *, + serving_config: gcr_serving_config.ServingConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Updates a ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = client.update_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateServingConfigRequest, dict]): + The request object. Request for UpdateServingConfig + method. + serving_config (google.cloud.retail_v2alpha.types.ServingConfig): + Required. The ServingConfig to + update. + + This corresponds to the ``serving_config`` 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 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.UpdateServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.UpdateServingConfigRequest): + request = serving_config_service.UpdateServingConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config.name", request.serving_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_serving_config(self, + request: Union[serving_config_service.GetServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> serving_config.ServingConfig: + r"""Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetServingConfigRequest, dict]): + The request object. Request for GetServingConfig method. + name (str): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.GetServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.GetServingConfigRequest): + request = serving_config_service.GetServingConfigRequest(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_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_serving_configs(self, + request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServingConfigsPager: + r"""Lists all ServingConfigs linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_list_serving_configs(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListServingConfigsRequest, dict]): + The request object. Request for ListServingConfigs + method. + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsPager: + Response for ListServingConfigs + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.ListServingConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.ListServingConfigsRequest): + request = serving_config_service.ListServingConfigsRequest(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_serving_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListServingConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_control(self, + request: Union[serving_config_service.AddControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_add_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.add_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddControlRequest, dict]): + The request object. Request for AddControl method. + serving_config (str): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.AddControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.AddControlRequest): + request = serving_config_service.AddControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_control(self, + request: Union[serving_config_service.RemoveControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_remove_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.remove_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveControlRequest, dict]): + The request object. Request for RemoveControl method. + serving_config (str): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.RemoveControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.RemoveControlRequest): + request = serving_config_service.RemoveControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServingConfigServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py new file mode 100644 index 00000000..8c4975b7 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config_service + + +class ListServingConfigsPager: + """A pager for iterating through ``list_serving_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``serving_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServingConfigs`` requests and continue to iterate + through the ``serving_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` + 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[..., serving_config_service.ListServingConfigsResponse], + request: serving_config_service.ListServingConfigsRequest, + response: serving_config_service.ListServingConfigsResponse, + *, + 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.retail_v2alpha.types.ListServingConfigsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListServingConfigsResponse): + 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 = serving_config_service.ListServingConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[serving_config_service.ListServingConfigsResponse]: + 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[serving_config.ServingConfig]: + for page in self.pages: + yield from page.serving_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServingConfigsAsyncPager: + """A pager for iterating through ``list_serving_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``serving_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServingConfigs`` requests and continue to iterate + through the ``serving_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` + 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[serving_config_service.ListServingConfigsResponse]], + request: serving_config_service.ListServingConfigsRequest, + response: serving_config_service.ListServingConfigsResponse, + *, + 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.retail_v2alpha.types.ListServingConfigsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListServingConfigsResponse): + 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 = serving_config_service.ListServingConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[serving_config_service.ListServingConfigsResponse]: + 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[serving_config.ServingConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.serving_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py new file mode 100644 index 00000000..3726ac83 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ServingConfigServiceTransport +from .grpc import ServingConfigServiceGrpcTransport +from .grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ServingConfigServiceTransport]] +_transport_registry['grpc'] = ServingConfigServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ServingConfigServiceGrpcAsyncIOTransport + +__all__ = ( + 'ServingConfigServiceTransport', + 'ServingConfigServiceGrpcTransport', + 'ServingConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py new file mode 100644 index 00000000..23a39b6d --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py @@ -0,0 +1,237 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ServingConfigServiceTransport(abc.ABC): + """Abstract transport class for ServingConfigService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_serving_config: gapic_v1.method.wrap_method( + self.create_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_serving_config: gapic_v1.method.wrap_method( + self.delete_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.update_serving_config: gapic_v1.method.wrap_method( + self.update_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.get_serving_config: gapic_v1.method.wrap_method( + self.get_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.list_serving_configs: gapic_v1.method.wrap_method( + self.list_serving_configs, + default_timeout=None, + client_info=client_info, + ), + self.add_control: gapic_v1.method.wrap_method( + self.add_control, + default_timeout=None, + client_info=client_info, + ), + self.remove_control: gapic_v1.method.wrap_method( + self.remove_control, + 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 create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + Union[ + serving_config.ServingConfig, + Awaitable[serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + Union[ + serving_config_service.ListServingConfigsResponse, + Awaitable[serving_config_service.ListServingConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ServingConfigServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py new file mode 100644 index 00000000..5ba2c69c --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py @@ -0,0 +1,438 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO + + +class ServingConfigServiceGrpcTransport(ServingConfigServiceTransport): + """gRPC backend transport for ServingConfigService. + + Service for modifying ServingConfig. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the create serving config method over gRPC. + + Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + Returns: + Callable[[~.CreateServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/CreateServingConfig', + request_serializer=serving_config_service.CreateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['create_serving_config'] + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete serving config method over gRPC. + + Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.DeleteServingConfigRequest], + ~.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_serving_config' not in self._stubs: + self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/DeleteServingConfig', + request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_serving_config'] + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the update serving config method over gRPC. + + Updates a ServingConfig. + + Returns: + Callable[[~.UpdateServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/UpdateServingConfig', + request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['update_serving_config'] + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + serving_config.ServingConfig]: + r"""Return a callable for the get serving config method over gRPC. + + Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.GetServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/GetServingConfig', + request_serializer=serving_config_service.GetServingConfigRequest.serialize, + response_deserializer=serving_config.ServingConfig.deserialize, + ) + return self._stubs['get_serving_config'] + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + serving_config_service.ListServingConfigsResponse]: + r"""Return a callable for the list serving configs method over gRPC. + + Lists all ServingConfigs linked to this catalog. + + Returns: + Callable[[~.ListServingConfigsRequest], + ~.ListServingConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: + self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/ListServingConfigs', + request_serializer=serving_config_service.ListServingConfigsRequest.serialize, + response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, + ) + return self._stubs['list_serving_configs'] + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the add control method over gRPC. + + Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + Returns: + Callable[[~.AddControlRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_control' not in self._stubs: + self._stubs['add_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/AddControl', + request_serializer=serving_config_service.AddControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['add_control'] + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the remove control method over gRPC. + + Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + Returns: + Callable[[~.RemoveControlRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_control' not in self._stubs: + self._stubs['remove_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/RemoveControl', + request_serializer=serving_config_service.RemoveControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['remove_control'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ServingConfigServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..b2524461 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py @@ -0,0 +1,437 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ServingConfigServiceGrpcTransport + + +class ServingConfigServiceGrpcAsyncIOTransport(ServingConfigServiceTransport): + """gRPC AsyncIO backend transport for ServingConfigService. + + Service for modifying ServingConfig. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the create serving config method over gRPC. + + Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + Returns: + Callable[[~.CreateServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/CreateServingConfig', + request_serializer=serving_config_service.CreateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['create_serving_config'] + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete serving config method over gRPC. + + Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.DeleteServingConfigRequest], + 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_serving_config' not in self._stubs: + self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/DeleteServingConfig', + request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_serving_config'] + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the update serving config method over gRPC. + + Updates a ServingConfig. + + Returns: + Callable[[~.UpdateServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/UpdateServingConfig', + request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['update_serving_config'] + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + Awaitable[serving_config.ServingConfig]]: + r"""Return a callable for the get serving config method over gRPC. + + Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.GetServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/GetServingConfig', + request_serializer=serving_config_service.GetServingConfigRequest.serialize, + response_deserializer=serving_config.ServingConfig.deserialize, + ) + return self._stubs['get_serving_config'] + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + Awaitable[serving_config_service.ListServingConfigsResponse]]: + r"""Return a callable for the list serving configs method over gRPC. + + Lists all ServingConfigs linked to this catalog. + + Returns: + Callable[[~.ListServingConfigsRequest], + Awaitable[~.ListServingConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: + self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/ListServingConfigs', + request_serializer=serving_config_service.ListServingConfigsRequest.serialize, + response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, + ) + return self._stubs['list_serving_configs'] + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the add control method over gRPC. + + Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + Returns: + Callable[[~.AddControlRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_control' not in self._stubs: + self._stubs['add_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/AddControl', + request_serializer=serving_config_service.AddControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['add_control'] + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the remove control method over gRPC. + + Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + Returns: + Callable[[~.RemoveControlRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_control' not in self._stubs: + self._stubs['remove_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/RemoveControl', + request_serializer=serving_config_service.RemoveControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['remove_control'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ServingConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py new file mode 100644 index 00000000..5f5171c1 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py new file mode 100644 index 00000000..1f08ee18 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py @@ -0,0 +1,730 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on the customer + website. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(UserEventServiceClient.catalog_path) + parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) + product_path = staticmethod(UserEventServiceClient.product_path) + parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_write_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_collect_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_purge_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_import_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2alpha.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_rejoin_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py new file mode 100644 index 00000000..f1dbd152 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py @@ -0,0 +1,929 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[UserEventServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on the customer + website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_write_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_collect_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_purge_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeUserEventsRequest): + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_import_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2alpha.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_rejoin_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.RejoinUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.RejoinUserEventsRequest): + request = user_event_service.RejoinUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py new file mode 100644 index 00000000..f53ee5d7 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py new file mode 100644 index 00000000..7a6f8e53 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.rejoin_user_events: gapic_v1.method.wrap_method( + self.rejoin_user_events, + 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 write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + user_event.UserEvent, + Awaitable[user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py new file mode 100644 index 00000000..d51a4e1a --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py @@ -0,0 +1,415 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..0a70cf03 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,414 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + 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 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py new file mode 100644 index 00000000..aa87618d --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py @@ -0,0 +1,284 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .catalog import ( + AttributesConfig, + Catalog, + CatalogAttribute, + CompletionConfig, + MerchantCenterLink, + MerchantCenterLinkingConfig, + ProductLevelConfig, +) +from .catalog_service import ( + AddCatalogAttributeRequest, + GetAttributesConfigRequest, + GetCompletionConfigRequest, + GetDefaultBranchRequest, + GetDefaultBranchResponse, + ListCatalogsRequest, + ListCatalogsResponse, + RemoveCatalogAttributeRequest, + ReplaceCatalogAttributeRequest, + SetDefaultBranchRequest, + UpdateAttributesConfigRequest, + UpdateCatalogRequest, + UpdateCompletionConfigRequest, +) +from .common import ( + Audience, + ColorInfo, + Condition, + CustomAttribute, + FulfillmentInfo, + Image, + Interval, + LocalInventory, + PriceInfo, + Rating, + Rule, + UserInfo, + AttributeConfigLevel, + SearchSolutionUseCase, + SolutionType, +) +from .completion_service import ( + CompleteQueryRequest, + CompleteQueryResponse, +) +from .control import ( + Control, +) +from .control_service import ( + CreateControlRequest, + DeleteControlRequest, + GetControlRequest, + ListControlsRequest, + ListControlsResponse, + UpdateControlRequest, +) +from .export_config import ( + ExportErrorsConfig, + ExportMetadata, + ExportProductsResponse, + ExportUserEventsResponse, +) +from .import_config import ( + BigQuerySource, + CompletionDataInputConfig, + GcsSource, + ImportCompletionDataRequest, + ImportCompletionDataResponse, + ImportErrorsConfig, + ImportMetadata, + ImportProductsRequest, + ImportProductsResponse, + ImportUserEventsRequest, + ImportUserEventsResponse, + ProductInlineSource, + ProductInputConfig, + UserEventImportSummary, + UserEventInlineSource, + UserEventInputConfig, +) +from .prediction_service import ( + PredictRequest, + PredictResponse, +) +from .product import ( + Product, +) +from .product_service import ( + AddFulfillmentPlacesMetadata, + AddFulfillmentPlacesRequest, + AddFulfillmentPlacesResponse, + AddLocalInventoriesMetadata, + AddLocalInventoriesRequest, + AddLocalInventoriesResponse, + CreateProductRequest, + DeleteProductRequest, + GetProductRequest, + ListProductsRequest, + ListProductsResponse, + RemoveFulfillmentPlacesMetadata, + RemoveFulfillmentPlacesRequest, + RemoveFulfillmentPlacesResponse, + RemoveLocalInventoriesMetadata, + RemoveLocalInventoriesRequest, + RemoveLocalInventoriesResponse, + SetInventoryMetadata, + SetInventoryRequest, + SetInventoryResponse, + UpdateProductRequest, +) +from .promotion import ( + Promotion, +) +from .purge_config import ( + PurgeMetadata, + PurgeProductsMetadata, + PurgeProductsRequest, + PurgeProductsResponse, + PurgeUserEventsRequest, + PurgeUserEventsResponse, +) +from .search_service import ( + SearchRequest, + SearchResponse, +) +from .serving_config import ( + ServingConfig, +) +from .serving_config_service import ( + AddControlRequest, + CreateServingConfigRequest, + DeleteServingConfigRequest, + GetServingConfigRequest, + ListServingConfigsRequest, + ListServingConfigsResponse, + RemoveControlRequest, + UpdateServingConfigRequest, +) +from .user_event import ( + CompletionDetail, + ProductDetail, + PurchaseTransaction, + UserEvent, +) +from .user_event_service import ( + CollectUserEventRequest, + RejoinUserEventsMetadata, + RejoinUserEventsRequest, + RejoinUserEventsResponse, + WriteUserEventRequest, +) + +__all__ = ( + 'AttributesConfig', + 'Catalog', + 'CatalogAttribute', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'ProductLevelConfig', + 'AddCatalogAttributeRequest', + 'GetAttributesConfigRequest', + 'GetCompletionConfigRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + 'SetDefaultBranchRequest', + 'UpdateAttributesConfigRequest', + 'UpdateCatalogRequest', + 'UpdateCompletionConfigRequest', + 'Audience', + 'ColorInfo', + 'Condition', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'Rule', + 'UserInfo', + 'AttributeConfigLevel', + 'SearchSolutionUseCase', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Control', + 'CreateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + 'UpdateControlRequest', + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeProductsMetadata', + 'PurgeProductsRequest', + 'PurgeProductsResponse', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'ServingConfig', + 'AddControlRequest', + 'CreateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'RemoveControlRequest', + 'UpdateServingConfigRequest', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py new file mode 100644 index 00000000..1e4a7ab5 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py @@ -0,0 +1,528 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'ProductLevelConfig', + 'CatalogAttribute', + 'AttributesConfig', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'Catalog', + }, +) + + +class ProductLevelConfig(proto.Message): + r"""Configures what level the product should be uploaded with + regards to how users will be send events and how predictions + will be made. + + Attributes: + ingestion_product_type (str): + The type of [Product][google.cloud.retail.v2alpha.Product]s + allowed to be ingested into the catalog. Acceptable values + are: + + - ``primary`` (default): You can ingest + [Product][google.cloud.retail.v2alpha.Product]s of all + types. When ingesting a + [Product][google.cloud.retail.v2alpha.Product], its type + will default to + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + if unset. + - ``variant``: You can only ingest + [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s. This + means + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] + cannot be empty. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``variant`` and + [merchant_center_product_id_field][google.cloud.retail.v2alpha.ProductLevelConfig.merchant_center_product_id_field] + is ``itemGroupId``, an INVALID_ARGUMENT error is returned. + + See `Using product + levels `__ + for more details. + merchant_center_product_id_field (str): + Which field of `Merchant Center + Product `__ + should be imported as + [Product.id][google.cloud.retail.v2alpha.Product.id]. + Acceptable values are: + + - ``offerId`` (default): Import ``offerId`` as the product + ID. + - ``itemGroupId``: Import ``itemGroupId`` as the product + ID. Notice that Retail API will choose one item from the + ones with the same ``itemGroupId``, and use it to + represent the item group. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``itemGroupId`` and + [ingestion_product_type][google.cloud.retail.v2alpha.ProductLevelConfig.ingestion_product_type] + is ``variant``, an INVALID_ARGUMENT error is returned. + + See `Using product + levels `__ + for more details. + """ + + ingestion_product_type = proto.Field( + proto.STRING, + number=1, + ) + merchant_center_product_id_field = proto.Field( + proto.STRING, + number=2, + ) + + +class CatalogAttribute(proto.Message): + r"""Catalog level attribute config for an attribute. For example, + if customers want to enable/disable facet for a specific + attribute. + + Attributes: + key (str): + Required. Attribute name. For example: ``color``, + ``brands``, ``attributes.custom_attribute``, such as + ``attributes.xyz``. + in_use (bool): + Output only. Indicates whether this attribute has been used + by any products. ``True`` if at least one + [Product][google.cloud.retail.v2alpha.Product] is using this + attribute in + [Product.attributes][google.cloud.retail.v2alpha.Product.attributes]. + Otherwise, this field is ``False``. + + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + can be pre-loaded by using [AddCatalogAttribute][], + [ImportCatalogAttributes][], or [UpdateAttributesConfig][] + APIs. This field is ``False`` for pre-loaded + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s. + + Only + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s + that are not in use by products can be deleted. + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s + that are in use by products cannot be deleted; however, + their configuration properties will reset to default values + upon removal request. + + After catalog changes, it takes about 10 minutes for this + field to update. + type_ (google.cloud.retail_v2alpha.types.CatalogAttribute.AttributeType): + Output only. The type of this attribute. This is derived + from the attribute in + [Product.attributes][google.cloud.retail.v2alpha.Product.attributes]. + indexable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.IndexableOption): + When + [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] + is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if INDEXABLE_ENABLED + attribute values are indexed so that it can be filtered, + faceted, or boosted in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + dynamic_facetable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.DynamicFacetableOption): + If DYNAMIC_FACETABLE_ENABLED, attribute values are available + for dynamic facet. Could only be DYNAMIC_FACETABLE_DISABLED + if + [CatalogAttribute.indexable_option][google.cloud.retail.v2alpha.CatalogAttribute.indexable_option] + is INDEXABLE_DISABLED. Otherwise, an INVALID_ARGUMENT error + is returned. + searchable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.SearchableOption): + When + [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] + is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if SEARCHABLE_ENABLED, + attribute values are searchable by text queries in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + If SEARCHABLE_ENABLED but attribute type is numerical, + attribute values will not be searchable by text queries in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + as there are no text values associated to numerical + attributes. + """ + class AttributeType(proto.Enum): + r"""The type of an attribute.""" + UNKNOWN = 0 + TEXTUAL = 1 + NUMERICAL = 2 + + class IndexableOption(proto.Enum): + r"""The status of the indexable option of a catalog attribute.""" + INDEXABLE_OPTION_UNSPECIFIED = 0 + INDEXABLE_ENABLED = 1 + INDEXABLE_DISABLED = 2 + + class DynamicFacetableOption(proto.Enum): + r"""The status of the dynamic facetable option of a catalog + attribute. + """ + DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 + DYNAMIC_FACETABLE_ENABLED = 1 + DYNAMIC_FACETABLE_DISABLED = 2 + + class SearchableOption(proto.Enum): + r"""The status of the searchable option of a catalog attribute.""" + SEARCHABLE_OPTION_UNSPECIFIED = 0 + SEARCHABLE_ENABLED = 1 + SEARCHABLE_DISABLED = 2 + + key = proto.Field( + proto.STRING, + number=1, + ) + in_use = proto.Field( + proto.BOOL, + number=9, + ) + type_ = proto.Field( + proto.ENUM, + number=10, + enum=AttributeType, + ) + indexable_option = proto.Field( + proto.ENUM, + number=5, + enum=IndexableOption, + ) + dynamic_facetable_option = proto.Field( + proto.ENUM, + number=6, + enum=DynamicFacetableOption, + ) + searchable_option = proto.Field( + proto.ENUM, + number=7, + enum=SearchableOption, + ) + + +class AttributesConfig(proto.Message): + r"""Catalog level attribute config. + + Attributes: + name (str): + Required. Immutable. The fully qualified resource name of + the attribute config. Format: + ``projects/*/locations/*/catalogs/*/attributesConfig`` + catalog_attributes (Mapping[str, google.cloud.retail_v2alpha.types.CatalogAttribute]): + Enable attribute(s) config at catalog level. For example, + indexable, dynamic_facetable, or searchable for each + attribute. + + The key is catalog attribute's name. For example: ``color``, + ``brands``, ``attributes.custom_attribute``, such as + ``attributes.xyz``. + + The maximum number of catalog attributes allowed in a + request is 1000. + attribute_config_level (google.cloud.retail_v2alpha.types.AttributeConfigLevel): + Output only. The + [AttributeConfigLevel][google.cloud.retail.v2alpha.AttributeConfigLevel] + used for this catalog. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + catalog_attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='CatalogAttribute', + ) + attribute_config_level = proto.Field( + proto.ENUM, + number=3, + enum=common.AttributeConfigLevel, + ) + + +class CompletionConfig(proto.Message): + r"""Catalog level autocomplete config for customers to customize + autocomplete feature's settings. + + Attributes: + name (str): + Required. Immutable. Fully qualified name + ``projects/*/locations/*/catalogs/*/completionConfig`` + matching_order (str): + Specifies the matching order for autocomplete suggestions, + e.g., a query consisting of 'sh' with 'out-of-order' + specified would suggest "women's shoes", whereas a query of + 'red s' with 'exact-prefix' specified would suggest "red + shoes". Currently supported values: + + - 'out-of-order' + - 'exact-prefix' + + Default value: 'exact-prefix'. + max_suggestions (int): + The maximum number of autocomplete + suggestions returned per term. The maximum + allowed max suggestions is 20. Default value is + 20. If left unset or set to 0, then will + fallback to default value. + min_prefix_length (int): + The minimum number of characters needed to be + typed in order to get suggestions. Default value + is 2. If left unset or set to 0, then will + fallback to default value. + auto_learning (bool): + If set to true, the auto learning function is enabled. Auto + learning uses user data to generate suggestions using ML + techniques. Default value is false. Only after enabling auto + learning can users use ``cloud-retail`` data in + [CompleteQueryRequest][google.cloud.retail.v2alpha.CompleteQueryRequest]. + suggestions_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the + autocomplete phrases uploaded by the customer. + last_suggestions_import_operation (str): + Output only. Name of the LRO corresponding to the latest + suggestion terms list import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + denylist_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the / + autocomplete denylist phrases uploaded by the + customer. + last_denylist_import_operation (str): + Output only. LRO corresponding to the latest denylist + import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + allowlist_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the + autocomplete allowlist phrases uploaded by the + customer. + last_allowlist_import_operation (str): + Output only. LRO corresponding to the latest allowlist + import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + matching_order = proto.Field( + proto.STRING, + number=2, + ) + max_suggestions = proto.Field( + proto.INT32, + number=3, + ) + min_prefix_length = proto.Field( + proto.INT32, + number=4, + ) + auto_learning = proto.Field( + proto.BOOL, + number=11, + ) + suggestions_input_config = proto.Field( + proto.MESSAGE, + number=5, + message=import_config.CompletionDataInputConfig, + ) + last_suggestions_import_operation = proto.Field( + proto.STRING, + number=6, + ) + denylist_input_config = proto.Field( + proto.MESSAGE, + number=7, + message=import_config.CompletionDataInputConfig, + ) + last_denylist_import_operation = proto.Field( + proto.STRING, + number=8, + ) + allowlist_input_config = proto.Field( + proto.MESSAGE, + number=9, + message=import_config.CompletionDataInputConfig, + ) + last_allowlist_import_operation = proto.Field( + proto.STRING, + number=10, + ) + + +class MerchantCenterLink(proto.Message): + r"""Represents a link between a Merchant Center account and a + branch. Once a link is established, products from the linked + merchant center account will be streamed to the linked branch. + + Attributes: + merchant_center_account_id (int): + Required. The linked `Merchant center account + id `__. + The account must be a standalone account or a sub-account of + a MCA. + branch_id (str): + The branch id (e.g. 0/1/2) within this catalog that products + from merchant_center_account_id are streamed to. When + updating this field, an empty value will use the currently + configured default branch. However, changing the default + branch later on won't change the linked branch here. + + A single branch id can only have one linked merchant center + account id. + destinations (Sequence[str]): + String representing the destination to import for, all if + left empty. List of possible values can be found here. + [https://support.google.com/merchants/answer/7501026] List + of allowed string values: "Shopping_ads", + "Buy_on_google_listings", "Display_ads", "Local_inventory + \_ads", "Free_listings", "Free_local_listings" NOTE: The + string values are case sensitive. + region_code (str): + Region code of offers to accept. 2-letter Uppercase ISO + 3166-1 alpha-2 code. List of values can be found + `here `__ + under the ``region`` tag. If left blank no region filtering + will be performed. + + Example value: ``US``. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. ISO + 639-1. + + This specifies the language of offers in Merchant Center + that will be accepted. If empty no language filtering will + be performed. + + Example value: ``en``. + """ + + merchant_center_account_id = proto.Field( + proto.INT64, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + destinations = proto.RepeatedField( + proto.STRING, + number=3, + ) + region_code = proto.Field( + proto.STRING, + number=4, + ) + language_code = proto.Field( + proto.STRING, + number=5, + ) + + +class MerchantCenterLinkingConfig(proto.Message): + r"""Configures Merchant Center linking. + Links contained in the config will be used to sync data from a + Merchant Center account to a Cloud Retail branch. + + Attributes: + links (Sequence[google.cloud.retail_v2alpha.types.MerchantCenterLink]): + Links between Merchant Center accounts and + branches. + """ + + links = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MerchantCenterLink', + ) + + +class Catalog(proto.Message): + r"""The catalog configuration. + + Attributes: + name (str): + Required. Immutable. The fully qualified + resource name of the catalog. + display_name (str): + Required. Immutable. The catalog display name. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + product_level_config (google.cloud.retail_v2alpha.types.ProductLevelConfig): + Required. The product level configuration. + merchant_center_linking_config (google.cloud.retail_v2alpha.types.MerchantCenterLinkingConfig): + The Merchant Center linking configuration. + Once a link is added, the data stream from + Merchant Center to Cloud Retail will be enabled + automatically. The requester must have access to + the merchant center account in order to make + changes to this field. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + product_level_config = proto.Field( + proto.MESSAGE, + number=4, + message='ProductLevelConfig', + ) + merchant_center_linking_config = proto.Field( + proto.MESSAGE, + number=6, + message='MerchantCenterLinkingConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py new file mode 100644 index 00000000..21d9b1c2 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py @@ -0,0 +1,453 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'UpdateCatalogRequest', + 'SetDefaultBranchRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'GetCompletionConfigRequest', + 'UpdateCompletionConfigRequest', + 'GetAttributesConfigRequest', + 'UpdateAttributesConfigRequest', + 'AddCatalogAttributeRequest', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + }, +) + + +class ListCatalogsRequest(proto.Message): + r"""Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + + Attributes: + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2alpha.Catalog]s under this + location, regardless of whether or not this location exists, + a PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [Catalog][google.cloud.retail.v2alpha.Catalog]s to return. + If unspecified, defaults to 50. The maximum allowed value is + 1000. Values above 1000 will be coerced to 1000. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [ListCatalogsResponse.next_page_token][google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token], + received from a previous + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCatalogsResponse(proto.Message): + r"""Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + + Attributes: + catalogs (Sequence[google.cloud.retail_v2alpha.types.Catalog]): + All the customer's + [Catalog][google.cloud.retail.v2alpha.Catalog]s. + next_page_token (str): + A token that can be sent as + [ListCatalogsRequest.page_token][google.cloud.retail.v2alpha.ListCatalogsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + catalogs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateCatalogRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] + method. + + Attributes: + catalog (google.cloud.retail_v2alpha.types.Catalog): + Required. The [Catalog][google.cloud.retail.v2alpha.Catalog] + to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2alpha.Catalog], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2alpha.Catalog] 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 + [Catalog][google.cloud.retail.v2alpha.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + catalog = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class SetDefaultBranchRequest(proto.Message): + r"""Request message to set a specified branch as new default_branch. + + Attributes: + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + branch_id (str): + The final component of the resource name of a branch. + + This field must be one of "0", "1" or "2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If there are no sufficient active products in the targeted + branch and + [force][google.cloud.retail.v2alpha.SetDefaultBranchRequest.force] + is not set, a FAILED_PRECONDITION error is returned. + note (str): + Some note on this request, this can be retrieved by + [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch] + before next valid default branch set occurs. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + force (bool): + If set to true, it permits switching to a branch with + [branch_id][google.cloud.retail.v2alpha.SetDefaultBranchRequest.branch_id] + even if it has no sufficient active products. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + force = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetDefaultBranchRequest(proto.Message): + r"""Request message to show which branch is currently the default + branch. + + Attributes: + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDefaultBranchResponse(proto.Message): + r"""Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. + + Attributes: + branch (str): + Full resource name of the branch id currently + set as default branch. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when this branch is set to default. + note (str): + This corresponds to + [SetDefaultBranchRequest.note][google.cloud.retail.v2alpha.SetDefaultBranchRequest.note] + field, when this branch was set as default. + """ + + branch = proto.Field( + proto.STRING, + number=1, + ) + set_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + + +class GetCompletionConfigRequest(proto.Message): + r"""Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] + method. + + Attributes: + name (str): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateCompletionConfigRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] + method. + + Attributes: + completion_config (google.cloud.retail_v2alpha.types.CompletionConfig): + Required. The + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + 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 + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + """ + + completion_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.CompletionConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetAttributesConfigRequest(proto.Message): + r"""Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] + method. + + Attributes: + name (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAttributesConfigRequest(proto.Message): + r"""Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] + method. + + Attributes: + attributes_config (google.cloud.retail_v2alpha.types.AttributesConfig): + Required. The + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + """ + + attributes_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.AttributesConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class AddCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + catalog_attribute (google.cloud.retail_v2alpha.types.CatalogAttribute): + Required. The + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + catalog_attribute = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_catalog.CatalogAttribute, + ) + + +class RemoveCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + key (str): + Required. The attribute name key of the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + key = proto.Field( + proto.STRING, + number=2, + ) + + +class ReplaceCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + catalog_attribute (google.cloud.retail_v2alpha.types.CatalogAttribute): + Required. The updated + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to update. The following are NOT supported: + + - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key] + + If not set, all supported fields are updated. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + catalog_attribute = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_catalog.CatalogAttribute, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py new file mode 100644 index 00000000..25fa2861 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py @@ -0,0 +1,1179 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'AttributeConfigLevel', + 'SolutionType', + 'SearchSolutionUseCase', + 'Condition', + 'Rule', + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'LocalInventory', + }, +) + + +class AttributeConfigLevel(proto.Enum): + r"""At which level we offer configuration for attributes.""" + ATTRIBUTE_CONFIG_LEVEL_UNSPECIFIED = 0 + PRODUCT_LEVEL_ATTRIBUTE_CONFIG = 1 + CATALOG_LEVEL_ATTRIBUTE_CONFIG = 2 + + +class SolutionType(proto.Enum): + r"""The type of solution.""" + SOLUTION_TYPE_UNSPECIFIED = 0 + SOLUTION_TYPE_RECOMMENDATION = 1 + SOLUTION_TYPE_SEARCH = 2 + + +class SearchSolutionUseCase(proto.Enum): + r"""The use case of Cloud Retail Search.""" + SEARCH_SOLUTION_USE_CASE_UNSPECIFIED = 0 + SEARCH_SOLUTION_USE_CASE_SEARCH = 1 + SEARCH_SOLUTION_USE_CASE_BROWSE = 2 + + +class Condition(proto.Message): + r"""Metadata that is used to define a condition that triggers an action. + A valid condition must specify at least one of 'query_terms' or + 'products_filter'. If multiple fields are specified, the condition + is met if all the fields are satisfied e.g. if a set of query terms + and product_filter are set, then only items matching the + product_filter for requests with a query matching the query terms + wil get boosted. + + Attributes: + query_terms (Sequence[google.cloud.retail_v2alpha.types.Condition.QueryTerm]): + A list (up to 10 entries) of terms to match + the query on. If not specified, match all + queries. If many query terms are specified, the + condition is matched if any of the terms is a + match (i.e. using the OR operator). + active_time_range (Sequence[google.cloud.retail_v2alpha.types.Condition.TimeRange]): + Range of time(s) specifying when Condition is + active. Condition true if any time range + matches. + """ + + class QueryTerm(proto.Message): + r"""Query terms that we want to match on. + + Attributes: + value (str): + The value of the term to match on. + Value cannot be empty. + Value can have at most 3 terms if specified as a + partial match. Each space separated string is + considered as one term. Example) "a b c" is 3 + terms and allowed, " a b c d" is 4 terms and not + allowed for partial match. + full_match (bool): + Whether this is supposed to be a full or + partial match. + """ + + value = proto.Field( + proto.STRING, + number=1, + ) + full_match = proto.Field( + proto.BOOL, + number=2, + ) + + class TimeRange(proto.Message): + r"""Used for time-dependent conditions. + Example: Want to have rule applied for week long sale. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start of time range. Range is inclusive. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End of time range. Range is inclusive. + """ + + start_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + query_terms = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=QueryTerm, + ) + active_time_range = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TimeRange, + ) + + +class Rule(proto.Message): + r"""A rule is a condition-action pair + + - A condition defines when a rule is to be triggered. + - An action specifies what occurs on that trigger. Currently only + boost rules are supported. Currently only supported by the search + endpoint. + + 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: + boost_action (google.cloud.retail_v2alpha.types.Rule.BoostAction): + A boost action. + + This field is a member of `oneof`_ ``action``. + redirect_action (google.cloud.retail_v2alpha.types.Rule.RedirectAction): + Redirects a shopper to a specific page. + + This field is a member of `oneof`_ ``action``. + oneway_synonyms_action (google.cloud.retail_v2alpha.types.Rule.OnewaySynonymsAction): + Treats specific term as a synonym with a + group of terms. Group of terms will not be + treated as synonyms with the specific term. + + This field is a member of `oneof`_ ``action``. + do_not_associate_action (google.cloud.retail_v2alpha.types.Rule.DoNotAssociateAction): + Prevents term from being associated with + other terms. + + This field is a member of `oneof`_ ``action``. + replacement_action (google.cloud.retail_v2alpha.types.Rule.ReplacementAction): + Replaces specific terms in the query. + + This field is a member of `oneof`_ ``action``. + ignore_action (google.cloud.retail_v2alpha.types.Rule.IgnoreAction): + Ignores specific terms from query during + search. + + This field is a member of `oneof`_ ``action``. + filter_action (google.cloud.retail_v2alpha.types.Rule.FilterAction): + Filters results. + + This field is a member of `oneof`_ ``action``. + twoway_synonyms_action (google.cloud.retail_v2alpha.types.Rule.TwowaySynonymsAction): + Treats a set of terms as synonyms of one + another. + + This field is a member of `oneof`_ ``action``. + condition (google.cloud.retail_v2alpha.types.Condition): + Required. The condition that triggers the + rule. If the condition is empty, the rule will + always apply. + """ + + class BoostAction(proto.Message): + r"""A boost action to apply to results matching condition + specified above. + + Attributes: + boost (float): + Strength of the condition boost, which must be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + products_filter (str): + The filter can have a max size of 5000 characters. An + expression which specifies which products to apply an action + to. The syntax and supported fields are the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": *(id: + ANY("product_1", "product_2"))* *AND* *(colorFamilies: + ANY("Red", "Blue"))* + """ + + boost = proto.Field( + proto.FLOAT, + number=1, + ) + products_filter = proto.Field( + proto.STRING, + number=2, + ) + + class FilterAction(proto.Message): + r"""- Rule Condition: + + - No [Condition][query_terms] provided is a global match. + - 1 or more [Condition][query_terms] provided is combined with + OR operator. + + - Action Input: The request query and filter that will be applied + to the retrieved products, in addition to any filters already + provided with the SearchRequest. The AND operator is used to + combine the query's existing filters with the filter rule(s). + NOTE: May result in 0 results when filters conflict. + - Action Result: Filters the returned objects to be ONLY those that + passed the filter. + + Attributes: + filter (str): + A filter to apply on the matching condition results. + Supported features: + + - [filter][google.cloud.retail.v2alpha.Rule.FilterAction.filter] + must be set. + - Filter syntax is identical to + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter]. + See more details at the Retail Search `user + guide `__. + - To filter products with product ID "product_1" or + "product_2", and color "Red" or "Blue": *(id: + ANY("product_1", "product_2"))* *AND* *(colorFamilies: + ANY("Red", "Blue"))* + """ + + filter = proto.Field( + proto.STRING, + number=1, + ) + + class RedirectAction(proto.Message): + r"""Redirects a shopper to a specific page. + + - Rule Condition: + + - Must specify [Condition][query_terms]. + + - Action Input: Request Query + - Action Result: Redirects shopper to provided uri. + + Attributes: + redirect_uri (str): + URL must have length equal or less than 2000 + characters. + """ + + redirect_uri = proto.Field( + proto.STRING, + number=1, + ) + + class TwowaySynonymsAction(proto.Message): + r"""Creates a set of terms that will be treated as synonyms of each + other. Example: synonyms of "sneakers" and "shoes". + + - "sneakers" will use a synonym of "shoes". + - "shoes" will use a synonym of "sneakers". + + Attributes: + synonyms (Sequence[str]): + Defines a set of synonyms. + Can specify up to 100 synonyms. + Must specify at least 2 synonyms. + """ + + synonyms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class OnewaySynonymsAction(proto.Message): + r"""Maps a set of terms to a set of synonyms. Set of synonyms will be + treated as synonyms of each query term only. ``query_terms`` will + not be treated as synonyms of each other. Example: "sneakers" will + use a synonym of "shoes". "shoes" will not use a synonym of + "sneakers". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. + Will treat synonyms as their synonyms. + Not themselves synonyms of the synonyms. + Can specify up to 100 terms. + synonyms (Sequence[str]): + Defines a set of synonyms. + Cannot contain duplicates. + Can specify up to 100 synonyms. + oneway_terms (Sequence[str]): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=3, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=4, + ) + oneway_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class DoNotAssociateAction(proto.Message): + r"""Prevents ``query_term`` from being associated with specified terms + during search. Example: Don't associate "gShoe" and "cheap". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. Will not consider + do_not_associate_terms for search if in search query. Can + specify up to 100 terms. + do_not_associate_terms (Sequence[str]): + Cannot contain duplicates or the query term. + Can specify up to 100 terms. + terms (Sequence[str]): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + do_not_associate_terms = proto.RepeatedField( + proto.STRING, + number=3, + ) + terms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class ReplacementAction(proto.Message): + r"""Replaces a term in the query. Multiple replacement candidates can be + specified. All ``query_terms`` will be replaced with the replacement + term. Example: Replace "gShoe" with "google shoe". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. + Will be replaced by replacement term. + Can specify up to 100 terms. + replacement_term (str): + Term that will be used for replacement. + term (str): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + replacement_term = proto.Field( + proto.STRING, + number=3, + ) + term = proto.Field( + proto.STRING, + number=1, + ) + + class IgnoreAction(proto.Message): + r"""Prevents a term in the query from being used in search. + Example: Don't search for "shoddy". + + Attributes: + ignore_terms (Sequence[str]): + Terms to ignore in the search query. + """ + + ignore_terms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + boost_action = proto.Field( + proto.MESSAGE, + number=2, + oneof='action', + message=BoostAction, + ) + redirect_action = proto.Field( + proto.MESSAGE, + number=3, + oneof='action', + message=RedirectAction, + ) + oneway_synonyms_action = proto.Field( + proto.MESSAGE, + number=6, + oneof='action', + message=OnewaySynonymsAction, + ) + do_not_associate_action = proto.Field( + proto.MESSAGE, + number=7, + oneof='action', + message=DoNotAssociateAction, + ) + replacement_action = proto.Field( + proto.MESSAGE, + number=8, + oneof='action', + message=ReplacementAction, + ) + ignore_action = proto.Field( + proto.MESSAGE, + number=9, + oneof='action', + message=IgnoreAction, + ) + filter_action = proto.Field( + proto.MESSAGE, + number=10, + oneof='action', + message=FilterAction, + ) + twoway_synonyms_action = proto.Field( + proto.MESSAGE, + number=11, + oneof='action', + message=TwowaySynonymsAction, + ) + condition = proto.Field( + proto.MESSAGE, + number=1, + message='Condition', + ) + + +class Audience(proto.Message): + r"""An intended audience of the + [Product][google.cloud.retail.v2alpha.Product] for whom it's sold. + + Attributes: + genders (Sequence[str]): + The genders of the audience. Strongly encouraged to use the + standard values: "male", "female", "unisex". + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `gender `__. + Schema.org property + `Product.audience.suggestedGender `__. + age_groups (Sequence[str]): + The age groups of the audience. Strongly encouraged to use + the standard values: "newborn" (up to 3 months old), + "infant" (3–12 months old), "toddler" (1–5 years old), + "kids" (5–13 years old), "adult" (typically teens or older). + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `age_group `__. + Schema.org property + `Product.audience.suggestedMinAge `__ + and + `Product.audience.suggestedMaxAge `__. + """ + + genders = proto.RepeatedField( + proto.STRING, + number=1, + ) + age_groups = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class ColorInfo(proto.Message): + r"""The color information of a + [Product][google.cloud.retail.v2alpha.Product]. + + Attributes: + color_families (Sequence[str]): + The standard color families. Strongly recommended to use the + following standard color groups: "Red", "Pink", "Orange", + "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", + "White", "Gray", "Black" and "Mixed". Normally it is + expected to have only 1 color family. May consider using + single "Mixed" instead of multiple values. + + A maximum of 5 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + colors (Sequence[str]): + The color display names, which may be different from + standard color family names, such as the color aliases used + in the website frontend. Normally it is expected to have + only 1 color. May consider using single "Mixed" instead of + multiple values. + + A maximum of 25 colors are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + """ + + color_families = proto.RepeatedField( + proto.STRING, + number=1, + ) + colors = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in + [Product][google.cloud.retail.v2alpha.Product]. + + Attributes: + text (Sequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an INVALID_ARGUMENT + error is returned. + + Exactly one of + [text][google.cloud.retail.v2alpha.CustomAttribute.text] or + [numbers][google.cloud.retail.v2alpha.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + numbers (Sequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [text][google.cloud.retail.v2alpha.CustomAttribute.text] or + [numbers][google.cloud.retail.v2alpha.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + searchable (bool): + This field will only be used when + [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] + of the [Catalog][google.cloud.retail.v2alpha.Catalog] is + 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute + values are searchable by text queries in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2alpha.UserEvent]. + + Only set if type + [text][google.cloud.retail.v2alpha.CustomAttribute.text] is + set. Otherwise, a INVALID_ARGUMENT error is returned. + + This field is a member of `oneof`_ ``_searchable``. + indexable (bool): + This field will only be used when + [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] + of the [Catalog][google.cloud.retail.v2alpha.Catalog] is + 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute + values are indexed, so that it can be filtered, faceted or + boosted in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2alpha.UserEvent]. + + See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter], + [SearchRequest.facet_specs][google.cloud.retail.v2alpha.SearchRequest.facet_specs] + and + [SearchRequest.boost_spec][google.cloud.retail.v2alpha.SearchRequest.boost_spec] + for more details. + + This field is a member of `oneof`_ ``_indexable``. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + searchable = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + indexable = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + +class FulfillmentInfo(proto.Message): + r"""Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + Attributes: + type_ (str): + The fulfillment type, including commonly used types (such as + pickup in store and same day delivery), and custom types. + Customers have to map custom types to their display names + before rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + place_ids (Sequence[str]): + The IDs for this + [type][google.cloud.retail.v2alpha.FulfillmentInfo.type], + such as the store IDs for + [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2alpha.FulfillmentInfo.type] + or the region IDs for + [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2alpha.FulfillmentInfo.type]. + + A maximum of 3000 values are allowed. Each value must be a + string with a length limit of 30 characters, matching the + pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". + Otherwise, an INVALID_ARGUMENT error is returned. + """ + + type_ = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class Image(proto.Message): + r"""[Product][google.cloud.retail.v2alpha.Product] image. + Recommendations AI and Retail Search do not use product images to + improve prediction and search results. However, product images can + be returned in results, and are shown in prediction or search + previews in the console. + + Attributes: + uri (str): + Required. URI of the image. + + This field must be a valid UTF-8 encoded URI with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + height (int): + Height of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + width (int): + Width of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + height = proto.Field( + proto.INT32, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + + +class Interval(proto.Message): + r"""A floating point interval. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum = proto.Field( + proto.DOUBLE, + number=1, + oneof='min', + ) + exclusive_minimum = proto.Field( + proto.DOUBLE, + number=2, + oneof='min', + ) + maximum = proto.Field( + proto.DOUBLE, + number=3, + oneof='max', + ) + exclusive_maximum = proto.Field( + proto.DOUBLE, + number=4, + oneof='max', + ) + + +class PriceInfo(proto.Message): + r"""The price information of a + [Product][google.cloud.retail.v2alpha.Product]. + + Attributes: + currency_code (str): + The 3-letter currency code defined in `ISO + 4217 `__. + + If this field is an unrecognizable currency code, an + INVALID_ARGUMENT error is returned. + + The + [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s with the + same + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] + must share the same + [currency_code][google.cloud.retail.v2alpha.PriceInfo.currency_code]. + Otherwise, a FAILED_PRECONDITION error is returned. + price (float): + Price of the product. + + Google Merchant Center property + `price `__. + Schema.org property + `Offer.price `__. + original_price (float): + Price of the product without any discount. If zero, by + default set to be the + [price][google.cloud.retail.v2alpha.PriceInfo.price]. + cost (float): + The costs associated with the sale of a particular product. + Used for gross profit reporting. + + - Profit = + [price][google.cloud.retail.v2alpha.PriceInfo.price] - + [cost][google.cloud.retail.v2alpha.PriceInfo.cost] + + Google Merchant Center property + `cost_of_goods_sold `__. + price_effective_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2alpha.PriceInfo.price] starts + to be effective. This can be set as a future timestamp, and + the [price][google.cloud.retail.v2alpha.PriceInfo.price] is + only used for search after + [price_effective_time][google.cloud.retail.v2alpha.PriceInfo.price_effective_time]. + If so, the + [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + is used before + [price_effective_time][google.cloud.retail.v2alpha.PriceInfo.price_effective_time]. + + Do not set if + [price][google.cloud.retail.v2alpha.PriceInfo.price] is + always effective because it will cause additional latency + during search. + price_expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2alpha.PriceInfo.price] stops + to be effective. The + [price][google.cloud.retail.v2alpha.PriceInfo.price] is used + for search before + [price_expire_time][google.cloud.retail.v2alpha.PriceInfo.price_expire_time]. + If this field is set, the + [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + is used after + [price_expire_time][google.cloud.retail.v2alpha.PriceInfo.price_expire_time]. + + Do not set if + [price][google.cloud.retail.v2alpha.PriceInfo.price] is + always effective because it will cause additional latency + during search. + price_range (google.cloud.retail_v2alpha.types.PriceInfo.PriceRange): + Output only. The price range of all the child + [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s grouped + together on the + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]. Only + populated for + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct]. + Do not set this field in API requests. + """ + + class PriceRange(proto.Message): + r"""The price range of all + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. + + Attributes: + price (google.cloud.retail_v2alpha.types.Interval): + The inclusive + [Product.pricing_info.price][google.cloud.retail.v2alpha.PriceInfo.price] + interval of all + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] having the + same + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. + original_price (google.cloud.retail_v2alpha.types.Interval): + The inclusive + [Product.pricing_info.original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + internal of all + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] having the + same + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. + """ + + price = proto.Field( + proto.MESSAGE, + number=1, + message='Interval', + ) + original_price = proto.Field( + proto.MESSAGE, + number=2, + message='Interval', + ) + + currency_code = proto.Field( + proto.STRING, + number=1, + ) + price = proto.Field( + proto.FLOAT, + number=2, + ) + original_price = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + price_effective_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + price_expire_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + price_range = proto.Field( + proto.MESSAGE, + number=7, + message=PriceRange, + ) + + +class Rating(proto.Message): + r"""The rating of a [Product][google.cloud.retail.v2alpha.Product]. + + Attributes: + rating_count (int): + The total number of ratings. This value is independent of + the value of + [rating_histogram][google.cloud.retail.v2alpha.Rating.rating_histogram]. + + This value must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + average_rating (float): + The average rating of the + [Product][google.cloud.retail.v2alpha.Product]. + + The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT + error is returned. + rating_histogram (Sequence[int]): + List of rating counts per rating value (index = rating - 1). + The list is empty if there is no rating. If the list is + non-empty, its size is always 5. Otherwise, an + INVALID_ARGUMENT error is returned. + + For example, [41, 14, 13, 47, 303]. It means that the + [Product][google.cloud.retail.v2alpha.Product] got 41 + ratings with 1 star, 14 ratings with 2 star, and so on. + """ + + rating_count = proto.Field( + proto.INT32, + number=1, + ) + average_rating = proto.Field( + proto.FLOAT, + number=2, + ) + rating_histogram = proto.RepeatedField( + proto.INT32, + number=3, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. + + Always use a hashed value for this ID. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + ip_address (str): + The end user's IP address. This field is used to extract + location information for personalization. + + This field must be either an IPv4 address (e.g. + "104.133.9.80") or an IPv6 address (e.g. + "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an + INVALID_ARGUMENT error is returned. + + This should not be set when: + + - setting + [SearchRequest.user_info][google.cloud.retail.v2alpha.SearchRequest.user_info]. + - using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2alpha.UserInfo.direct_user_request] + is set. + user_agent (str): + User agent as included in the HTTP header. Required for + getting + [SearchResponse.sponsored_results][google.cloud.retail.v2alpha.SearchResponse.sponsored_results]. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2alpha.UserInfo.direct_user_request] + is set. + direct_user_request (bool): + True if the request is made directly from the end user, in + which case the + [ip_address][google.cloud.retail.v2alpha.UserInfo.ip_address] + and + [user_agent][google.cloud.retail.v2alpha.UserInfo.user_agent] + can be populated from the HTTP request. This flag should be + set only if the API request is made directly from the end + user such as a mobile app (and not if a gateway or a server + is processing and pushing the user events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent]. + """ + + user_id = proto.Field( + proto.STRING, + number=1, + ) + ip_address = proto.Field( + proto.STRING, + number=2, + ) + user_agent = proto.Field( + proto.STRING, + number=3, + ) + direct_user_request = proto.Field( + proto.BOOL, + number=4, + ) + + +class LocalInventory(proto.Message): + r"""The inventory information at a place (e.g. a store) + identified by a place ID. + + Attributes: + place_id (str): + The place ID for the current set of inventory + information. + price_info (google.cloud.retail_v2alpha.types.PriceInfo): + Product price and cost information. + + Google Merchant Center property + `price `__. + attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): + Additional local inventory attributes, for example, store + name, promotion tags, etc. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - At most 30 attributes are allowed. + - The key must be a UTF-8 encoded string with a length + limit of 32 characters. + - The key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis + or KEY_1_LIKE_THIS. + - The attribute values must be of the same type (text or + number). + - Only 1 value is allowed for each attribute. + - For text values, the length limit is 256 UTF-8 + characters. + - The attribute does not support search. The ``searchable`` + field should be unset or set to false. + - The max summed total bytes of custom attribute keys and + values per product is 5MiB. + fulfillment_types (Sequence[str]): + Input only. Supported fulfillment types. Valid fulfillment + type values include commonly used types (such as pickup in + store and same day delivery), and custom types. Customers + have to map custom types to their display names before + rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + All the elements must be distinct. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + place_id = proto.Field( + proto.STRING, + number=1, + ) + price_info = proto.Field( + proto.MESSAGE, + number=2, + message='PriceInfo', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='CustomAttribute', + ) + fulfillment_types = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py new file mode 100644 index 00000000..f3bb27b3 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'CompleteQueryRequest', + 'CompleteQueryResponse', + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Auto-complete parameters. + + Attributes: + catalog (str): + Required. Catalog for which the completion is performed. + + Full resource name of catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + query (str): + Required. The query used to generate + suggestions. + The maximum number of allowed characters is 255. + visitor_id (str): + Required field. A unique identifier for tracking visitors. + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + language_codes (Sequence[str]): + The language filters applied to the output suggestions. If + set, it should contain the language of the query. If not + set, suggestions are returned without considering language + restrictions. This is the BCP-47 language code, such as + "en-US" or "sr-Latn". For more information, see `Tags for + Identifying + Languages `__. The + maximum number of language codes is 3. + device_type (str): + The device type context for completion suggestions. It is + useful to apply different suggestions on different device + types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the + suggestions are across all device types. + + Supported formats: + + - ``UNKNOWN_DEVICE_TYPE`` + + - ``DESKTOP`` + + - ``MOBILE`` + + - A customized string starts with ``OTHER_``, e.g. + ``OTHER_IPHONE``. + dataset (str): + Determines which dataset to use for fetching completion. + "user-data" will use the imported dataset through + [CompletionService.ImportCompletionData][google.cloud.retail.v2alpha.CompletionService.ImportCompletionData]. + "cloud-retail" will use the dataset generated by cloud + retail based on user events. If leave empty, it will use the + "user-data". + + Current supported values: + + - user-data + + - cloud-retail This option requires additional + allowlisting. Before using cloud-retail, contact Cloud + Retail support team first. + max_suggestions (int): + Completion max suggestions. If left unset or set to 0, then + will fallback to the configured value + [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions]. + + The maximum allowed max suggestions is 20. If it is set + higher, it will be capped by 20. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + visitor_id = proto.Field( + proto.STRING, + number=7, + ) + language_codes = proto.RepeatedField( + proto.STRING, + number=3, + ) + device_type = proto.Field( + proto.STRING, + number=4, + ) + dataset = proto.Field( + proto.STRING, + number=6, + ) + max_suggestions = proto.Field( + proto.INT32, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response of the auto-complete query. + + Attributes: + completion_results (Sequence[google.cloud.retail_v2alpha.types.CompleteQueryResponse.CompletionResult]): + Results of the matching suggestions. The + result list is ordered and the first result is + top suggestion. + attribution_token (str): + A unique complete token. This should be included in the + [UserEvent.completion_detail][google.cloud.retail.v2alpha.UserEvent.completion_detail] + for search events resulting from this completion, which + enables accurate attribution of complete model performance. + recent_search_results (Sequence[google.cloud.retail_v2alpha.types.CompleteQueryResponse.RecentSearchResult]): + Matched recent searches of this user. The maximum number of + recent searches is 10. This field is a restricted feature. + Contact Retail Search support team if you are interested in + enabling it. + + This feature is only available when + [CompleteQueryRequest.visitor_id][google.cloud.retail.v2alpha.CompleteQueryRequest.visitor_id] + field is set and + [UserEvent][google.cloud.retail.v2alpha.UserEvent] is + imported. The recent searches satisfy the follow rules: + + - They are ordered from latest to oldest. + - They are matched with + [CompleteQueryRequest.query][google.cloud.retail.v2alpha.CompleteQueryRequest.query] + case insensitively. + - They are transformed to lower cases. + - They are UTF-8 safe. + + Recent searches are deduplicated. More recent searches will + be reserved when duplication happens. + """ + + class CompletionResult(proto.Message): + r"""Resource that represents completion results. + + Attributes: + suggestion (str): + The suggestion for the query. + attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): + Custom attributes for the suggestion term. + + - For "user-data", the attributes are additional custom + attributes ingested through BigQuery. + - For "cloud-retail", the attributes are product attributes + generated by Cloud Retail. + """ + + suggestion = proto.Field( + proto.STRING, + number=1, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=common.CustomAttribute, + ) + + class RecentSearchResult(proto.Message): + r"""Recent search of this user. + + Attributes: + recent_search (str): + The recent search query. + """ + + recent_search = proto.Field( + proto.STRING, + number=1, + ) + + completion_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=CompletionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + recent_search_results = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=RecentSearchResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py new file mode 100644 index 00000000..93e84d08 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'Control', + }, +) + + +class Control(proto.Message): + r"""Configures dynamic serving time metadata that is used to pre + and post process search/recommendation model results. + + 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: + facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec): + A facet specification to perform faceted + search. + + This field is a member of `oneof`_ ``control``. + rule (google.cloud.retail_v2alpha.types.Rule): + A rule control - a condition-action pair. + Enacts a set action when the condition is + triggered. For example: Boost "gShoe" when query + full matches "Running Shoes". + + This field is a member of `oneof`_ ``control``. + name (str): + Immutable. Fully qualified name + projects/\ */locations/global/catalogs/*/controls/\* + display_name (str): + Required. The human readable control display name. Used in + Retail UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is thrown. + associated_serving_config_ids (Sequence[str]): + Output only. List of serving configuration + ids that that are associated with this control. + Note the association is managed via the + ServingConfig, this is an output only + denormalizeed view. Assumed to be in the same + catalog. + solution_types (Sequence[google.cloud.retail_v2alpha.types.SolutionType]): + Required. Immutable. The solution types that the serving + config is used for. Currently we support setting only one + type of solution at creation time. + + Only ``SOLUTION_TYPE_SEARCH`` value is supported at the + moment. If no solution type is provided at creation time, + will default to SOLUTION_TYPE_SEARCH. + search_solution_use_case (Sequence[google.cloud.retail_v2alpha.types.SearchSolutionUseCase]): + Required. Specifies the use case for the control. Affects + what condition fields can be set. Only settable by search + controls. Will default to SEARCH_SOLUTION_USE_CASE_SEARCH if + not specified. Currently only allow one + search_solution_use_case per control. + """ + + facet_spec = proto.Field( + proto.MESSAGE, + number=3, + oneof='control', + message=search_service.SearchRequest.FacetSpec, + ) + rule = proto.Field( + proto.MESSAGE, + number=4, + oneof='control', + message=common.Rule, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + associated_serving_config_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + solution_types = proto.RepeatedField( + proto.ENUM, + number=6, + enum=common.SolutionType, + ) + search_solution_use_case = proto.RepeatedField( + proto.ENUM, + number=7, + enum=common.SearchSolutionUseCase, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py new file mode 100644 index 00000000..da0c4915 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'CreateControlRequest', + 'UpdateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + }, +) + + +class CreateControlRequest(proto.Message): + r"""Request for CreateControl method. + + Attributes: + parent (str): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + control (google.cloud.retail_v2alpha.types.Control): + Required. The Control to create. + control_id (str): + Required. The ID to use for the Control, which will become + the final component of the Control's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-_/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + control = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_control.Control, + ) + control_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateControlRequest(proto.Message): + r"""Request for UpdateControl method. + + Attributes: + control (google.cloud.retail_v2alpha.types.Control): + Required. The Control to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Control][google.cloud.retail.v2alpha.Control] to update. + The following are NOT supported: + + - [Control.name][google.cloud.retail.v2alpha.Control.name] + + If not set or empty, all supported fields are updated. + """ + + control = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_control.Control, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteControlRequest(proto.Message): + r"""Request for DeleteControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetControlRequest(proto.Message): + r"""Request for GetControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListControlsRequest(proto.Message): + r"""Request for ListControls method. + + Attributes: + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 50. Max + allowed value is 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListControls`` call. Provide this to retrieve the + subsequent page. + filter (str): + Optional. A filter to apply on the list results. Supported + features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2alpha.ListControlsRequest.filter] + is unset. + - List controls that are used in a single ServingConfig: + 'serving_config = "boosted_home_page_cvr"' + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListControlsResponse(proto.Message): + r"""Response for ListControls method. + + Attributes: + controls (Sequence[google.cloud.retail_v2alpha.types.Control]): + All the Controls for a given catalog. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + controls = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_control.Control, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py new file mode 100644 index 00000000..ffb42fde --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + }, +) + + +class ExportErrorsConfig(proto.Message): + r"""Configuration of destination for Export related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage path for import errors. This must be an + empty, existing Cloud Storage bucket. Export errors will be + written to a file in this bucket, one per line, as a + JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ExportMetadata(proto.Message): + r"""Metadata related to the progress of the Export operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ExportProductsResponse(proto.Message): + r"""Response of the ExportProductsRequest. If the long running + operation is done, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2alpha.types.ExportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExportErrorsConfig', + ) + + +class ExportUserEventsResponse(proto.Message): + r"""Response of the ExportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2alpha.types.ExportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExportErrorsConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py new file mode 100644 index 00000000..b6260358 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py @@ -0,0 +1,691 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import user_event +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'GcsSource', + 'BigQuerySource', + 'ProductInlineSource', + 'UserEventInlineSource', + 'ImportErrorsConfig', + 'ImportProductsRequest', + 'ImportUserEventsRequest', + 'ImportCompletionDataRequest', + 'ProductInputConfig', + 'UserEventInputConfig', + 'CompletionDataInputConfig', + 'ImportMetadata', + 'ImportProductsResponse', + 'ImportUserEventsResponse', + 'UserEventImportSummary', + 'ImportCompletionDataResponse', + }, +) + + +class GcsSource(proto.Message): + r"""Google Cloud Storage location for input content. + format. + + Attributes: + input_uris (Sequence[str]): + Required. Google Cloud Storage URIs to input files. URI can + be up to 2000 characters long. URIs can match the full + object path (for example, + ``gs://bucket/directory/object.json``) or a pattern matching + one or more files, such as ``gs://bucket/directory/*.json``. + A request can contain at most 100 files, and each file can + be up to 2 GB. See `Importing product + information `__ + for the expected file format and setup instructions. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2alpha.Product] per line. + Each product must have a valid + [Product.id][google.cloud.retail.v2alpha.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2alpha.UserEvent] per + line. + - ``user_event_ga360``: Using + https://support.google.com/analytics/answer/3437719. + + Supported values for control imports: + + - 'control' (default): One JSON + [Control][google.cloud.retail.v2alpha.Control] per line. + + Supported values for catalog attribute imports: + + - 'catalog_attribute' (default): One CSV + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + per line. + """ + + input_uris = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID (can be project # or ID) that + the BigQuery source is in with a length limit of + 128 characters. If not specified, inherits the + project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2alpha.Product] per line. + Each product must have a valid + [Product.id][google.cloud.retail.v2alpha.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2alpha.UserEvent] per + line. + - ``user_event_ga360``: The schema is available here: + https://support.google.com/analytics/answer/3437719. + - ``user_event_ga4``: This feature is in private preview. + Please contact the support team for importing Google + Analytics 4 events. The schema is available here: + https://support.google.com/analytics/answer/7029846. + + Supported values for auto-completion imports: + + - ``suggestions`` (default): One JSON completion suggestion + per line. + - ``denylist``: One JSON deny suggestion per line. + - ``allowlist``: One JSON allow suggestion per line. + """ + + partition_date = proto.Field( + proto.MESSAGE, + number=6, + oneof='partition', + message=date_pb2.Date, + ) + project_id = proto.Field( + proto.STRING, + number=5, + ) + dataset_id = proto.Field( + proto.STRING, + number=1, + ) + table_id = proto.Field( + proto.STRING, + number=2, + ) + gcs_staging_dir = proto.Field( + proto.STRING, + number=3, + ) + data_schema = proto.Field( + proto.STRING, + number=4, + ) + + +class ProductInlineSource(proto.Message): + r"""The inline source for the input config for ImportProducts + method. + + Attributes: + products (Sequence[google.cloud.retail_v2alpha.types.Product]): + Required. A list of products to update/create. Each product + must have a valid + [Product.id][google.cloud.retail.v2alpha.Product.id]. + Recommended max of 100 items. + """ + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=product.Product, + ) + + +class UserEventInlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (Sequence[google.cloud.retail_v2alpha.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + +class ImportErrorsConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage prefix for import errors. This must be + an empty, existing Cloud Storage directory. Import errors + will be written to sharded files in this directory, one per + line, as a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportProductsRequest(proto.Message): + r"""Request message for Import methods. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` + + If no updateMask is specified, requires products.create + permission. If updateMask is specified, requires + products.update permission. + request_id (str): + Deprecated. This field has no effect. + input_config (google.cloud.retail_v2alpha.types.ProductInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported 'products' to update. If not set, will + by default update all fields. + reconciliation_mode (google.cloud.retail_v2alpha.types.ImportProductsRequest.ReconciliationMode): + The mode of reconciliation between existing products and the + products to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + """ + class ReconciliationMode(proto.Enum): + r"""Indicates how imported products are reconciled with the + existing products created or imported before. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + request_id = proto.Field( + proto.STRING, + number=6, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='ProductInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + reconciliation_mode = proto.Field( + proto.ENUM, + number=5, + enum=ReconciliationMode, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=7, + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + input_config (google.cloud.retail_v2alpha.types.UserEventInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='UserEventInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + + +class ImportCompletionDataRequest(proto.Message): + r"""Request message for ImportCompletionData methods. + + Attributes: + parent (str): + Required. The catalog which the suggestions dataset belongs + to. + + Format: + ``projects/1234/locations/global/catalogs/default_catalog``. + input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): + Required. The desired input location of the + data. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='CompletionDataInputConfig', + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=3, + ) + + +class ProductInputConfig(proto.Message): + r"""The input config source for products. + + 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: + product_inline_source (google.cloud.retail_v2alpha.types.ProductInlineSource): + The Inline source for the input content for + products. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2alpha.types.GcsSource): + Google Cloud Storage location for the input + content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + product_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='ProductInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class UserEventInputConfig(proto.Message): + r"""The input config source for user events. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user_event_inline_source (google.cloud.retail_v2alpha.types.UserEventInlineSource): + Required. The Inline source for the input + content for UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2alpha.types.GcsSource): + Required. Google Cloud Storage location for + the input content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): + Required. BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + user_event_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='UserEventInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class CompletionDataInputConfig(proto.Message): + r"""The input config source for completion data. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): + Required. BigQuery input source. + Add the IAM permission "BigQuery Data Viewer" + for + cloud-retail-customer-data-access@system.gserviceaccount.com + before using this feature otherwise an error is + thrown. + + This field is a member of `oneof`_ ``source``. + """ + + big_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='BigQuerySource', + ) + + +class ImportMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + request_id (str): + Deprecated. This field is never set. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=3, + ) + failure_count = proto.Field( + proto.INT64, + number=4, + ) + request_id = proto.Field( + proto.STRING, + number=5, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=6, + ) + + +class ImportProductsResponse(proto.Message): + r"""Response of the + [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + import_summary (google.cloud.retail_v2alpha.types.UserEventImportSummary): + Aggregated statistics of user event import + status. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + import_summary = proto.Field( + proto.MESSAGE, + number=3, + message='UserEventImportSummary', + ) + + +class UserEventImportSummary(proto.Message): + r"""A summary of import result. The UserEventImportSummary + summarizes the import status for user events. + + Attributes: + joined_events_count (int): + Count of user events imported with complete + existing catalog information. + unjoined_events_count (int): + Count of user events imported, but with + catalog information not found in the imported + catalog. + """ + + joined_events_count = proto.Field( + proto.INT64, + number=1, + ) + unjoined_events_count = proto.Field( + proto.INT64, + number=2, + ) + + +class ImportCompletionDataResponse(proto.Message): + r"""Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. + 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 (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py new file mode 100644 index 00000000..51233cae --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import user_event as gcr_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'PredictRequest', + 'PredictResponse', + }, +) + + +class PredictRequest(proto.Message): + r"""Request message for Predict method. + + Attributes: + placement (str): + Required. Full resource name of the format: + {name=projects/*/locations/global/catalogs/default_catalog/placements/*} + The ID of the Recommendations AI placement. Before you can + request predictions from your model, you must create at + least one placement for it. For more information, see + `Managing + placements `__. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements + user_event (google.cloud.retail_v2alpha.types.UserEvent): + Required. Context about the user, what they + are looking at and what action they took to + trigger the predict request. Note that this user + event detail won't be ingested to userEvent + logs. Thus, a separate userEvent write request + is required for event logging. + page_size (int): + Maximum number of results to return per page. + Set this property to the number of prediction + results needed. If zero, the service will choose + a reasonable default. The maximum allowed value + is 100. Values above 100 will be coerced to 100. + page_token (str): + The previous PredictResponse.next_page_token. + filter (str): + Filter for restricting prediction results with a length + limit of 5,000 characters. Accepts values for tags and the + ``filterOutOfStockItems`` flag. + + - Tag expressions. Restricts predictions to products that + match all of the specified tags. Boolean operators ``OR`` + and ``NOT`` are supported if the expression is enclosed + in parentheses, and must be separated from the tag values + by a space. ``-"tagA"`` is also supported and is + equivalent to ``NOT "tagA"``. Tag values must be double + quoted UTF-8 encoded strings with a size limit of 1,000 + characters. + + Note: "Recently viewed" models don't support tag + filtering at the moment. + + - filterOutOfStockItems. Restricts predictions to products + that do not have a stockState value of OUT_OF_STOCK. + + Examples: + + - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT + "promotional") + - filterOutOfStockItems tag=(-"promotional") + - filterOutOfStockItems + + If your filter blocks all prediction results, the API will + return generic (unfiltered) popular products. If you only + want results strictly matching the filters, set + ``strictFiltering`` to True in ``PredictRequest.params`` to + receive empty results instead. Note that the API will never + return items with storageStatus of "EXPIRED" or "DELETED" + regardless of filter choices. + validate_only (bool): + Use validate only mode for this prediction + query. If set to true, a dummy model will be + used that returns arbitrary products. Note that + the validate only mode should only be used for + testing the API, or if the model is not ready. + params (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific parameters for the predictions. + + Allowed values: + + - ``returnProduct``: Boolean. If set to true, the + associated product object will be returned in the + ``results.metadata`` field in the prediction response. + - ``returnScore``: Boolean. If set to true, the prediction + 'score' corresponding to each returned product will be + set in the ``results.metadata`` field in the prediction + response. The given 'score' indicates the probability of + an product being clicked/purchased given the user's + context and history. + - ``strictFiltering``: Boolean. True by default. If set to + false, the service will return generic (unfiltered) + popular products instead of empty if your filter blocks + all prediction results. + - ``priceRerankLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of + {'no-price-reranking', 'low-price-reranking', + 'medium-price-reranking', 'high-price-reranking'}. This + gives request-level control and adjusts prediction + results based on product price. + - ``diversityLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of {'no-diversity', + 'low-diversity', 'medium-diversity', 'high-diversity', + 'auto-diversity'}. This gives request-level control and + adjusts prediction results based on product category. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters, and cannot be empty. Values can + be empty, and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + placement = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + filter = proto.Field( + proto.STRING, + number=5, + ) + validate_only = proto.Field( + proto.BOOL, + number=6, + ) + params = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class PredictResponse(proto.Message): + r"""Response message for predict method. + + Attributes: + results (Sequence[google.cloud.retail_v2alpha.types.PredictResponse.PredictionResult]): + A list of recommended products. The order + represents the ranking (from the most relevant + product to the least). + attribution_token (str): + A unique attribution token. This should be included in the + [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs + resulting from this recommendation, which enables accurate + attribution of recommendation model performance. + missing_ids (Sequence[str]): + IDs of products in the request that were + missing from the inventory. + validate_only (bool): + True if the validateOnly property was set in + the request. + """ + + class PredictionResult(proto.Message): + r"""PredictionResult represents the recommendation prediction + results. + + Attributes: + id (str): + ID of the recommended product + metadata (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional product metadata / annotations. + + Possible values: + + - ``product``: JSON representation of the product. Will be + set if ``returnProduct`` is set to true in + ``PredictRequest.params``. + - ``score``: Prediction score in double value. Will be set + if ``returnScore`` is set to true in + ``PredictRequest.params``. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + metadata = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=PredictionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + missing_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py new file mode 100644 index 00000000..492a51ff --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py @@ -0,0 +1,705 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'Product', + }, +) + + +class Product(proto.Message): + r"""Product captures all metadata information of items to be + recommended or searched. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this product becomes unavailable for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + If it is set, the + [Product][google.cloud.retail.v2alpha.Product] is not + available for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + after + [expire_time][google.cloud.retail.v2alpha.Product.expire_time]. + However, the product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + [expire_time][google.cloud.retail.v2alpha.Product.expire_time] + must be later than + [available_time][google.cloud.retail.v2alpha.Product.available_time] + and + [publish_time][google.cloud.retail.v2alpha.Product.publish_time], + otherwise an INVALID_ARGUMENT error is thrown. + + Corresponding properties: Google Merchant Center property + `expiration_date `__. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Input only. The TTL (time to live) of the product. + + If it is set, it must be a non-negative value, and + [expire_time][google.cloud.retail.v2alpha.Product.expire_time] + is set as current timestamp plus + [ttl][google.cloud.retail.v2alpha.Product.ttl]. The derived + [expire_time][google.cloud.retail.v2alpha.Product.expire_time] + is returned in the output and + [ttl][google.cloud.retail.v2alpha.Product.ttl] is left blank + when retrieving the + [Product][google.cloud.retail.v2alpha.Product]. + + If it is set, the product is not available for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + after current timestamp plus + [ttl][google.cloud.retail.v2alpha.Product.ttl]. However, the + product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This field is a member of `oneof`_ ``expiration``. + name (str): + Immutable. Full resource name of the product, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. + id (str): + Immutable. [Product][google.cloud.retail.v2alpha.Product] + identifier, which is the final component of + [name][google.cloud.retail.v2alpha.Product.name]. For + example, this field is "id_1", if + [name][google.cloud.retail.v2alpha.Product.name] is + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `id `__. + Schema.org property + `Product.sku `__. + type_ (google.cloud.retail_v2alpha.types.Product.Type): + Immutable. The type of the product. Default to + [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2alpha.ProductLevelConfig.ingestion_product_type] + if unset. + primary_product_id (str): + Variant group identifier. Must be an + [id][google.cloud.retail.v2alpha.Product.id], with the same + parent branch with this product. Otherwise, an error is + thrown. + + For + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]s, this field + can only be empty or set to the same value as + [id][google.cloud.retail.v2alpha.Product.id]. + + For VARIANT [Product][google.cloud.retail.v2alpha.Product]s, + this field cannot be empty. A maximum of 2,000 products are + allowed to share the same + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]. Otherwise, + an INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `item_group_id `__. + Schema.org property + `Product.inProductGroupWithID `__. + collection_member_ids (Sequence[str]): + The [id][google.cloud.retail.v2alpha.Product.id] of the + collection members when + [type][google.cloud.retail.v2alpha.Product.type] is + [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION]. + + Non-existent product ids are allowed. The + [type][google.cloud.retail.v2alpha.Product.type] of the + members must be either + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + or + [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + otherwise and INVALID_ARGUMENT error is thrown. Should not + set it for other types. A maximum of 1000 values are + allowed. Otherwise, an INVALID_ARGUMENT error is return. + gtin (str): + The Global Trade Item Number (GTIN) of the product. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This field must be a Unigram. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `gtin `__. + Schema.org property + `Product.isbn `__, + `Product.gtin8 `__, + `Product.gtin12 `__, + `Product.gtin13 `__, or + `Product.gtin14 `__. + + If the value is not a valid GTIN, an INVALID_ARGUMENT error + is returned. + categories (Sequence[str]): + Product categories. This field is repeated for supporting + one product belonging to several parallel categories. + Strongly recommended using the full path for better search / + recommendation quality. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + For example, if a shoes product belongs to both ["Shoes & + Accessories" -> "Shoes"] and ["Sports & Fitness" -> + "Athletic Clothing" -> "Shoes"], it could be represented as: + + :: + + "categories": [ + "Shoes & Accessories > Shoes", + "Sports & Fitness > Athletic Clothing > Shoes" + ] + + Must be set for + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] otherwise an + INVALID_ARGUMENT error is returned. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. Empty values + are not allowed. Each value must be a UTF-8 encoded string + with a length limit of 5,000 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `google_product_category `__. + Schema.org property [Product.category] + (https://schema.org/category). + title (str): + Required. Product title. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `title `__. + Schema.org property + `Product.name `__. + brands (Sequence[str]): + The brands of the product. + + A maximum of 30 brands are allowed. Each brand must be a + UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `brand `__. + Schema.org property + `Product.brand `__. + description (str): + Product description. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `description `__. + Schema.org property + `Product.description `__. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. + + For product prediction, this field is ignored and the model + automatically detects the text language. The + [Product][google.cloud.retail.v2alpha.Product] can include + text in different languages, but duplicating + [Product][google.cloud.retail.v2alpha.Product]s to provide + text in multiple languages can result in degraded model + performance. + + For product search this field is in use. It defaults to + "en-US" if unset. + attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): + Highly encouraged. Extra product attributes to be included. + For example, for products, this could include the store + name, vendor, style, color, etc. These are very strong + signals for recommendation model, thus we highly recommend + providing the attributes here. + + Features that can take on one of a limited number of + possible values. Two types of features can be set are: + + Textual features. some examples would be the brand/maker of + a product, or country of a customer. Numerical features. + Some examples would be the height/weight of a product, or + age of a customer. + + For example: + ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - Max entries count: 200. + - The key must be a UTF-8 encoded string with a length + limit of 128 characters. + - For indexable attribute, the key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, + ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a + non-empty UTF-8 encoded string with a length limit of 256 + characters. + - For number attributes, at most 400 values are allowed. + tags (Sequence[str]): + Custom tags associated with the product. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. This value + must be a UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This tag can be used for filtering recommendation results by + passing the tag as part of the + [PredictRequest.filter][google.cloud.retail.v2alpha.PredictRequest.filter]. + + Corresponding properties: Google Merchant Center property + `custom_label_0–4 `__. + price_info (google.cloud.retail_v2alpha.types.PriceInfo): + Product price and cost information. + + Corresponding properties: Google Merchant Center property + `price `__. + rating (google.cloud.retail_v2alpha.types.Rating): + The rating of this product. + available_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this + [Product][google.cloud.retail.v2alpha.Product] becomes + available for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + availability (google.cloud.retail_v2alpha.types.Product.Availability): + The online availability of the + [Product][google.cloud.retail.v2alpha.Product]. Default to + [Availability.IN_STOCK][google.cloud.retail.v2alpha.Product.Availability.IN_STOCK]. + + Corresponding properties: Google Merchant Center property + `availability `__. + Schema.org property + `Offer.availability `__. + available_quantity (google.protobuf.wrappers_pb2.Int32Value): + The available quantity of the item. + fulfillment_info (Sequence[google.cloud.retail_v2alpha.types.FulfillmentInfo]): + Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + All the elements must have distinct + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type]. + Otherwise, an INVALID_ARGUMENT error is returned. + uri (str): + Canonical URL directly linking to the product detail page. + + It is strongly recommended to provide a valid uri for the + product, otherwise the service performance could be + significantly degraded. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `link `__. + Schema.org property `Offer.url `__. + images (Sequence[google.cloud.retail_v2alpha.types.Image]): + Product images for the product. We highly recommend putting + the main image first. + + A maximum of 300 images are allowed. + + Corresponding properties: Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + audience (google.cloud.retail_v2alpha.types.Audience): + The target group associated with a given + audience (e.g. male, veterans, car owners, + musicians, etc.) of the product. + color_info (google.cloud.retail_v2alpha.types.ColorInfo): + The color of the product. + + Corresponding properties: Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + sizes (Sequence[str]): + The size of the product. To represent different size systems + or size types, consider using this format: + [[[size_system:]size_type:]size_value]. + + For example, in "US:MENS:M", "US" represents size system; + "MENS" represents size type; "M" represents size value. In + "GIRLS:27", size system is empty; "GIRLS" represents size + type; "27" represents size value. In "32 inches", both size + system and size type are empty, while size value is "32 + inches". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `size `__, + `size_type `__, + and + `size_system `__. + Schema.org property + `Product.size `__. + materials (Sequence[str]): + The material of the product. For example, "leather", + "wooden". + + A maximum of 20 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 200 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `material `__. + Schema.org property + `Product.material `__. + patterns (Sequence[str]): + The pattern or graphic print of the product. For example, + "striped", "polka dot", "paisley". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `pattern `__. + Schema.org property + `Product.pattern `__. + conditions (Sequence[str]): + The condition of the product. Strongly encouraged to use the + standard values: "new", "refurbished", "used". + + A maximum of 1 value is allowed per + [Product][google.cloud.retail.v2alpha.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `condition `__. + Schema.org property + `Offer.itemCondition `__. + promotions (Sequence[google.cloud.retail_v2alpha.types.Promotion]): + The promotions applied to the product. A maximum of 10 + values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. Only + [Promotion.promotion_id][google.cloud.retail.v2alpha.Promotion.promotion_id] + will be used, other fields will be ignored if set. + publish_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the product is published by the retailer + for the first time, which indicates the freshness of the + products. Note that this field is different from + [available_time][google.cloud.retail.v2alpha.Product.available_time], + given it purely describes product freshness regardless of + when it is available on search and recommendation. + retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the + [Product][google.cloud.retail.v2alpha.Product]s are returned + in + [SearchResponse][google.cloud.retail.v2alpha.SearchResponse]. + + Supported fields for all + [type][google.cloud.retail.v2alpha.Product.type]s: + + - [audience][google.cloud.retail.v2alpha.Product.audience] + - [availability][google.cloud.retail.v2alpha.Product.availability] + - [brands][google.cloud.retail.v2alpha.Product.brands] + - [color_info][google.cloud.retail.v2alpha.Product.color_info] + - [conditions][google.cloud.retail.v2alpha.Product.conditions] + - [gtin][google.cloud.retail.v2alpha.Product.gtin] + - [materials][google.cloud.retail.v2alpha.Product.materials] + - [name][google.cloud.retail.v2alpha.Product.name] + - [patterns][google.cloud.retail.v2alpha.Product.patterns] + - [price_info][google.cloud.retail.v2alpha.Product.price_info] + - [rating][google.cloud.retail.v2alpha.Product.rating] + - [sizes][google.cloud.retail.v2alpha.Product.sizes] + - [title][google.cloud.retail.v2alpha.Product.title] + - [uri][google.cloud.retail.v2alpha.Product.uri] + + Supported fields only for + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION]: + + - [categories][google.cloud.retail.v2alpha.Product.categories] + - [description][google.cloud.retail.v2alpha.Product.description] + - [images][google.cloud.retail.v2alpha.Product.images] + + Supported fields only for + [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT]: + + - Only the first image in + [images][google.cloud.retail.v2alpha.Product.images] + + To mark + [attributes][google.cloud.retail.v2alpha.Product.attributes] + as retrievable, include paths of the form "attributes.key" + where "key" is the key of a custom attribute, as specified + in + [attributes][google.cloud.retail.v2alpha.Product.attributes]. + + For + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION], + the following fields are always returned in + [SearchResponse][google.cloud.retail.v2alpha.SearchResponse] + by default: + + - [name][google.cloud.retail.v2alpha.Product.name] + + For + [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT], + the following fields are always returned in by default: + + - [name][google.cloud.retail.v2alpha.Product.name] + - [color_info][google.cloud.retail.v2alpha.Product.color_info] + + Maximum number of paths is 30. Otherwise, an + INVALID_ARGUMENT error is returned. + + Note: Returning more fields in + [SearchResponse][google.cloud.retail.v2alpha.SearchResponse] + may increase response payload size and serving latency. + variants (Sequence[google.cloud.retail_v2alpha.types.Product]): + Output only. Product variants grouped together on primary + product which share similar product attributes. It's + automatically grouped by + [primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] + for all the product variants. Only populated for + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct]. + Do not set this field in API requests. + """ + class Type(proto.Enum): + r"""The type of this product.""" + TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + VARIANT = 2 + COLLECTION = 3 + + class Availability(proto.Enum): + r"""Product availability. If this field is unspecified, the + product is assumed to be in stock. + """ + AVAILABILITY_UNSPECIFIED = 0 + IN_STOCK = 1 + OUT_OF_STOCK = 2 + PREORDER = 3 + BACKORDER = 4 + + expire_time = proto.Field( + proto.MESSAGE, + number=16, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl = proto.Field( + proto.MESSAGE, + number=17, + oneof='expiration', + message=duration_pb2.Duration, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + type_ = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + primary_product_id = proto.Field( + proto.STRING, + number=4, + ) + collection_member_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + gtin = proto.Field( + proto.STRING, + number=6, + ) + categories = proto.RepeatedField( + proto.STRING, + number=7, + ) + title = proto.Field( + proto.STRING, + number=8, + ) + brands = proto.RepeatedField( + proto.STRING, + number=9, + ) + description = proto.Field( + proto.STRING, + number=10, + ) + language_code = proto.Field( + proto.STRING, + number=11, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message=common.CustomAttribute, + ) + tags = proto.RepeatedField( + proto.STRING, + number=13, + ) + price_info = proto.Field( + proto.MESSAGE, + number=14, + message=common.PriceInfo, + ) + rating = proto.Field( + proto.MESSAGE, + number=15, + message=common.Rating, + ) + available_time = proto.Field( + proto.MESSAGE, + number=18, + message=timestamp_pb2.Timestamp, + ) + availability = proto.Field( + proto.ENUM, + number=19, + enum=Availability, + ) + available_quantity = proto.Field( + proto.MESSAGE, + number=20, + message=wrappers_pb2.Int32Value, + ) + fulfillment_info = proto.RepeatedField( + proto.MESSAGE, + number=21, + message=common.FulfillmentInfo, + ) + uri = proto.Field( + proto.STRING, + number=22, + ) + images = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=common.Image, + ) + audience = proto.Field( + proto.MESSAGE, + number=24, + message=common.Audience, + ) + color_info = proto.Field( + proto.MESSAGE, + number=25, + message=common.ColorInfo, + ) + sizes = proto.RepeatedField( + proto.STRING, + number=26, + ) + materials = proto.RepeatedField( + proto.STRING, + number=27, + ) + patterns = proto.RepeatedField( + proto.STRING, + number=28, + ) + conditions = proto.RepeatedField( + proto.STRING, + number=29, + ) + promotions = proto.RepeatedField( + proto.MESSAGE, + number=34, + message=promotion.Promotion, + ) + publish_time = proto.Field( + proto.MESSAGE, + number=33, + message=timestamp_pb2.Timestamp, + ) + retrievable_fields = proto.Field( + proto.MESSAGE, + number=30, + message=field_mask_pb2.FieldMask, + ) + variants = proto.RepeatedField( + proto.MESSAGE, + number=31, + message='Product', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py new file mode 100644 index 00000000..ddfc08ed --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py @@ -0,0 +1,877 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'CreateProductRequest', + 'GetProductRequest', + 'UpdateProductRequest', + 'DeleteProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'SetInventoryRequest', + 'SetInventoryMetadata', + 'SetInventoryResponse', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesResponse', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesResponse', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesResponse', + }, +) + + +class CreateProductRequest(proto.Message): + r"""Request message for [CreateProduct][] method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + product (google.cloud.retail_v2alpha.types.Product): + Required. The [Product][google.cloud.retail.v2alpha.Product] + to create. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2alpha.Product], which will + become the final component of the + [Product.name][google.cloud.retail.v2alpha.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2alpha.Product]s with the + same + [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + product_id = proto.Field( + proto.STRING, + number=3, + ) + + +class GetProductRequest(proto.Message): + r"""Request message for [GetProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested + [Product][google.cloud.retail.v2alpha.Product] does not + exist, a NOT_FOUND error is returned. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateProductRequest(proto.Message): + r"""Request message for [UpdateProduct][] method. + + Attributes: + product (google.cloud.retail_v2alpha.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Product][google.cloud.retail.v2alpha.Product] to update. + The immutable and output only fields are NOT supported. If + not set, all supported fields (the fields that are neither + immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + a new [Product][google.cloud.retail.v2alpha.Product] will be + created. In this situation, ``update_mask`` is ignored. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteProductRequest(proto.Message): + r"""Request message for [DeleteProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2alpha.Product] to delete + can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] with more + than one + [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2alpha.Product] will be + deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProductsRequest(proto.Message): + r"""Request message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list products + under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2alpha.Product]s under this + branch, regardless of whether or not this branch exists, a + PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [Product][google.cloud.retail.v2alpha.Product]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 + [ListProductsResponse.next_page_token][google.cloud.retail.v2alpha.ListProductsResponse.next_page_token], + received from a previous + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + filter (str): + A filter to apply on the list results. Supported features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2alpha.ListProductsRequest.filter] + is unset. + - List + [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s sharing + the same + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]. For + example: ``primary_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2alpha.Product]s + bundled in a + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product]. For + example: ``collection_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2alpha.Product]s with + a partibular type. For example: ``type = "PRIMARY"`` + ``type = "VARIANT"`` ``type = "COLLECTION"`` + + If the field is unrecognizable, an INVALID_ARGUMENT error is + returned. + + If the specified + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] or + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product] does not + exist, a NOT_FOUND error is returned. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields of [Product][google.cloud.retail.v2alpha.Product] + to return in the responses. If not set or empty, the + following fields are returned: + + - [Product.name][google.cloud.retail.v2alpha.Product.name] + - [Product.id][google.cloud.retail.v2alpha.Product.id] + - [Product.title][google.cloud.retail.v2alpha.Product.title] + - [Product.uri][google.cloud.retail.v2alpha.Product.uri] + - [Product.images][google.cloud.retail.v2alpha.Product.images] + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.brands][google.cloud.retail.v2alpha.Product.brands] + + If "*" is provided, all fields are returned. + [Product.name][google.cloud.retail.v2alpha.Product.name] is + always returned no matter what mask is set. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + require_total_size (bool): + If true and + [page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] + is empty, + [ListProductsResponse.total_size][google.cloud.retail.v2alpha.ListProductsResponse.total_size] + is set to the total count of matched items irrespective of + pagination. + + Notice that setting this field to true affects the + performance. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + require_total_size = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListProductsResponse(proto.Message): + r"""Response message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + + Attributes: + products (Sequence[google.cloud.retail_v2alpha.types.Product]): + The [Product][google.cloud.retail.v2alpha.Product]s. + next_page_token (str): + A token that can be sent as + [ListProductsRequest.page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + total_size (int): + The total count of matched + [Product][google.cloud.retail.v2alpha.Product]s irrespective + of pagination. The total number of + [Product][google.cloud.retail.v2alpha.Product]s returned by + pagination may be less than the + [total_size][google.cloud.retail.v2alpha.ListProductsResponse.total_size] + that matches. + + This field is ignored if + [ListProductsRequest.require_total_size][google.cloud.retail.v2alpha.ListProductsRequest.require_total_size] + is not set or + [ListProductsRequest.page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] + is not empty. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + + +class SetInventoryRequest(proto.Message): + r"""Request message for [SetInventory][] method. + + Attributes: + inventory (google.cloud.retail_v2alpha.types.Product): + Required. The inventory information to update. The allowable + fields to update are: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product] named in + [Product.name][google.cloud.retail.v2alpha.Product.name], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting the + last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of fulfillment + types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear in + [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types have + empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following inventory + fields: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + + If a full overwrite of inventory information while ignoring + timestamps is needed, [UpdateProduct][] should be invoked + instead. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2alpha.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the request is issued, used to + prevent out-of-order updates on inventory fields + with the last update time recorded. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] with name + [Product.name][google.cloud.retail.v2alpha.Product.name] is + not found, the inventory update will still be processed and + retained for at most 1 day until the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + inventory = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + set_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + set_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=4, + ) + + +class SetInventoryMetadata(proto.Message): + r"""Metadata related to the progress of the SetInventory operation. + Currently empty because there is no meaningful metadata populated + from the [SetInventory][] method. + + """ + + +class SetInventoryResponse(proto.Message): + r"""Response of the SetInventoryRequest. Currently empty because there + is no meaningful response populated from the [SetInventory][] + method. + + """ + + +class AddFulfillmentPlacesRequest(proto.Message): + r"""Request message for [AddFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery" to be added for this + [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type]. + Duplicate IDs will be automatically ignored. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If the total number of place IDs exceeds 2000 for this + [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type] + after adding, then the update will be rejected. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + the fulfillment information will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + add_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class AddFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the AddFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [AddFulfillmentPlaces][] method. + + """ + + +class AddFulfillmentPlacesResponse(proto.Message): + r"""Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + + +class AddLocalInventoriesRequest(proto.Message): + r"""Request message for [AddLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + local_inventories (Sequence[google.cloud.retail_v2alpha.types.LocalInventory]): + Required. A list of inventory information at + difference places. Each place is identified by + its place ID. At most 3000 inventories are + allowed per request. + add_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided list of + [LocalInventory][google.cloud.retail.v2alpha.LocalInventory] + to update. The field is updated to the provided value. + + If a field is set while the place does not have a previous + local inventory, the local inventory at that store is + created. + + If a field is set while the value of that field is not + provided, the original field value, if it exists, is + deleted. + + If the mask is not set or set with empty paths, all + inventory fields will be updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory updates are + issued. Used to prevent out-of-order updates on + local inventory fields. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + the local inventory will still be processed and retained for + at most 1 day and processed once the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + local_inventories = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.LocalInventory, + ) + add_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + add_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=6, + ) + + +class AddLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the AddLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [AddLocalInventories][] method. + + """ + + +class AddLocalInventoriesResponse(proto.Message): + r"""Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesRequest(proto.Message): + r"""Request message for [RemoveLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + place_ids (Sequence[str]): + Required. A list of place IDs to have their + inventory deleted. At most 3000 place IDs are + allowed per request. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory deletions are + issued. Used to prevent out-of-order updates and + deletions on local inventory fields. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + the local inventory removal request will still be processed + and retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class RemoveLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesResponse(proto.Message): + r"""Response of the [RemoveLocalInventories][] API. Currently empty + because there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + + +class RemoveFulfillmentPlacesRequest(proto.Message): + r"""Request message for [RemoveFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery", to be removed for this + [type][google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type]. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + the fulfillment information will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class RemoveFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveFulfillmentPlaces][] method. + + """ + + +class RemoveFulfillmentPlacesResponse(proto.Message): + r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty + because there is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py new file mode 100644 index 00000000..bd5b8a58 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'Promotion', + }, +) + + +class Promotion(proto.Message): + r"""Promotion information. + + Attributes: + promotion_id (str): + ID of the promotion. For example, "free gift". + + The value must be a UTF-8 encoded string with a length limit + of 128 characters, and match the pattern: + ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or + ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is + returned. + + Google Merchant Center property + `promotion `__. + """ + + promotion_id = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py new file mode 100644 index 00000000..ad7ff6f6 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py @@ -0,0 +1,251 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'PurgeMetadata', + 'PurgeProductsMetadata', + 'PurgeProductsRequest', + 'PurgeProductsResponse', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + }, +) + + +class PurgeMetadata(proto.Message): + r"""Metadata related to the progress of the Purge operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + """ + + +class PurgeProductsMetadata(proto.Message): + r"""Metadata related to the progress of the PurgeProducts + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were deleted + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=3, + ) + failure_count = proto.Field( + proto.INT64, + number=4, + ) + + +class PurgeProductsRequest(proto.Message): + r"""Request message for PurgeProducts method. + + Attributes: + parent (str): + Required. The resource name of the branch under which the + products are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}/branches/${branchId}`` + filter (str): + Required. The filter string to specify the products to be + deleted with a length limit of 5,000 characters. + + Empty string filter is not allowed. "*" implies delete all + items in a branch. + + The eligible fields for filtering are: + + - ``availability``: Double quoted + [Product.availability][google.cloud.retail.v2alpha.Product.availability] + string. + - ``create_time`` : in ISO 8601 "zulu" format. + + Supported syntax: + + - Comparators (">", "<", ">=", "<=", "="). Examples: + + - create_time <= "2015-02-13T17:05:46Z" + - availability = "IN_STOCK" + + - Conjunctions ("AND") Examples: + + - create_time <= "2015-02-13T17:05:46Z" AND availability + = "PREORDER" + + - Disjunctions ("OR") Examples: + + - create_time <= "2015-02-13T17:05:46Z" OR availability + = "IN_STOCK" + + - Can support nested queries. Examples: + + - (create_time <= "2015-02-13T17:05:46Z" AND + availability = "PREORDER") OR (create_time >= + "2015-02-14T13:03:32Z" AND availability = "IN_STOCK") + + - Filter Limits: + + - Filter should not contain more than 6 conditions. + - Max nesting depth should not exceed 2 levels. + + Examples queries: + + - Delete back order products created before a timestamp. + create_time <= "2015-02-13T17:05:46Z" OR availability = + "BACKORDER". + force (bool): + Actually perform the purge. If ``force`` is set to false, + the method will return the expected purge count without + deleting any products. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeProductsResponse(proto.Message): + r"""Response of the PurgeProductsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purge_count (int): + The total count of products purged as a + result of the operation. + purge_sample (Sequence[str]): + A sample of the product names that will be deleted. Only + populated if ``force`` is set to false. A max of 100 names + will be returned and the names are chosen at random. + """ + + purge_count = proto.Field( + proto.INT64, + number=1, + ) + purge_sample = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + + Attributes: + parent (str): + Required. The resource name of the catalog under which the + events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}`` + filter (str): + Required. The filter string to specify the events to be + deleted with a length limit of 5,000 characters. Empty + string filter is not allowed. The eligible fields for + filtering are: + + - ``eventType``: Double quoted + [UserEvent.event_type][google.cloud.retail.v2alpha.UserEvent.event_type] + string. + - ``eventTime``: in ISO 8601 "zulu" format. + - ``visitorId``: Double quoted string. Specifying this will + delete all events associated with a visitor. + - ``userId``: Double quoted string. Specifying this will + delete all events associated with a user. + + Examples: + + - Deleting all events in a time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + - Deleting specific eventType in time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + - Deleting all events for a specific visitor: + ``visitorId = "visitor1024"`` + + The filtering fields are assumed to have an implicit AND. + force (bool): + Actually perform the purge. If ``force`` is set to false, + the method will return the expected purge count without + deleting any user events. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsResponse(proto.Message): + r"""Response of the PurgeUserEventsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purged_events_count (int): + The total count of events purged as a result + of the operation. + """ + + purged_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py new file mode 100644 index 00000000..e4dc0ba2 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py @@ -0,0 +1,1099 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'SearchRequest', + 'SearchResponse', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + + Attributes: + placement (str): + Required. The resource name of the search engine placement, + such as + ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` + This field is used to identify the serving configuration + name and the set of models that will be used to make the + search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + + Use "default_branch" as the branch ID or leave this field + empty, to search products under the default branch. + query (str): + Raw search query. + visitor_id (str): + Required. A unique identifier for tracking visitors. For + example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + This should be the same identifier as + [UserEvent.visitor_id][google.cloud.retail.v2alpha.UserEvent.visitor_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2alpha.types.UserInfo): + User information. + page_size (int): + Maximum number of + [Product][google.cloud.retail.v2alpha.Product]s to return. + If unspecified, defaults to a reasonable value. The maximum + allowed value is 120. Values above 120 will be coerced to + 120. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [SearchResponse.next_page_token][google.cloud.retail.v2alpha.SearchResponse.next_page_token], + received from a previous + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Product][google.cloud.retail.v2alpha.Product]s deemed by + the API as relevant) in search results. This field is only + considered if + [page_token][google.cloud.retail.v2alpha.SearchRequest.page_token] + is unset. + + If this field is negative, an INVALID_ARGUMENT is returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. Filter expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + canonical_filter (str): + The default filter that is applied when a user performs a + search without checking any filters on the search page. + + The filter applied to every search request when quality + improvement such as query expansion is needed. For example, + if a query does not have enough results, an expanded query + with + [SearchRequest.canonical_filter][google.cloud.retail.v2alpha.SearchRequest.canonical_filter] + will be returned as a supplement of the original query. This + field is strongly recommended to achieve high search + quality. + + See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for more details about filter syntax. + order_by (str): + The order in which products are returned. Products can be + ordered by a field in an + [Product][google.cloud.retail.v2alpha.Product] object. Leave + it unset if ordered by relevance. OrderBy expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + facet_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + dynamic_facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec): + Deprecated. Refer to + https://cloud.google.com/retail/docs/configs#dynamic + to enable dynamic facets. Do not set this field. + The specification for dynamically generated + facets. Notice that only textual facets can be + dynamically generated. + boost_spec (google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec): + Boost specification to boost certain products. See more + details at this `user + guide `__. + + Notice that if both + [ServingConfig.boost_control_ids][google.cloud.retail.v2alpha.ServingConfig.boost_control_ids] + and [SearchRequest.boost_spec] are set, the boost conditions + from both places are evaluated. If a search request matches + multiple boost conditions, the final boost score is equal to + the sum of the boost scores from all matched boost + conditions. + query_expansion_spec (google.cloud.retail_v2alpha.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that specifies the + conditions under which query expansion will occur. See more + details at this `user + guide `__. + relevance_threshold (google.cloud.retail_v2alpha.types.SearchRequest.RelevanceThreshold): + The relevance threshold of the search results. + + Defaults to + [RelevanceThreshold.HIGH][google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH], + which means only the most relevant results are shown, and + the least number of results are returned. See more details + at this `user + guide `__. + variant_rollup_keys (Sequence[str]): + The keys to fetch and rollup the matching + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s attributes, + [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo] + or + [LocalInventory][google.cloud.retail.v2alpha.LocalInventory]s + attributes. The attributes from all the matching + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s or + [LocalInventory][google.cloud.retail.v2alpha.LocalInventory]s + are merged and de-duplicated. Notice that rollup attributes + will lead to extra query latency. Maximum number of keys is + 30. + + For + [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], + a fulfillment type and a fulfillment ID must be provided in + the format of "fulfillmentType.fulfillmentId". E.g., in + "pickupInStore.store123", "pickupInStore" is fulfillment + type and "store123" is the store ID. + + Supported keys are: + + - colorFamilies + - price + - originalPrice + - discount + - variantId + - inventory(place_id,price) + - inventory(place_id,original_price) + - inventory(place_id,attributes.key), where key is any key + in the [Product.inventories.attributes][] map. + - attributes.key, where key is any key in the + [Product.attributes][google.cloud.retail.v2alpha.Product.attributes] + map. + - pickupInStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "pickup-in-store". + - shipToStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "ship-to-store". + - sameDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "same-day-delivery". + - nextDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "next-day-delivery". + - customFulfillment1.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-1". + - customFulfillment2.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-2". + - customFulfillment3.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-3". + - customFulfillment4.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-4". + - customFulfillment5.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-5". + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. Required for + category navigation queries to achieve good search quality. + The format should be the same as + [UserEvent.page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories]; + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + search_mode (google.cloud.retail_v2alpha.types.SearchRequest.SearchMode): + The search mode of the search request. If not + specified, a single search request triggers both + product search and faceted search. + personalization_spec (google.cloud.retail_v2alpha.types.SearchRequest.PersonalizationSpec): + The specification for personalization. + """ + class RelevanceThreshold(proto.Enum): + r"""The relevance threshold of the search results. The higher + relevance threshold is, the higher relevant results are shown + and the less number of results are returned. + """ + RELEVANCE_THRESHOLD_UNSPECIFIED = 0 + HIGH = 1 + MEDIUM = 2 + LOW = 3 + LOWEST = 4 + + class SearchMode(proto.Enum): + r"""The search mode of each search request.""" + SEARCH_MODE_UNSPECIFIED = 0 + PRODUCT_SEARCH_ONLY = 1 + FACETED_SEARCH_ONLY = 2 + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum of facet values that should be returned for this + facet. If unspecified, defaults to 20. The maximum allowed + value is 300. Values above 300 will be coerced to 300. + + If this field is negative, an INVALID_ARGUMENT is returned. + excluded_filter_keys (Sequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + For example, suppose there are 100 products with color facet + "Red" and 200 products with color facet "Blue". A query + containing the filter "colorFamilies:ANY("Red")" and have + "colorFamilies" as + [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] + will by default return the "Red" with count 100. + + If this field contains "colorFamilies", then the query + returns both the "Red" with count 100 and "Blue" with count + 200, because the "colorFamilies" key is now excluded from + the filter. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined by Google Retail Search. It will be ordered + together with dynamic facets if dynamic facets is enabled. + If set to false, the position of this facet in the response + will be the same as in the request, and it will be ranked + before the facets with dynamic position enable and all + dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response will be determined by Google Retail + Search. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enable, which will + generate a facet 'gender'. Then the final order of the + facets in the response can be ("price", "brands", "rating", + "gender") or ("price", "brands", "gender", "rating") depends + on how Google Retail Search orders "gender" and "rating" + facets. However, notice that "price" and "brands" will + always be ranked at 1st and 2nd position since their + enable_dynamic_position are false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Product][google.cloud.retail.v2alpha.Product] object, over + which the facet values are computed. Facet key is + case-sensitive. + + Allowed facet keys when + [FacetKey.query][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.query] + is not specified: + + - textual_field = + + - "brands" + - "categories" + - "genders" + - "ageGroups" + - "availability" + - "colorFamilies" + - "colors" + - "sizes" + - "materials" + - "patterns" + - "conditions" + - "attributes.key" + - "pickupInStore" + - "shipToStore" + - "sameDayDelivery" + - "nextDayDelivery" + - "customFulfillment1" + - "customFulfillment2" + - "customFulfillment3" + - "customFulfillment4" + - "customFulfillment5" + - "inventory(place_id,attributes.key)" + + - numerical_field = + + - "price" + - "discount" + - "rating" + - "ratingCount" + - "attributes.key" + - "inventory(place_id,price)" + - "inventory(place_id,original_price)" + - "inventory(place_id,attributes.key)". + intervals (Sequence[google.cloud.retail_v2alpha.types.Interval]): + Set only if values should be bucketized into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (Sequence[str]): + Only get facet for the given restricted values. For example, + when using "pickupInStore" as key and set restricted values + to ["store123", "store456"], only facets for "store123" and + "store456" are returned. Only supported on textual fields + and fulfillments. Maximum is 20. + + Must be set for the fulfillment facet keys: + + - pickupInStore + + - shipToStore + + - sameDayDelivery + + - nextDayDelivery + + - customFulfillment1 + + - customFulfillment2 + + - customFulfillment3 + + - customFulfillment4 + + - customFulfillment5 + prefixes (Sequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "categories" has three values "Women > Shoe", + "Women > Dress" and "Men > Shoe". If set + "prefixes" to "Women", the "categories" facet + will give only "Women > Shoe" and "Women > + Dress". Only supported on textual fields. + Maximum is 10. + contains (Sequence[str]): + Only get facet values that contains the given + strings. For example, suppose "categories" has + three values "Women > Shoe", "Women > Dress" and + "Men > Shoe". If set "contains" to "Shoe", the + "categories" facet will give only "Women > Shoe" + and "Men > Shoe". Only supported on textual + fields. Maximum is 10. + order_by (str): + The order in which [Facet.values][] are returned. + + Allowed values are: + + - "count desc", which means order by + [Facet.FacetValue.count][] descending. + + - "value desc", which means order by + [Facet.FacetValue.value][] descending. Only applies to + textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.intervals]; + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + are sorted in the order given by + [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.restricted_values]. + query (str): + The query that is used to compute facet for the given facet + key. When provided, it will override the default behavior of + facet computation. The query syntax is the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for detail syntax and limitations. Notice that there is no + limitation on + [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] + when query is specified. + + In the response, [FacetValue.value][] will be always "1" and + [FacetValue.count][] will be the number of results that + matches the query. + + For example, you can set a customized facet for + "shipToStore", where + [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] + is "customizedShipToStore", and + [FacetKey.query][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.query] + is "availability: ANY("IN_STOCK") AND shipToStore: + ANY("123")". Then the facet will count the products that are + both in stock and ship to store "123". + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + intervals = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes = proto.RepeatedField( + proto.STRING, + number=8, + ) + contains = proto.RepeatedField( + proto.STRING, + number=9, + ) + order_by = proto.Field( + proto.STRING, + number=4, + ) + query = proto.Field( + proto.STRING, + number=5, + ) + + facet_key = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.FacetSpec.FacetKey', + ) + limit = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position = proto.Field( + proto.BOOL, + number=4, + ) + + class DynamicFacetSpec(proto.Message): + r"""The specifications of dynamically generated facets. + + Attributes: + mode (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec.Mode): + Mode of the DynamicFacet feature. Defaults to + [Mode.DISABLED][google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec.Mode.DISABLED] + if it's unset. + """ + class Mode(proto.Enum): + r"""Enum to control DynamicFacet mode""" + MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.DynamicFacetSpec.Mode', + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain items. + + Attributes: + condition_boost_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a product + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 10. + skip_boost_spec_validation (bool): + Whether to skip boostspec validation. If this field is set + to true, invalid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] + will be ignored and valid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] + will still be applied. + + This field is a member of `oneof`_ ``_skip_boost_spec_validation``. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to products which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": + + - (id: ANY("product_1", "product_2")) AND + (colorFamilies: ANY("Red","Blue")) + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition = proto.Field( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + skip_boost_spec_validation = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.retail_v2alpha.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 3 + + condition = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.QueryExpansionSpec.Condition', + ) + pin_unexpanded_results = proto.Field( + proto.BOOL, + number=2, + ) + + class PersonalizationSpec(proto.Message): + r"""The specification for personalization. + + Attributes: + mode (google.cloud.retail_v2alpha.types.SearchRequest.PersonalizationSpec.Mode): + Defaults to + [Mode.AUTO][google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""The personalization mode of each search request.""" + MODE_UNSPECIFIED = 0 + AUTO = 1 + DISABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.PersonalizationSpec.Mode', + ) + + placement = proto.Field( + proto.STRING, + number=1, + ) + branch = proto.Field( + proto.STRING, + number=2, + ) + query = proto.Field( + proto.STRING, + number=3, + ) + visitor_id = proto.Field( + proto.STRING, + number=4, + ) + user_info = proto.Field( + proto.MESSAGE, + number=5, + message=common.UserInfo, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + offset = proto.Field( + proto.INT32, + number=9, + ) + filter = proto.Field( + proto.STRING, + number=10, + ) + canonical_filter = proto.Field( + proto.STRING, + number=28, + ) + order_by = proto.Field( + proto.STRING, + number=11, + ) + facet_specs = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=FacetSpec, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=21, + message=DynamicFacetSpec, + ) + boost_spec = proto.Field( + proto.MESSAGE, + number=13, + message=BoostSpec, + ) + query_expansion_spec = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionSpec, + ) + relevance_threshold = proto.Field( + proto.ENUM, + number=15, + enum=RelevanceThreshold, + ) + variant_rollup_keys = proto.RepeatedField( + proto.STRING, + number=17, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=23, + ) + search_mode = proto.Field( + proto.ENUM, + number=31, + enum=SearchMode, + ) + personalization_spec = proto.Field( + proto.MESSAGE, + number=32, + message=PersonalizationSpec, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + + Attributes: + results (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.SearchResult]): + A list of matched items. The order represents + the ranking. + facets (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.Facet]): + Results of facets requested by user. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.retail.v2alpha.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.retail.v2alpha.SearchResponse.total_size] + that matches. + corrected_query (str): + If spell correction applies, the corrected + query. Otherwise, empty. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs + resulting from this search, which enables accurate + attribution of search model performance. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.retail.v2alpha.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + query_expansion_info (google.cloud.retail_v2alpha.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search will be performed, and only + [redirect_uri][google.cloud.retail.v2alpha.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.retail.v2alpha.SearchResponse.attribution_token] + will be set in the response. + applied_controls (Sequence[str]): + The fully qualified resource name of applied + `controls `__. + invalid_condition_boost_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + The invalid + [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] + that are not applied during serving. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Product.id][google.cloud.retail.v2alpha.Product.id] of the + searched [Product][google.cloud.retail.v2alpha.Product]. + product (google.cloud.retail_v2alpha.types.Product): + The product data snippet in the search response. Only + [Product.name][google.cloud.retail.v2alpha.Product.name] is + guaranteed to be populated. + + [Product.variants][google.cloud.retail.v2alpha.Product.variants] + contains the product variants that match the search query. + If there are multiple product variants matching the query, + top 5 most relevant product variants are returned and + ordered by relevancy. + + If relevancy can be deternmined, use + [matching_variant_fields][google.cloud.retail.v2alpha.SearchResponse.SearchResult.matching_variant_fields] + to look up matched product variants fields. If relevancy + cannot be determined, e.g. when searching "shoe" all + products in a shoe product can be a match, 5 product + variants are returned but order is meaningless. + matching_variant_count (int): + The count of matched + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s. + matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): + If a + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] matches the + search query, this map indicates which + [Product][google.cloud.retail.v2alpha.Product] fields are + matched. The key is the + [Product.name][google.cloud.retail.v2alpha.Product.name], + the value is a field mask of the matched + [Product][google.cloud.retail.v2alpha.Product] fields. If + matched attributes cannot be determined, this map will be + empty. + + For example, a key "sku1" with field mask + "products.color_info" indicates there is a match between + "sku1" [ColorInfo][google.cloud.retail.v2alpha.ColorInfo] + and the query. + variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): + The rollup matching + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] attributes. + The key is one of the + [SearchRequest.variant_rollup_keys][google.cloud.retail.v2alpha.SearchRequest.variant_rollup_keys]. + The values are the merged and de-duplicated + [Product][google.cloud.retail.v2alpha.Product] attributes. + Notice that the rollup values are respect filter. For + example, when filtering by "colorFamilies:ANY("red")" and + rollup "colorFamilies", only "red" is returned. + + For textual and numerical attributes, the rollup values is a + list of string or double values with type + [google.protobuf.ListValue][google.protobuf.ListValue]. For + example, if there are two variants with colors "red" and + "blue", the rollup values are + + :: + + { key: "colorFamilies" + value { + list_value { + values { string_value: "red" } + values { string_value: "blue" } + } + } + } + + For + [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], + the rollup values is a double value with type + [google.protobuf.Value][google.protobuf.Value]. For example, + ``{key: "pickupInStore.store1" value { number_value: 10 }}`` + means a there are 10 variants in this product are available + in the store "store1". + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + matching_variant_count = proto.Field( + proto.INT32, + number=3, + ) + matching_variant_fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + variant_rollup_values = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. E.g., "colorFamilies" + or "price" or "attributes.attr1". + values (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Text value of a facet, such as "Black" for + facet "colorFamilies". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.retail_v2alpha.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value = proto.Field( + proto.STRING, + number=1, + oneof='facet_value', + ) + interval = proto.Field( + proto.MESSAGE, + number=2, + oneof='facet_value', + message=common.Interval, + ) + count = proto.Field( + proto.INT64, + number=3, + ) + + key = proto.Field( + proto.STRING, + number=1, + ) + values = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SearchResponse.Facet.FacetValue', + ) + dynamic_facet = proto.Field( + proto.BOOL, + number=3, + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count = proto.Field( + proto.INT64, + number=2, + ) + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + corrected_query = proto.Field( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + next_page_token = proto.Field( + proto.STRING, + number=6, + ) + query_expansion_info = proto.Field( + proto.MESSAGE, + number=7, + message=QueryExpansionInfo, + ) + redirect_uri = proto.Field( + proto.STRING, + number=10, + ) + applied_controls = proto.RepeatedField( + proto.STRING, + number=12, + ) + invalid_condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py new file mode 100644 index 00000000..c8c3ccca --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py @@ -0,0 +1,309 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'ServingConfig', + }, +) + + +class ServingConfig(proto.Message): + r"""Configures metadata that is used to generate serving time results + (e.g. search results or recommendation predictions). The + ServingConfig is passed in the search and predict request and + together with the Catalog.default_branch, generates results. + + Attributes: + name (str): + Immutable. Fully qualified name + projects/\ */locations/global/catalogs/*/servingConfig/\* + display_name (str): + Required. The human readable serving config display name. + Used in Retail UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + model_id (str): + The id of the model to use at serving time. Currently only + RecommendationModels are supported: + https://cloud.google.com/retail/recommendations-ai/docs/create-models + Can be changed but only to a compatible model (e.g. + others-you-may-like CTR to others-you-may-like CVR). + + Required when + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + price_reranking_level (str): + How much price ranking we want in serving results. Price + reranking causes product items with a similar recommendation + probability to be ordered by price, with the highest-priced + items first. This setting could result in a decrease in + click-through and conversion rates. Allowed values are: + + - 'no-price-reranking' + - 'low-price-raranking' + - 'medium-price-reranking' + - 'high-price-reranking' + + If not specified, we choose default based on model type. + Default value: 'no-price-reranking'. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + facet_control_ids (Sequence[str]): + Facet specifications for faceted search. If empty, no facets + are returned. The ids refer to the ids of + [Control][google.cloud.retail.v2alpha.Control] resources + with only the Facet control set. These controls are assumed + to be in the same + [Catalog][google.cloud.retail.v2alpha.Catalog] as the + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]. + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + dynamic_facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec): + The specification for dynamically generated facets. Notice + that only textual facets can be dynamically generated. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + boost_control_ids (Sequence[str]): + Condition boost specifications. If a product matches + multiple conditions in the specifications, boost scores from + these specifications are all applied and combined in a + non-linear way. Maximum number of specifications is 100. + + Notice that if both + [ServingConfig.boost_control_ids][google.cloud.retail.v2alpha.ServingConfig.boost_control_ids] + and [SearchRequest.boost_spec] are set, the boost conditions + from both places are evaluated. If a search request matches + multiple boost conditions, the final boost score is equal to + the sum of the boost scores from all matched boost + conditions. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + filter_control_ids (Sequence[str]): + Condition filter specifications. If a product matches + multiple conditions in the specifications, filters from + these specifications are all applied and combined via the + AND operator. Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + redirect_control_ids (Sequence[str]): + Condition redirect specifications. Only the first triggered + redirect action is applied, even if multiple apply. Maximum + number of specifications is 1000. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + twoway_synonyms_control_ids (Sequence[str]): + Condition synonyms specifications. If multiple syonyms + conditions match, all matching synonyms control in the list + will execute. Order of controls in the list will not matter. + Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + oneway_synonyms_control_ids (Sequence[str]): + Condition oneway synonyms specifications. If multiple oneway + synonyms conditions match, all matching oneway synonyms + controls in the list will execute. Order of controls in the + list will not matter. Maximum number of specifications is + 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + do_not_associate_control_ids (Sequence[str]): + Condition do not associate specifications. If multiple do + not associate conditions match, all matching do not + associate controls in the list will execute. + + - Order does not matter. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + replacement_control_ids (Sequence[str]): + Condition replacement specifications. + + - Applied according to the order in the list. + - A previously replaced term can not be re-replaced. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + ignore_control_ids (Sequence[str]): + Condition ignore specifications. If multiple ignore + conditions match, all matching ignore controls in the list + will execute. + + - Order does not matter. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + diversity_level (str): + How much diversity to use in recommendation model results + e.g. 'medium-diversity' or 'high-diversity'. Currently + supported values: + + - 'no-diversity' + - 'low-diversity' + - 'medium-diversity' + - 'high-diversity' + - 'auto-diversity' + + If not specified, we choose default based on recommendation + model type. Default value: 'no-diversity'. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + enable_category_filter_level (str): + Whether to add additional category filters on the + 'similar-items' model. If not specified, we enable it by + default. Allowed values are: + + - 'no-category-match': No additional filtering of original + results from the model and the customer's filters. + - 'relaxed-category-match': Only keep results with + categories that match at least one item categories in the + PredictRequests's context item. + + - If customer also sends filters in the PredictRequest, + then the results will satisfy both conditions (user + given and category match). + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + solution_types (Sequence[google.cloud.retail_v2alpha.types.SolutionType]): + Required. Immutable. Specifies the solution + types that a serving config can be associated + with. Currently we support setting only one type + of solution. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + model_id = proto.Field( + proto.STRING, + number=3, + ) + price_reranking_level = proto.Field( + proto.STRING, + number=4, + ) + facet_control_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=6, + message=search_service.SearchRequest.DynamicFacetSpec, + ) + boost_control_ids = proto.RepeatedField( + proto.STRING, + number=7, + ) + filter_control_ids = proto.RepeatedField( + proto.STRING, + number=9, + ) + redirect_control_ids = proto.RepeatedField( + proto.STRING, + number=10, + ) + twoway_synonyms_control_ids = proto.RepeatedField( + proto.STRING, + number=18, + ) + oneway_synonyms_control_ids = proto.RepeatedField( + proto.STRING, + number=12, + ) + do_not_associate_control_ids = proto.RepeatedField( + proto.STRING, + number=13, + ) + replacement_control_ids = proto.RepeatedField( + proto.STRING, + number=14, + ) + ignore_control_ids = proto.RepeatedField( + proto.STRING, + number=15, + ) + diversity_level = proto.Field( + proto.STRING, + number=8, + ) + enable_category_filter_level = proto.Field( + proto.STRING, + number=16, + ) + solution_types = proto.RepeatedField( + proto.ENUM, + number=19, + enum=common.SolutionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py new file mode 100644 index 00000000..635f42bb --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py @@ -0,0 +1,234 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'CreateServingConfigRequest', + 'UpdateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'AddControlRequest', + 'RemoveControlRequest', + }, +) + + +class CreateServingConfigRequest(proto.Message): + r"""Request for CreateServingConfig method. + + Attributes: + parent (str): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + serving_config (google.cloud.retail_v2alpha.types.ServingConfig): + Required. The ServingConfig to create. + serving_config_id (str): + Required. The ID to use for the ServingConfig, which will + become the final component of the ServingConfig's resource + name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-_/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + serving_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_serving_config.ServingConfig, + ) + serving_config_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateServingConfigRequest(proto.Message): + r"""Request for UpdateServingConfig method. + + Attributes: + serving_config (google.cloud.retail_v2alpha.types.ServingConfig): + Required. The ServingConfig to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] + + If not set, all supported fields are updated. + """ + + serving_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_serving_config.ServingConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteServingConfigRequest(proto.Message): + r"""Request for DeleteServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetServingConfigRequest(proto.Message): + r"""Request for GetServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListServingConfigsRequest(proto.Message): + r"""Request for ListServingConfigs method. + + Attributes: + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 100. If a + value greater than 100 is provided, at most 100 + results are returned. + page_token (str): + Optional. A page token, received from a previous + ``ListServingConfigs`` call. Provide this to retrieve the + subsequent page. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServingConfigsResponse(proto.Message): + r"""Response for ListServingConfigs method. + + Attributes: + serving_configs (Sequence[google.cloud.retail_v2alpha.types.ServingConfig]): + All the ServingConfigs for a given catalog. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + serving_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_serving_config.ServingConfig, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class AddControlRequest(proto.Message): + r"""Request for AddControl method. + + Attributes: + serving_config (str): + Required. The source ServingConfig resource name . Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + control_id (str): + Required. The id of the control to apply. Assumed to be in + the same catalog as the serving config - if id is not found + a NOT_FOUND error is returned. + """ + + serving_config = proto.Field( + proto.STRING, + number=1, + ) + control_id = proto.Field( + proto.STRING, + number=2, + ) + + +class RemoveControlRequest(proto.Message): + r"""Request for RemoveControl method. + + Attributes: + serving_config (str): + Required. The source ServingConfig resource name . Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + control_id (str): + Required. The id of the control to apply. + Assumed to be in the same catalog as the serving + config. + """ + + serving_config = proto.Field( + proto.STRING, + number=1, + ) + control_id = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py new file mode 100644 index 00000000..f9d6a684 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py @@ -0,0 +1,507 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'UserEvent', + 'ProductDetail', + 'CompletionDetail', + 'PurchaseTransaction', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Retail API needs + to know about how end users interact with customers' website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + - ``add-to-cart``: Products being added to cart. + - ``category-page-view``: Special pages such as sale or + promotion pages viewed. + - ``detail-page-view``: Products detail page viewed. + - ``home-page-view``: Homepage viewed. + - ``promotion-offered``: Promotion is offered to a user. + - ``promotion-not-offered``: Promotion is not offered to a + user. + - ``purchase-complete``: User finishing a purchase. + - ``search``: Product search. + - ``shopping-cart-page-view``: User viewing a shopping + cart. + visitor_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + The field should not contain PII or user-data. We recommend + to use Google Analystics `Client + ID `__ + for this field. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the sesion_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add visitor_id as prefix. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.retail.v2alpha.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + experiment_ids (Sequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups + (e.g. using Retail API, using different + recommendation models). + attribution_token (str): + Highly recommended for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2alpha.PredictionService.Predict]. + This field enables accurate attribution of recommendation + model performance. + + The value must be a valid + [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] + for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2alpha.PredictionService.Predict]. + The value must be a valid + [SearchResponse.attribution_token][google.cloud.retail.v2alpha.SearchResponse.attribution_token] + for user events that are the result of + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + This token enables us to accurately attribute page view or + purchase back to the event and the particular predict + response containing this clicked/purchased product. If user + clicks on product K in the recommendation results, pass + [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] + as a URL parameter to product K's page. When recording + events on product K's page, log the + [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] + to this field. + product_details (Sequence[google.cloud.retail_v2alpha.types.ProductDetail]): + The main product details related to the event. + + This field is required for the following event types: + + - ``add-to-cart`` + - ``detail-page-view`` + - ``purchase-complete`` + - ``search`` + + In a ``search`` event, this field represents the products + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [product_details][google.cloud.retail.v2alpha.UserEvent.product_details] + is desired. The end user may have not finished browsing the + whole page yet. + completion_detail (google.cloud.retail_v2alpha.types.CompletionDetail): + The main auto-completion details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Retail API use those + custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - The key must be a UTF-8 encoded string with a length + limit of 5,000 characters. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a UTF-8 + encoded string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is traffic_channel, which is how a user arrives + at the site. Users can arrive at the site by coming to the + site directly, coming through Google search, or in other + ways. + cart_id (str): + The ID or name of the associated shopping cart. This ID is + used to associate multiple items added or present in the + cart before purchase. + + This can only be set for ``add-to-cart``, + ``purchase-complete``, or ``shopping-cart-page-view`` + events. + purchase_transaction (google.cloud.retail_v2alpha.types.PurchaseTransaction): + A transaction represents the entire purchase transaction. + + Required for ``purchase-complete`` events. Other event types + should not set this field. Otherwise, an INVALID_ARGUMENT + error is returned. + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.retail.v2alpha.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + At least one of + [search_query][google.cloud.retail.v2alpha.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. + + See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + order_by (str): + The order in which products are returned. + + See + [SearchRequest.order_by][google.cloud.retail.v2alpha.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.retail.v2alpha.SearchRequest.offset] + for definition. + + If this field is negative, an INVALID_ARGUMENT is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + + Required for ``category-page-view`` events. At least one of + [search_query][google.cloud.retail.v2alpha.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2alpha.types.UserInfo): + User information. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. + page_view_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageViewId`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + """ + + event_type = proto.Field( + proto.STRING, + number=1, + ) + visitor_id = proto.Field( + proto.STRING, + number=2, + ) + session_id = proto.Field( + proto.STRING, + number=21, + ) + event_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + experiment_ids = proto.RepeatedField( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + product_details = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ProductDetail', + ) + completion_detail = proto.Field( + proto.MESSAGE, + number=22, + message='CompletionDetail', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=common.CustomAttribute, + ) + cart_id = proto.Field( + proto.STRING, + number=8, + ) + purchase_transaction = proto.Field( + proto.MESSAGE, + number=9, + message='PurchaseTransaction', + ) + search_query = proto.Field( + proto.STRING, + number=10, + ) + filter = proto.Field( + proto.STRING, + number=16, + ) + order_by = proto.Field( + proto.STRING, + number=17, + ) + offset = proto.Field( + proto.INT32, + number=18, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=11, + ) + user_info = proto.Field( + proto.MESSAGE, + number=12, + message=common.UserInfo, + ) + uri = proto.Field( + proto.STRING, + number=13, + ) + referrer_uri = proto.Field( + proto.STRING, + number=14, + ) + page_view_id = proto.Field( + proto.STRING, + number=15, + ) + + +class ProductDetail(proto.Message): + r"""Detailed product information associated with a user event. + + Attributes: + product (google.cloud.retail_v2alpha.types.Product): + Required. [Product][google.cloud.retail.v2alpha.Product] + information. + + Required field(s): + + - [Product.id][google.cloud.retail.v2alpha.Product.id] + + Optional override field(s): + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + + If any supported optional fields are provided, we will treat + them as a full override when looking up product information + from the catalog. Thus, it is important to ensure that the + overriding fields are accurate and complete. + + All other product fields are ignored and instead populated + via catalog lookup after event ingestion. + quantity (google.protobuf.wrappers_pb2.Int32Value): + Quantity of the product associated with the user event. + + For example, this field will be 2 if two products are added + to the shopping cart for ``purchase-complete`` event. + Required for ``add-to-cart`` and ``purchase-complete`` event + types. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + quantity = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +class CompletionDetail(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + completion_attribution_token (str): + Completion attribution token in + [CompleteQueryResponse.attribution_token][google.cloud.retail.v2alpha.CompleteQueryResponse.attribution_token]. + selected_suggestion (str): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2alpha.CompleteQueryResponse.CompletionResult.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2alpha.CompleteQueryResponse.CompletionResult.suggestion] + position, starting from 0. + """ + + completion_attribution_token = proto.Field( + proto.STRING, + number=1, + ) + selected_suggestion = proto.Field( + proto.STRING, + number=2, + ) + selected_position = proto.Field( + proto.INT32, + number=3, + ) + + +class PurchaseTransaction(proto.Message): + r"""A transaction represents the entire purchase transaction. + + Attributes: + id (str): + The transaction ID with a length limit of 128 + characters. + revenue (float): + Required. Total non-zero revenue or grand + total associated with the transaction. This + value include shipping, tax, or other + adjustments to total revenue that you want to + include as part of your revenue calculations. + tax (float): + All the taxes associated with the + transaction. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [revenue][google.cloud.retail.v2alpha.PurchaseTransaction.revenue] + - + [tax][google.cloud.retail.v2alpha.PurchaseTransaction.tax] + - + [cost][google.cloud.retail.v2alpha.PurchaseTransaction.cost] + currency_code (str): + Required. Currency code. Use three-character + ISO-4217 code. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + revenue = proto.Field( + proto.FLOAT, + number=2, + ) + tax = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + currency_code = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py new file mode 100644 index 00000000..0e679b22 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import user_event as gcr_user_event + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'WriteUserEventRequest', + 'CollectUserEventRequest', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'RejoinUserEventsMetadata', + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (google.cloud.retail_v2alpha.types.UserEvent): + Required. User event to write. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for 3rd party requests. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.STRING, + number=2, + ) + uri = proto.Field( + proto.STRING, + number=3, + ) + ets = proto.Field( + proto.INT64, + number=4, + ) + + +class RejoinUserEventsRequest(proto.Message): + r"""Request message for RejoinUserEvents method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event_rejoin_scope (google.cloud.retail_v2alpha.types.RejoinUserEventsRequest.UserEventRejoinScope): + The type of the user event rejoin to define the scope and + range of the user events to be rejoined with the latest + product catalog. Defaults to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not + set, or set to an invalid integer value. + """ + class UserEventRejoinScope(proto.Enum): + r"""The scope of user events to be rejoined with the latest product + catalog. If the rejoining aims at reducing number of unjoined + events, set UserEventRejoinScope to UNJOINED_EVENTS. If the + rejoining aims at correcting product catalog information in joined + events, set UserEventRejoinScope to JOINED_EVENTS. If all events + needs to be rejoined, set UserEventRejoinScope to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. + """ + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 + JOINED_EVENTS = 1 + UNJOINED_EVENTS = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event_rejoin_scope = proto.Field( + proto.ENUM, + number=2, + enum=UserEventRejoinScope, + ) + + +class RejoinUserEventsResponse(proto.Message): + r"""Response message for RejoinUserEvents method. + + Attributes: + rejoined_user_events_count (int): + Number of user events that were joined with + latest product catalog. + """ + + rejoined_user_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +class RejoinUserEventsMetadata(proto.Message): + r"""Metadata for RejoinUserEvents method. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/mypy.ini b/owl-bot-staging/v2alpha/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v2alpha/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2alpha/noxfile.py b/owl-bot-staging/v2alpha/noxfile.py new file mode 100644 index 00000000..9f7eeaa1 --- /dev/null +++ b/owl-bot-staging/v2alpha/noxfile.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.6", + "3.7", + "3.8", + "3.9", + "3.10", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==19.10b0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.9" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/retail_v2alpha/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py new file mode 100644 index 00000000..9b5622c2 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async] +from google.cloud import retail_v2alpha + + +async def sample_add_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py new file mode 100644 index 00000000..ec76bc9f --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync] +from google.cloud import retail_v2alpha + + +def sample_add_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py new file mode 100644 index 00000000..d2f66638 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetAttributesConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_get_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetAttributesConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py new file mode 100644 index 00000000..91c914b3 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_get_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py new file mode 100644 index 00000000..9da8e840 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetCompletionConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_get_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetCompletionConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py new file mode 100644 index 00000000..5da5cd9f --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_get_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py new file mode 100644 index 00000000..2134a810 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetDefaultBranch_async] +from google.cloud import retail_v2alpha + + +async def sample_get_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py new file mode 100644 index 00000000..d233b424 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync] +from google.cloud import retail_v2alpha + + +def sample_get_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py new file mode 100644 index 00000000..7e7fbf33 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_ListCatalogs_async] +from google.cloud import retail_v2alpha + + +async def sample_list_catalogs(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py new file mode 100644 index 00000000..8165c25b --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_ListCatalogs_sync] +from google.cloud import retail_v2alpha + + +def sample_list_catalogs(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py new file mode 100644 index 00000000..f79bd768 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async] +from google.cloud import retail_v2alpha + + +async def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = await client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py new file mode 100644 index 00000000..35b6611c --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync] +from google.cloud import retail_v2alpha + + +def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py new file mode 100644 index 00000000..c42a8bb1 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReplaceCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async] +from google.cloud import retail_v2alpha + + +async def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py new file mode 100644 index 00000000..56e779ab --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReplaceCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync] +from google.cloud import retail_v2alpha + + +def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py new file mode 100644 index 00000000..9ddf2f8e --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_SetDefaultBranch_async] +from google.cloud import retail_v2alpha + + +async def sample_set_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + +# [END retail_v2alpha_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py new file mode 100644 index 00000000..6fa13ce6 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync] +from google.cloud import retail_v2alpha + + +def sample_set_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + +# [END retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py new file mode 100644 index 00000000..c4654be4 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_update_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + attributes_config = retail_v2alpha.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2alpha.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = await client.update_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py new file mode 100644 index 00000000..1f4d3432 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_update_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + attributes_config = retail_v2alpha.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2alpha.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = client.update_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py new file mode 100644 index 00000000..6035f718 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateCatalog_async] +from google.cloud import retail_v2alpha + + +async def sample_update_catalog(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2alpha.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2alpha.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py new file mode 100644 index 00000000..35fff0d1 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateCatalog_sync] +from google.cloud import retail_v2alpha + + +def sample_update_catalog(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2alpha.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2alpha.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py new file mode 100644 index 00000000..26cac134 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_update_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + completion_config = retail_v2alpha.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2alpha.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = await client.update_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py new file mode 100644 index 00000000..b9e11448 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_update_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + completion_config = retail_v2alpha.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2alpha.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = client.update_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py new file mode 100644 index 00000000..13dce99f --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CompletionService_CompleteQuery_async] +from google.cloud import retail_v2alpha + + +async def sample_complete_query(): + # Create a client + client = retail_v2alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py new file mode 100644 index 00000000..20687e33 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CompletionService_CompleteQuery_sync] +from google.cloud import retail_v2alpha + + +def sample_complete_query(): + # Create a client + client = retail_v2alpha.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py new file mode 100644 index 00000000..d1a515f2 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CompletionService_ImportCompletionData_async] +from google.cloud import retail_v2alpha + + +async def sample_import_completion_data(): + # Create a client + client = retail_v2alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2alpha.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py new file mode 100644 index 00000000..3c6ddc55 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CompletionService_ImportCompletionData_sync] +from google.cloud import retail_v2alpha + + +def sample_import_completion_data(): + # Create a client + client = retail_v2alpha.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2alpha.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py new file mode 100644 index 00000000..131de87e --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_CreateControl_async] +from google.cloud import retail_v2alpha + + +async def sample_create_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = await client.create_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_CreateControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py new file mode 100644 index 00000000..8fee66d8 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_CreateControl_sync] +from google.cloud import retail_v2alpha + + +def sample_create_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = client.create_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_CreateControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py new file mode 100644 index 00000000..ae438a78 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_DeleteControl_async] +from google.cloud import retail_v2alpha + + +async def sample_delete_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteControlRequest( + name="name_value", + ) + + # Make the request + await client.delete_control(request=request) + + +# [END retail_v2alpha_generated_ControlService_DeleteControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py new file mode 100644 index 00000000..b83ddcd5 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_DeleteControl_sync] +from google.cloud import retail_v2alpha + + +def sample_delete_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteControlRequest( + name="name_value", + ) + + # Make the request + client.delete_control(request=request) + + +# [END retail_v2alpha_generated_ControlService_DeleteControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py new file mode 100644 index 00000000..588c8955 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_GetControl_async] +from google.cloud import retail_v2alpha + + +async def sample_get_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetControlRequest( + name="name_value", + ) + + # Make the request + response = await client.get_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_GetControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py new file mode 100644 index 00000000..f04eb36b --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_GetControl_sync] +from google.cloud import retail_v2alpha + + +def sample_get_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetControlRequest( + name="name_value", + ) + + # Make the request + response = client.get_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_GetControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py new file mode 100644 index 00000000..005329c1 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListControls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_ListControls_async] +from google.cloud import retail_v2alpha + + +async def sample_list_controls(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ControlService_ListControls_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py new file mode 100644 index 00000000..301c6036 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListControls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_ListControls_sync] +from google.cloud import retail_v2alpha + + +def sample_list_controls(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ControlService_ListControls_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py new file mode 100644 index 00000000..dc422066 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_UpdateControl_async] +from google.cloud import retail_v2alpha + + +async def sample_update_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.UpdateControlRequest( + control=control, + ) + + # Make the request + response = await client.update_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_UpdateControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py new file mode 100644 index 00000000..cf7823fd --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_UpdateControl_sync] +from google.cloud import retail_v2alpha + + +def sample_update_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.UpdateControlRequest( + control=control, + ) + + # Make the request + response = client.update_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_UpdateControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py new file mode 100644 index 00000000..7d3c4540 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_PredictionService_Predict_async] +from google.cloud import retail_v2alpha + + +async def sample_predict(): + # Create a client + client = retail_v2alpha.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py new file mode 100644 index 00000000..c3dbd187 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_PredictionService_Predict_sync] +from google.cloud import retail_v2alpha + + +def sample_predict(): + # Create a client + client = retail_v2alpha.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py new file mode 100644 index 00000000..4ef15987 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async] +from google.cloud import retail_v2alpha + + +async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py new file mode 100644 index 00000000..03f0cd6d --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync] +from google.cloud import retail_v2alpha + + +def sample_add_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py new file mode 100644 index 00000000..c3b7dfdf --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_AddLocalInventories_async] +from google.cloud import retail_v2alpha + + +async def sample_add_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py new file mode 100644 index 00000000..b91b57f3 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_AddLocalInventories_sync] +from google.cloud import retail_v2alpha + + +def sample_add_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py new file mode 100644 index 00000000..8ca45663 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_CreateProduct_async] +from google.cloud import retail_v2alpha + + +async def sample_create_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py new file mode 100644 index 00000000..b2946508 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_CreateProduct_sync] +from google.cloud import retail_v2alpha + + +def sample_create_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py new file mode 100644 index 00000000..1ae74222 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_DeleteProduct_async] +from google.cloud import retail_v2alpha + + +async def sample_delete_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + +# [END retail_v2alpha_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py new file mode 100644 index 00000000..faebc2e4 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_DeleteProduct_sync] +from google.cloud import retail_v2alpha + + +def sample_delete_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + +# [END retail_v2alpha_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py new file mode 100644 index 00000000..70903b9e --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_GetProduct_async] +from google.cloud import retail_v2alpha + + +async def sample_get_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py new file mode 100644 index 00000000..25fccda2 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_GetProduct_sync] +from google.cloud import retail_v2alpha + + +def sample_get_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py new file mode 100644 index 00000000..5cfaf031 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_ImportProducts_async] +from google.cloud import retail_v2alpha + + +async def sample_import_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2alpha.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py new file mode 100644 index 00000000..ca54ea57 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_ImportProducts_sync] +from google.cloud import retail_v2alpha + + +def sample_import_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2alpha.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py new file mode 100644 index 00000000..8dcf7a71 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_ListProducts_async] +from google.cloud import retail_v2alpha + + +async def sample_list_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py new file mode 100644 index 00000000..aa96e9c2 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_ListProducts_sync] +from google.cloud import retail_v2alpha + + +def sample_list_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py new file mode 100644 index 00000000..8adf6af4 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_PurgeProducts_async] +from google.cloud import retail_v2alpha + + +async def sample_purge_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeProductsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_PurgeProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py new file mode 100644 index 00000000..72c32c88 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_PurgeProducts_sync] +from google.cloud import retail_v2alpha + + +def sample_purge_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeProductsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_PurgeProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py new file mode 100644 index 00000000..da379da0 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async] +from google.cloud import retail_v2alpha + + +async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py new file mode 100644 index 00000000..55bf6522 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync] +from google.cloud import retail_v2alpha + + +def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py new file mode 100644 index 00000000..bc0b9406 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_RemoveLocalInventories_async] +from google.cloud import retail_v2alpha + + +async def sample_remove_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py new file mode 100644 index 00000000..40e0b2bb --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync] +from google.cloud import retail_v2alpha + + +def sample_remove_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py new file mode 100644 index 00000000..64dc769c --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_SetInventory_async] +from google.cloud import retail_v2alpha + + +async def sample_set_inventory(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2alpha.Product() + inventory.title = "title_value" + + request = retail_v2alpha.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py new file mode 100644 index 00000000..9dbf88b6 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_SetInventory_sync] +from google.cloud import retail_v2alpha + + +def sample_set_inventory(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2alpha.Product() + inventory.title = "title_value" + + request = retail_v2alpha.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py new file mode 100644 index 00000000..35df5c2b --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_UpdateProduct_async] +from google.cloud import retail_v2alpha + + +async def sample_update_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py new file mode 100644 index 00000000..6248e977 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_UpdateProduct_sync] +from google.cloud import retail_v2alpha + + +def sample_update_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py new file mode 100644 index 00000000..75520b76 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_SearchService_Search_async] +from google.cloud import retail_v2alpha + + +async def sample_search(): + # Create a client + client = retail_v2alpha.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py new file mode 100644 index 00000000..2b2853a3 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_SearchService_Search_sync] +from google.cloud import retail_v2alpha + + +def sample_search(): + # Create a client + client = retail_v2alpha.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py new file mode 100644 index 00000000..0694590c --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_AddControl_async] +from google.cloud import retail_v2alpha + + +async def sample_add_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.add_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_AddControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py new file mode 100644 index 00000000..10d50ff7 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_AddControl_sync] +from google.cloud import retail_v2alpha + + +def sample_add_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.add_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_AddControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py new file mode 100644 index 00000000..33b080fc --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_create_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = await client.create_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py new file mode 100644 index 00000000..e7b0e80e --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_create_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = client.create_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py new file mode 100644 index 00000000..f8259bdf --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_delete_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_serving_config(request=request) + + +# [END retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py new file mode 100644 index 00000000..621916ef --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_delete_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_serving_config(request=request) + + +# [END retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py new file mode 100644 index 00000000..fdfd4d80 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_GetServingConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_get_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_GetServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py new file mode 100644 index 00000000..a1408016 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_get_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py new file mode 100644 index 00000000..c8244f95 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServingConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async] +from google.cloud import retail_v2alpha + + +async def sample_list_serving_configs(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py new file mode 100644 index 00000000..86e02687 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServingConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync] +from google.cloud import retail_v2alpha + + +def sample_list_serving_configs(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py new file mode 100644 index 00000000..66e07902 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_RemoveControl_async] +from google.cloud import retail_v2alpha + + +async def sample_remove_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.remove_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_RemoveControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py new file mode 100644 index 00000000..8b39362b --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_RemoveControl_sync] +from google.cloud import retail_v2alpha + + +def sample_remove_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.remove_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_RemoveControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py new file mode 100644 index 00000000..64e82dba --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_update_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = await client.update_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py new file mode 100644 index 00000000..46d2d65c --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_update_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = client.update_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 00000000..f8aa3f78 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_CollectUserEvent_async] +from google.cloud import retail_v2alpha + + +async def sample_collect_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 00000000..026972b1 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_CollectUserEvent_sync] +from google.cloud import retail_v2alpha + + +def sample_collect_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py new file mode 100644 index 00000000..540ce130 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_ImportUserEvents_async] +from google.cloud import retail_v2alpha + + +async def sample_import_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2alpha.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 00000000..fe9310db --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_ImportUserEvents_sync] +from google.cloud import retail_v2alpha + + +def sample_import_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2alpha.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py new file mode 100644 index 00000000..17d5c66d --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_PurgeUserEvents_async] +from google.cloud import retail_v2alpha + + +async def sample_purge_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py new file mode 100644 index 00000000..d8b2ae83 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync] +from google.cloud import retail_v2alpha + + +def sample_purge_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py new file mode 100644 index 00000000..d38bb5f4 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_RejoinUserEvents_async] +from google.cloud import retail_v2alpha + + +async def sample_rejoin_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py new file mode 100644 index 00000000..f88f6437 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync] +from google.cloud import retail_v2alpha + + +def sample_rejoin_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py new file mode 100644 index 00000000..2dda0e65 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_WriteUserEvent_async] +from google.cloud import retail_v2alpha + + +async def sample_write_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 00000000..a121bdbd --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_WriteUserEvent_sync] +from google.cloud import retail_v2alpha + + +def sample_write_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json b/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json new file mode 100644 index 00000000..ea2cf419 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json @@ -0,0 +1,7066 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.retail.v2alpha", + "version": "v2alpha" + } + ], + "language": "PYTHON", + "name": "google-cloud-retail" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.add_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "AddCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "add_catalog_attribute" + }, + "description": "Sample for AddCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.add_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "AddCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "add_catalog_attribute" + }, + "description": "Sample for AddCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetAttributesConfigRequest" + }, + { + "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.retail_v2alpha.types.AttributesConfig", + "shortName": "get_attributes_config" + }, + "description": "Sample for GetAttributesConfig", + "file": "retail_v2alpha_generated_catalog_service_get_attributes_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetAttributesConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_attributes_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetAttributesConfigRequest" + }, + { + "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.retail_v2alpha.types.AttributesConfig", + "shortName": "get_attributes_config" + }, + "description": "Sample for GetAttributesConfig", + "file": "retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_completion_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetCompletionConfigRequest" + }, + { + "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.retail_v2alpha.types.CompletionConfig", + "shortName": "get_completion_config" + }, + "description": "Sample for GetCompletionConfig", + "file": "retail_v2alpha_generated_catalog_service_get_completion_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetCompletionConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_completion_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_completion_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetCompletionConfigRequest" + }, + { + "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.retail_v2alpha.types.CompletionConfig", + "shortName": "get_completion_config" + }, + "description": "Sample for GetCompletionConfig", + "file": "retail_v2alpha_generated_catalog_service_get_completion_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_completion_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2alpha_generated_catalog_service_get_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetDefaultBranch_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2alpha_generated_catalog_service_get_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListCatalogsRequest" + }, + { + "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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsAsyncPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2alpha_generated_catalog_service_list_catalogs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_ListCatalogs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_list_catalogs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListCatalogsRequest" + }, + { + "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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2alpha_generated_catalog_service_list_catalogs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_ListCatalogs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_list_catalogs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.remove_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "RemoveCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "remove_catalog_attribute" + }, + "description": "Sample for RemoveCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.remove_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "RemoveCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "remove_catalog_attribute" + }, + "description": "Sample for RemoveCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.replace_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ReplaceCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "replace_catalog_attribute" + }, + "description": "Sample for ReplaceCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.replace_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ReplaceCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "replace_catalog_attribute" + }, + "description": "Sample for ReplaceCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2alpha_generated_catalog_service_set_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_SetDefaultBranch_async", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_set_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2alpha_generated_catalog_service_set_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_set_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest" + }, + { + "name": "attributes_config", + "type": "google.cloud.retail_v2alpha.types.AttributesConfig" + }, + { + "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.retail_v2alpha.types.AttributesConfig", + "shortName": "update_attributes_config" + }, + "description": "Sample for UpdateAttributesConfig", + "file": "retail_v2alpha_generated_catalog_service_update_attributes_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_attributes_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest" + }, + { + "name": "attributes_config", + "type": "google.cloud.retail_v2alpha.types.AttributesConfig" + }, + { + "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.retail_v2alpha.types.AttributesConfig", + "shortName": "update_attributes_config" + }, + "description": "Sample for UpdateAttributesConfig", + "file": "retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2alpha.types.Catalog" + }, + { + "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.retail_v2alpha.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2alpha_generated_catalog_service_update_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCatalog_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2alpha.types.Catalog" + }, + { + "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.retail_v2alpha.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2alpha_generated_catalog_service_update_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCatalog_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_completion_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest" + }, + { + "name": "completion_config", + "type": "google.cloud.retail_v2alpha.types.CompletionConfig" + }, + { + "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.retail_v2alpha.types.CompletionConfig", + "shortName": "update_completion_config" + }, + "description": "Sample for UpdateCompletionConfig", + "file": "retail_v2alpha_generated_catalog_service_update_completion_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_completion_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_completion_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest" + }, + { + "name": "completion_config", + "type": "google.cloud.retail_v2alpha.types.CompletionConfig" + }, + { + "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.retail_v2alpha.types.CompletionConfig", + "shortName": "update_completion_config" + }, + "description": "Sample for UpdateCompletionConfig", + "file": "retail_v2alpha_generated_catalog_service_update_completion_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_completion_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2alpha.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2alpha_generated_completion_service_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CompletionService_CompleteQuery_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_completion_service_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2alpha.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2alpha_generated_completion_service_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CompletionService_CompleteQuery_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_completion_service_complete_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2alpha.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2alpha_generated_completion_service_import_completion_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CompletionService_ImportCompletionData_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_completion_service_import_completion_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2alpha.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2alpha_generated_completion_service_import_completion_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CompletionService_ImportCompletionData_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_completion_service_import_completion_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.create_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.CreateControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "CreateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateControlRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "control", + "type": "google.cloud.retail_v2alpha.types.Control" + }, + { + "name": "control_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.retail_v2alpha.types.Control", + "shortName": "create_control" + }, + "description": "Sample for CreateControl", + "file": "retail_v2alpha_generated_control_service_create_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_CreateControl_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_create_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.create_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.CreateControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "CreateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateControlRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "control", + "type": "google.cloud.retail_v2alpha.types.Control" + }, + { + "name": "control_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.retail_v2alpha.types.Control", + "shortName": "create_control" + }, + "description": "Sample for CreateControl", + "file": "retail_v2alpha_generated_control_service_create_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_CreateControl_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_create_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.delete_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.DeleteControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "DeleteControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteControlRequest" + }, + { + "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_control" + }, + "description": "Sample for DeleteControl", + "file": "retail_v2alpha_generated_control_service_delete_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_DeleteControl_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_delete_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.delete_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.DeleteControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "DeleteControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteControlRequest" + }, + { + "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_control" + }, + "description": "Sample for DeleteControl", + "file": "retail_v2alpha_generated_control_service_delete_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_DeleteControl_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_delete_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.get_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.GetControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "GetControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetControlRequest" + }, + { + "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.retail_v2alpha.types.Control", + "shortName": "get_control" + }, + "description": "Sample for GetControl", + "file": "retail_v2alpha_generated_control_service_get_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_GetControl_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_get_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.get_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.GetControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "GetControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetControlRequest" + }, + { + "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.retail_v2alpha.types.Control", + "shortName": "get_control" + }, + "description": "Sample for GetControl", + "file": "retail_v2alpha_generated_control_service_get_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_GetControl_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_get_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.list_controls", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.ListControls", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListControlsRequest" + }, + { + "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.retail_v2alpha.services.control_service.pagers.ListControlsAsyncPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "retail_v2alpha_generated_control_service_list_controls_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_ListControls_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_list_controls_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.list_controls", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.ListControls", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListControlsRequest" + }, + { + "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.retail_v2alpha.services.control_service.pagers.ListControlsPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "retail_v2alpha_generated_control_service_list_controls_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_ListControls_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_list_controls_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.update_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.UpdateControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "UpdateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateControlRequest" + }, + { + "name": "control", + "type": "google.cloud.retail_v2alpha.types.Control" + }, + { + "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.retail_v2alpha.types.Control", + "shortName": "update_control" + }, + "description": "Sample for UpdateControl", + "file": "retail_v2alpha_generated_control_service_update_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_UpdateControl_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_update_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.update_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.UpdateControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "UpdateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateControlRequest" + }, + { + "name": "control", + "type": "google.cloud.retail_v2alpha.types.Control" + }, + { + "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.retail_v2alpha.types.Control", + "shortName": "update_control" + }, + "description": "Sample for UpdateControl", + "file": "retail_v2alpha_generated_control_service_update_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_UpdateControl_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_update_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.PredictionServiceAsyncClient", + "shortName": "PredictionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.PredictionServiceAsyncClient.predict", + "method": { + "fullName": "google.cloud.retail.v2alpha.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2alpha.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2alpha_generated_prediction_service_predict_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_PredictionService_Predict_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_prediction_service_predict_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.PredictionServiceClient", + "shortName": "PredictionServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.PredictionServiceClient.predict", + "method": { + "fullName": "google.cloud.retail.v2alpha.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2alpha.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2alpha_generated_prediction_service_predict_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_PredictionService_Predict_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_prediction_service_predict_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2alpha_generated_product_service_add_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_add_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2alpha_generated_product_service_add_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_AddLocalInventories_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_add_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2alpha_generated_product_service_add_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_AddLocalInventories_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_add_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "name": "product_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.retail_v2alpha.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2alpha_generated_product_service_create_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_CreateProduct_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_create_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "name": "product_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.retail_v2alpha.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2alpha_generated_product_service_create_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_CreateProduct_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_create_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2alpha_generated_product_service_delete_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_DeleteProduct_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_delete_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2alpha_generated_product_service_delete_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_DeleteProduct_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_delete_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetProductRequest" + }, + { + "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.retail_v2alpha.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2alpha_generated_product_service_get_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_GetProduct_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_get_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetProductRequest" + }, + { + "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.retail_v2alpha.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2alpha_generated_product_service_get_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_GetProduct_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_get_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2alpha_generated_product_service_import_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_ImportProducts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_import_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2alpha_generated_product_service_import_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_ImportProducts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_import_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListProductsRequest" + }, + { + "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.retail_v2alpha.services.product_service.pagers.ListProductsAsyncPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2alpha_generated_product_service_list_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_ListProducts_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_list_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListProductsRequest" + }, + { + "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.retail_v2alpha.services.product_service.pagers.ListProductsPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2alpha_generated_product_service_list_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_ListProducts_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_list_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.purge_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.PurgeProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "PurgeProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PurgeProductsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_products" + }, + "description": "Sample for PurgeProducts", + "file": "retail_v2alpha_generated_product_service_purge_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_PurgeProducts_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_purge_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.purge_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.PurgeProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "PurgeProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PurgeProductsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_products" + }, + "description": "Sample for PurgeProducts", + "file": "retail_v2alpha_generated_product_service_purge_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_PurgeProducts_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_purge_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2alpha_generated_product_service_remove_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_RemoveLocalInventories_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_remove_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2alpha_generated_product_service_remove_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_remove_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2alpha_generated_product_service_set_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_SetInventory_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_set_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2alpha_generated_product_service_set_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_SetInventory_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_set_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "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.retail_v2alpha.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2alpha_generated_product_service_update_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_UpdateProduct_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_update_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "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.retail_v2alpha.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2alpha_generated_product_service_update_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_UpdateProduct_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_update_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.SearchServiceAsyncClient.search", + "method": { + "fullName": "google.cloud.retail.v2alpha.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2alpha.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2alpha_generated_search_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_SearchService_Search_async", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_search_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.SearchServiceClient", + "shortName": "SearchServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.SearchServiceClient.search", + "method": { + "fullName": "google.cloud.retail.v2alpha.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2alpha.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.services.search_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2alpha_generated_search_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_SearchService_Search_sync", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_search_service_search_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.add_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.AddControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "AddControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "add_control" + }, + "description": "Sample for AddControl", + "file": "retail_v2alpha_generated_serving_config_service_add_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_AddControl_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_add_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.add_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.AddControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "AddControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "add_control" + }, + "description": "Sample for AddControl", + "file": "retail_v2alpha_generated_serving_config_service_add_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_AddControl_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_add_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.create_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.CreateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "CreateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateServingConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2alpha.types.ServingConfig" + }, + { + "name": "serving_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "create_serving_config" + }, + "description": "Sample for CreateServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_create_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_create_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.create_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.CreateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "CreateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateServingConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2alpha.types.ServingConfig" + }, + { + "name": "serving_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "create_serving_config" + }, + "description": "Sample for CreateServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.delete_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.DeleteServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "DeleteServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteServingConfigRequest" + }, + { + "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_serving_config" + }, + "description": "Sample for DeleteServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.delete_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.DeleteServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "DeleteServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteServingConfigRequest" + }, + { + "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_serving_config" + }, + "description": "Sample for DeleteServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.get_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.GetServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "GetServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetServingConfigRequest" + }, + { + "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.retail_v2alpha.types.ServingConfig", + "shortName": "get_serving_config" + }, + "description": "Sample for GetServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_get_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_GetServingConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_get_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.get_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.GetServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "GetServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetServingConfigRequest" + }, + { + "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.retail_v2alpha.types.ServingConfig", + "shortName": "get_serving_config" + }, + "description": "Sample for GetServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.list_serving_configs", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.ListServingConfigs", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "ListServingConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListServingConfigsRequest" + }, + { + "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.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsAsyncPager", + "shortName": "list_serving_configs" + }, + "description": "Sample for ListServingConfigs", + "file": "retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.list_serving_configs", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.ListServingConfigs", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "ListServingConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListServingConfigsRequest" + }, + { + "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.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsPager", + "shortName": "list_serving_configs" + }, + "description": "Sample for ListServingConfigs", + "file": "retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.remove_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.RemoveControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "RemoveControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "remove_control" + }, + "description": "Sample for RemoveControl", + "file": "retail_v2alpha_generated_serving_config_service_remove_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_RemoveControl_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_remove_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.remove_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.RemoveControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "RemoveControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "remove_control" + }, + "description": "Sample for RemoveControl", + "file": "retail_v2alpha_generated_serving_config_service_remove_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_RemoveControl_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_remove_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.update_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.UpdateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "UpdateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateServingConfigRequest" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2alpha.types.ServingConfig" + }, + { + "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.retail_v2alpha.types.ServingConfig", + "shortName": "update_serving_config" + }, + "description": "Sample for UpdateServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_update_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_update_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.update_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.UpdateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "UpdateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateServingConfigRequest" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2alpha.types.ServingConfig" + }, + { + "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.retail_v2alpha.types.ServingConfig", + "shortName": "update_serving_config" + }, + "description": "Sample for UpdateServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2alpha_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_CollectUserEvent_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2alpha_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_CollectUserEvent_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2alpha_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_ImportUserEvents_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2alpha_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_ImportUserEvents_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2alpha_generated_user_event_service_purge_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_PurgeUserEvents_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_purge_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2alpha_generated_user_event_service_purge_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_purge_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_RejoinUserEvents_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2alpha_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_WriteUserEvent_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2alpha_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_WriteUserEvent_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py b/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py new file mode 100644 index 00000000..5fbe2d4d --- /dev/null +++ b/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py @@ -0,0 +1,219 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class retailCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_catalog_attribute': ('attributes_config', 'catalog_attribute', ), + 'add_control': ('serving_config', 'control_id', ), + 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), + 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), + 'create_control': ('parent', 'control', 'control_id', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'create_serving_config': ('parent', 'serving_config', 'serving_config_id', ), + 'delete_control': ('name', ), + 'delete_product': ('name', ), + 'delete_serving_config': ('name', ), + 'get_attributes_config': ('name', ), + 'get_completion_config': ('name', ), + 'get_control': ('name', ), + 'get_default_branch': ('catalog', ), + 'get_product': ('name', ), + 'get_serving_config': ('name', ), + 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), + 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), + 'import_user_events': ('parent', 'input_config', 'errors_config', ), + 'list_catalogs': ('parent', 'page_size', 'page_token', ), + 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', 'require_total_size', ), + 'list_serving_configs': ('parent', 'page_size', 'page_token', ), + 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), + 'purge_products': ('parent', 'filter', 'force', ), + 'purge_user_events': ('parent', 'filter', 'force', ), + 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), + 'remove_catalog_attribute': ('attributes_config', 'key', ), + 'remove_control': ('serving_config', 'control_id', ), + 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), + 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), + 'replace_catalog_attribute': ('attributes_config', 'catalog_attribute', 'update_mask', ), + 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'relevance_threshold', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), + 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), + 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), + 'update_attributes_config': ('attributes_config', 'update_mask', ), + 'update_catalog': ('catalog', 'update_mask', ), + 'update_completion_config': ('completion_config', 'update_mask', ), + 'update_control': ('control', 'update_mask', ), + 'update_product': ('product', 'update_mask', 'allow_missing', ), + 'update_serving_config': ('serving_config', 'update_mask', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=retailCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the retail client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2alpha/setup.py b/owl-bot-staging/v2alpha/setup.py new file mode 100644 index 00000000..3d49d09f --- /dev/null +++ b/owl-bot-staging/v2alpha/setup.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-retail', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-retail", + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.31.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'googleapis-common-protos >= 1.55.0, <2.0.0dev', + 'proto-plus >= 1.19.7', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2alpha/tests/__init__.py b/owl-bot-staging/v2alpha/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/tests/unit/__init__.py b/owl-bot-staging/v2alpha/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py new file mode 100644 index 00000000..b956c510 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py @@ -0,0 +1,3793 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.catalog_service import CatalogServiceAsyncClient +from google.cloud.retail_v2alpha.services.catalog_service import CatalogServiceClient +from google.cloud.retail_v2alpha.services.catalog_service import pagers +from google.cloud.retail_v2alpha.services.catalog_service import transports +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CatalogServiceClient._get_default_mtls_endpoint(None) is None + assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CatalogServiceGrpcTransport, "grpc"), + (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_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", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_catalog_service_client_get_transport_class(): + transport = CatalogServiceClient.get_transport_class() + available_transports = [ + transports.CatalogServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CatalogServiceClient.get_transport_class("grpc") + assert transport == transports.CatalogServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + CatalogServiceClient, CatalogServiceAsyncClient +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_catalog_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CatalogServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ListCatalogsRequest, + dict, +]) +def test_list_catalogs(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_catalogs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalogs), + '__call__') as call: + client.list_catalogs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + +@pytest.mark.asyncio +async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_catalogs_async_from_dict(): + await test_list_catalogs_async(request_type=dict) + + +def test_list_catalogs_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = catalog_service.ListCatalogsResponse() + client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_catalogs( + 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_catalogs_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_catalogs_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_catalogs( + 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_catalogs_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + + +def test_list_catalogs_pager(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_catalogs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, catalog.Catalog) + for i in results) +def test_list_catalogs_pages(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = list(client.list_catalogs(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_catalogs_async_pager(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_catalogs(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, catalog.Catalog) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_catalogs_async_pages(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCatalogRequest, + dict, +]) +def test_update_catalog(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + ) + response = client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_catalog_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalog), + '__call__') as call: + client.update_catalog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + +@pytest.mark.asyncio +async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_catalog_async_from_dict(): + await test_update_catalog_async(request_type=dict) + + +def test_update_catalog_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = gcr_catalog.Catalog() + client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_catalog_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +def test_update_catalog_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_catalog_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.SetDefaultBranchRequest, + dict, +]) +def test_set_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_set_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + client.set_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_set_default_branch_async_from_dict(): + await test_set_default_branch_async(request_type=dict) + + +def test_set_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = None + client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_set_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_set_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetDefaultBranchRequest, + dict, +]) +def test_get_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + ) + response = client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +def test_get_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_default_branch), + '__call__') as call: + client.get_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + )) + response = await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +@pytest.mark.asyncio +async def test_get_default_branch_async_from_dict(): + await test_get_default_branch_async(request_type=dict) + + +def test_get_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = catalog_service.GetDefaultBranchResponse() + client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_get_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_get_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetCompletionConfigRequest, + dict, +]) +def test_get_completion_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + ) + response = client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +def test_get_completion_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_completion_config), + '__call__') as call: + client.get_completion_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + +@pytest.mark.asyncio +async def test_get_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCompletionConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + )) + response = await client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +@pytest.mark.asyncio +async def test_get_completion_config_async_from_dict(): + await test_get_completion_config_async(request_type=dict) + + +def test_get_completion_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCompletionConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + call.return_value = catalog.CompletionConfig() + client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_completion_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCompletionConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + await client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_completion_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_completion_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_completion_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_completion_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_completion_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_completion_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCompletionConfigRequest, + dict, +]) +def test_update_completion_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + ) + response = client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +def test_update_completion_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_completion_config), + '__call__') as call: + client.update_completion_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + +@pytest.mark.asyncio +async def test_update_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCompletionConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + )) + response = await client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +@pytest.mark.asyncio +async def test_update_completion_config_async_from_dict(): + await test_update_completion_config_async(request_type=dict) + + +def test_update_completion_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCompletionConfigRequest() + + request.completion_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + call.return_value = catalog.CompletionConfig() + client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'completion_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_completion_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCompletionConfigRequest() + + request.completion_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + await client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'completion_config.name=name_value', + ) in kw['metadata'] + + +def test_update_completion_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_completion_config( + completion_config=catalog.CompletionConfig(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].completion_config + mock_val = catalog.CompletionConfig(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_completion_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_completion_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_completion_config( + completion_config=catalog.CompletionConfig(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].completion_config + mock_val = catalog.CompletionConfig(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_completion_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetAttributesConfigRequest, + dict, +]) +def test_get_attributes_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_get_attributes_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_attributes_config), + '__call__') as call: + client.get_attributes_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + +@pytest.mark.asyncio +async def test_get_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetAttributesConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_get_attributes_config_async_from_dict(): + await test_get_attributes_config_async(request_type=dict) + + +def test_get_attributes_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetAttributesConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_attributes_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetAttributesConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_attributes_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_attributes_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_attributes_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_attributes_config( + catalog_service.GetAttributesConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_attributes_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_attributes_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_attributes_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_attributes_config( + catalog_service.GetAttributesConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateAttributesConfigRequest, + dict, +]) +def test_update_attributes_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_update_attributes_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_attributes_config), + '__call__') as call: + client.update_attributes_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + +@pytest.mark.asyncio +async def test_update_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateAttributesConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_update_attributes_config_async_from_dict(): + await test_update_attributes_config_async(request_type=dict) + + +def test_update_attributes_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateAttributesConfigRequest() + + request.attributes_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_attributes_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateAttributesConfigRequest() + + request.attributes_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config.name=name_value', + ) in kw['metadata'] + + +def test_update_attributes_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_attributes_config( + attributes_config=catalog.AttributesConfig(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].attributes_config + mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_attributes_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_attributes_config( + attributes_config=catalog.AttributesConfig(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].attributes_config + mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.AddCatalogAttributeRequest, + dict, +]) +def test_add_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_add_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + client.add_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_add_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.AddCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_add_catalog_attribute_async_from_dict(): + await test_add_catalog_attribute_async(request_type=dict) + + +def test_add_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.AddCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.AddCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + catalog_service.RemoveCatalogAttributeRequest, + dict, +]) +def test_remove_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_remove_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + client.remove_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.RemoveCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_async_from_dict(): + await test_remove_catalog_attribute_async(request_type=dict) + + +def test_remove_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.RemoveCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.RemoveCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ReplaceCatalogAttributeRequest, + dict, +]) +def test_replace_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_replace_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + client.replace_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ReplaceCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_async_from_dict(): + await test_replace_catalog_attribute_async(request_type=dict) + + +def test_replace_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ReplaceCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ReplaceCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CatalogServiceClient.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 = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CatalogServiceGrpcTransport, + ) + +def test_catalog_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_catalog_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_catalogs', + 'update_catalog', + 'set_default_branch', + 'get_default_branch', + 'get_completion_config', + 'update_completion_config', + 'get_attributes_config', + 'update_attributes_config', + 'add_catalog_attribute', + 'remove_catalog_attribute', + 'replace_catalog_attribute', + ) + 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_catalog_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.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport( + 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_catalog_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.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport() + adc.assert_called_once() + + +def test_catalog_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) + CatalogServiceClient() + 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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +def test_catalog_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,grpc_helpers", + [ + (transports.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_catalog_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_no_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_with_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_catalog_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcTransport( + 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_catalog_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcAsyncIOTransport( + 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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_attributes_config_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.attributes_config_path(project, location, catalog) + assert expected == actual + + +def test_parse_attributes_config_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CatalogServiceClient.attributes_config_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_attributes_config_path(path) + assert expected == actual + +def test_branch_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = CatalogServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "branch": "clam", + } + path = CatalogServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_branch_path(path) + assert expected == actual + +def test_catalog_path(): + project = "whelk" + location = "octopus" + catalog = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + } + path = CatalogServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_completion_config_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.completion_config_path(project, location, catalog) + assert expected == actual + + +def test_parse_completion_config_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + } + path = CatalogServiceClient.completion_config_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_completion_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CatalogServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = CatalogServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = CatalogServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CatalogServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CatalogServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CatalogServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = CatalogServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CatalogServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CatalogServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CatalogServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py new file mode 100644 index 00000000..9cd6cc79 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py @@ -0,0 +1,1451 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.completion_service import CompletionServiceAsyncClient +from google.cloud.retail_v2alpha.services.completion_service import CompletionServiceClient +from google.cloud.retail_v2alpha.services.completion_service import transports +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CompletionServiceClient._get_default_mtls_endpoint(None) is None + assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CompletionServiceGrpcTransport, "grpc"), + (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_completion_service_client_get_transport_class(): + transport = CompletionServiceClient.get_transport_class() + available_transports = [ + transports.CompletionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CompletionServiceClient.get_transport_class("grpc") + assert transport == transports.CompletionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + CompletionServiceClient, CompletionServiceAsyncClient +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_completion_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CompletionServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + ) + response = client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +def test_complete_query_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + client.complete_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + +@pytest.mark.asyncio +async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + )) + response = await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +@pytest.mark.asyncio +async def test_complete_query_async_from_dict(): + await test_complete_query_async(request_type=dict) + + +def test_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) + await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportCompletionDataRequest, + dict, +]) +def test_import_completion_data(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_completion_data_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + client.import_completion_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + +@pytest.mark.asyncio +async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_completion_data_async_from_dict(): + await test_import_completion_data_async(request_type=dict) + + +def test_import_completion_data_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # 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_completion_data_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CompletionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CompletionServiceGrpcTransport, + ) + +def test_completion_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_completion_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'complete_query', + 'import_completion_data', + ) + 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_completion_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_completion_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport() + adc.assert_called_once() + + +def test_completion_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CompletionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionServiceGrpcTransport, grpc_helpers), + (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_completion_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_no_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_with_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_completion_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_completion_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_completion_service_grpc_lro_client(): + client = CompletionServiceClient( + 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_completion_service_grpc_lro_async_client(): + client = CompletionServiceAsyncClient( + 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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CompletionServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CompletionServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CompletionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CompletionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = CompletionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CompletionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CompletionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CompletionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = CompletionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CompletionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CompletionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CompletionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CompletionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py new file mode 100644 index 00000000..197c7a8b --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py @@ -0,0 +1,2566 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.control_service import ControlServiceAsyncClient +from google.cloud.retail_v2alpha.services.control_service import ControlServiceClient +from google.cloud.retail_v2alpha.services.control_service import pagers +from google.cloud.retail_v2alpha.services.control_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.cloud.retail_v2alpha.types import search_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ControlServiceClient._get_default_mtls_endpoint(None) is None + assert ControlServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ControlServiceClient, "grpc"), + (ControlServiceAsyncClient, "grpc_asyncio"), +]) +def test_control_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ControlServiceGrpcTransport, "grpc"), + (transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_control_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", [ + (ControlServiceClient, "grpc"), + (ControlServiceAsyncClient, "grpc_asyncio"), +]) +def test_control_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_control_service_client_get_transport_class(): + transport = ControlServiceClient.get_transport_class() + available_transports = [ + transports.ControlServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ControlServiceClient.get_transport_class("grpc") + assert transport == transports.ControlServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +def test_control_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(ControlServiceClient, '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(ControlServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "true"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "false"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_control_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + ControlServiceClient, ControlServiceAsyncClient +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +def test_control_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_control_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_control_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_control_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.control_service.transports.ControlServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ControlServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_control_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.CreateControlRequest, + dict, +]) +def test_create_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +def test_create_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.create_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + +@pytest.mark.asyncio +async def test_create_control_async(transport: str = 'grpc_asyncio', request_type=control_service.CreateControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + )) + response = await client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +@pytest.mark.asyncio +async def test_create_control_async_from_dict(): + await test_create_control_async(request_type=dict) + + +def test_create_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.CreateControlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + call.return_value = gcr_control.Control() + client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.CreateControlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + await client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_control( + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) + assert arg == mock_val + arg = args[0].control_id + mock_val = 'control_id_value' + assert arg == mock_val + + +def test_create_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.CreateControlRequest(), + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_id_value', + ) + +@pytest.mark.asyncio +async def test_create_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_control( + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) + assert arg == mock_val + arg = args[0].control_id + mock_val = 'control_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.CreateControlRequest(), + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.DeleteControlRequest, + dict, +]) +def test_delete_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.delete_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + +@pytest.mark.asyncio +async def test_delete_control_async(transport: str = 'grpc_asyncio', request_type=control_service.DeleteControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_control_async_from_dict(): + await test_delete_control_async(request_type=dict) + + +def test_delete_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.DeleteControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__call__') as call: + call.return_value = None + client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.DeleteControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__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_control( + 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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.DeleteControlRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__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_control( + 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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.DeleteControlRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.UpdateControlRequest, + dict, +]) +def test_update_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +def test_update_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.update_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + +@pytest.mark.asyncio +async def test_update_control_async(transport: str = 'grpc_asyncio', request_type=control_service.UpdateControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + )) + response = await client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +@pytest.mark.asyncio +async def test_update_control_async_from_dict(): + await test_update_control_async(request_type=dict) + + +def test_update_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.UpdateControlRequest() + + request.control.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + call.return_value = gcr_control.Control() + client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'control.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.UpdateControlRequest() + + request.control.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + await client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'control.name=name_value', + ) in kw['metadata'] + + +def test_update_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_control( + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_control( + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.GetControlRequest, + dict, +]) +def test_get_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +def test_get_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.get_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + +@pytest.mark.asyncio +async def test_get_control_async(transport: str = 'grpc_asyncio', request_type=control_service.GetControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + )) + response = await client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +@pytest.mark.asyncio +async def test_get_control_async_from_dict(): + await test_get_control_async(request_type=dict) + + +def test_get_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.GetControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + call.return_value = control.Control() + client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.GetControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) + await client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_control( + 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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.GetControlRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_control( + 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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.GetControlRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.ListControlsRequest, + dict, +]) +def test_list_controls(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_controls_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_controls), + '__call__') as call: + client.list_controls() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + +@pytest.mark.asyncio +async def test_list_controls_async(transport: str = 'grpc_asyncio', request_type=control_service.ListControlsRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_controls_async_from_dict(): + await test_list_controls_async(request_type=dict) + + +def test_list_controls_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.ListControlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + call.return_value = control_service.ListControlsResponse() + client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_controls_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.ListControlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) + await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_controls_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_controls( + 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_controls_flattened_error(): + client = ControlServiceClient( + credentials=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_controls( + control_service.ListControlsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_controls_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_controls( + 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_controls_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_controls( + control_service.ListControlsRequest(), + parent='parent_value', + ) + + +def test_list_controls_pager(transport_name: str = "grpc"): + client = ControlServiceClient( + 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_controls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_controls(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, control.Control) + for i in results) +def test_list_controls_pages(transport_name: str = "grpc"): + client = ControlServiceClient( + 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_controls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + pages = list(client.list_controls(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_controls_async_pager(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_controls(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, control.Control) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_controls_async_pages(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_controls(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ControlServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ControlServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ControlServiceClient.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 = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ControlServiceGrpcTransport, + ) + +def test_control_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ControlServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_control_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.control_service.transports.ControlServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ControlServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_control', + 'delete_control', + 'update_control', + 'get_control', + 'list_controls', + ) + 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_control_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.retail_v2alpha.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ControlServiceTransport( + 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_control_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.retail_v2alpha.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ControlServiceTransport() + adc.assert_called_once() + + +def test_control_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) + ControlServiceClient() + 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.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + ], +) +def test_control_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,grpc_helpers", + [ + (transports.ControlServiceGrpcTransport, grpc_helpers), + (transports.ControlServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_control_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_control_service_host_no_port(transport_name): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_control_service_host_with_port(transport_name): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_control_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ControlServiceGrpcTransport( + 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_control_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ControlServiceGrpcAsyncIOTransport( + 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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = ControlServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = ControlServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_control_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + control = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) + actual = ControlServiceClient.control_path(project, location, catalog, control) + assert expected == actual + + +def test_parse_control_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "control": "clam", + } + path = ControlServiceClient.control_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_control_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ControlServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ControlServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ControlServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ControlServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ControlServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ControlServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ControlServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ControlServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.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 = ControlServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ControlServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.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.ControlServiceTransport, '_prep_wrapped_messages') as prep: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ControlServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ControlServiceClient.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 = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ControlServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ControlServiceClient( + 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", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py new file mode 100644 index 00000000..c264812d --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py @@ -0,0 +1,1279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.prediction_service import PredictionServiceAsyncClient +from google.cloud.retail_v2alpha.services.prediction_service import PredictionServiceClient +from google.cloud.retail_v2alpha.services.prediction_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import prediction_service +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import user_event +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PredictionServiceClient._get_default_mtls_endpoint(None) is None + assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionServiceGrpcTransport, "grpc"), + (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_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", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_prediction_service_client_get_transport_class(): + transport = PredictionServiceClient.get_transport_class() + available_transports = [ + transports.PredictionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = PredictionServiceClient.get_transport_class("grpc") + assert transport == transports.PredictionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + PredictionServiceClient, PredictionServiceAsyncClient +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_prediction_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PredictionServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_service.PredictRequest, + dict, +]) +def test_predict(request_type, transport: str = 'grpc'): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + response = client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_predict_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + client.predict() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + +@pytest.mark.asyncio +async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + )) + response = await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +@pytest.mark.asyncio +async def test_predict_async_from_dict(): + await test_predict_async(request_type=dict) + + +def test_predict_field_headers(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_predict_field_headers_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) + await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = PredictionServiceClient.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 = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'predict', + ) + 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport( + 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport() + adc.assert_called_once() + + +def test_prediction_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) + PredictionServiceClient() + 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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +def test_prediction_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,grpc_helpers", + [ + (transports.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_prediction_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_no_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_with_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_prediction_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcTransport( + 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_prediction_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcAsyncIOTransport( + 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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_product_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + product = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + "branch": "winkle", + "product": "nautilus", + } + path = PredictionServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PredictionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = PredictionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = PredictionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = PredictionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PredictionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = PredictionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = PredictionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = PredictionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = PredictionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PredictionServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py new file mode 100644 index 00000000..f6da565c --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py @@ -0,0 +1,4237 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.product_service import ProductServiceAsyncClient +from google.cloud.retail_v2alpha.services.product_service import ProductServiceClient +from google.cloud.retail_v2alpha.services.product_service import pagers +from google.cloud.retail_v2alpha.services.product_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import purge_config +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProductServiceClient._get_default_mtls_endpoint(None) is None + assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProductServiceGrpcTransport, "grpc"), + (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_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", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_product_service_client_get_transport_class(): + transport = ProductServiceClient.get_transport_class() + available_transports = [ + transports.ProductServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ProductServiceClient.get_transport_class("grpc") + assert transport == transports.ProductServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_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(ProductServiceClient, '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(ProductServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + ProductServiceClient, ProductServiceAsyncClient +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_product_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProductServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.CreateProductRequest, + dict, +]) +def test_create_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_create_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.create_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + +@pytest.mark.asyncio +async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_create_product_async_from_dict(): + await test_create_product_async(request_type=dict) + + +def test_create_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + + +def test_create_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + +@pytest.mark.asyncio +async def test_create_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_get_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.get_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + +@pytest.mark.asyncio +async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_get_product_async_from_dict(): + await test_get_product_async(request_type=dict) + + +def test_get_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = product.Product() + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.GetProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.GetProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.list_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + +@pytest.mark.asyncio +async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_products_async_from_dict(): + await test_list_products_async(request_type=dict) + + +def test_list_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = product_service.ListProductsResponse() + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products( + 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_products_flattened_error(): + client = ProductServiceClient( + credentials=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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products( + 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_products_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + + +def test_list_products_pager(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_products(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, product.Product) + for i in results) +def test_list_products_pages(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(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_products_async_pager(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(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, product.Product) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_products(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + product_service.UpdateProductRequest, + dict, +]) +def test_update_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_update_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.update_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + +@pytest.mark.asyncio +async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_update_product_async_from_dict(): + await test_update_product_async(request_type=dict) + + +def test_update_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +def test_update_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.DeleteProductRequest, + dict, +]) +def test_delete_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.delete_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + +@pytest.mark.asyncio +async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_product_async_from_dict(): + await test_delete_product_async(request_type=dict) + + +def test_delete_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = None + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeProductsRequest, + dict, +]) +def test_purge_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + client.purge_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeProductsRequest() + +@pytest.mark.asyncio +async def test_purge_products_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_products_async_from_dict(): + await test_purge_products_async(request_type=dict) + + +def test_purge_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_purge_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportProductsRequest, + dict, +]) +def test_import_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.import_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + +@pytest.mark.asyncio +async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__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_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_products_async_from_dict(): + await test_import_products_async(request_type=dict) + + +def test_import_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + product_service.SetInventoryRequest, + dict, +]) +def test_set_inventory(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_inventory_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + client.set_inventory() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + +@pytest.mark.asyncio +async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_set_inventory_async_from_dict(): + await test_set_inventory_async(request_type=dict) + + +def test_set_inventory_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_inventory_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +def test_set_inventory_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_set_inventory_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_set_inventory_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_inventory_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddFulfillmentPlacesRequest, + dict, +]) +def test_add_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + client.add_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async_from_dict(): + await test_add_fulfillment_places_async(request_type=dict) + + +def test_add_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveFulfillmentPlacesRequest, + dict, +]) +def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + client.remove_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async_from_dict(): + await test_remove_fulfillment_places_async(request_type=dict) + + +def test_remove_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddLocalInventoriesRequest, + dict, +]) +def test_add_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + client.add_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_local_inventories_async_from_dict(): + await test_add_local_inventories_async(request_type=dict) + + +def test_add_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveLocalInventoriesRequest, + dict, +]) +def test_remove_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + client.remove_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_local_inventories_async_from_dict(): + await test_remove_local_inventories_async(request_type=dict) + + +def test_remove_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ProductServiceClient.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 = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProductServiceGrpcTransport, + ) + +def test_product_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_product_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.product_service.transports.ProductServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_product', + 'get_product', + 'list_products', + 'update_product', + 'delete_product', + 'purge_products', + 'import_products', + 'set_inventory', + 'add_fulfillment_places', + 'remove_fulfillment_places', + 'add_local_inventories', + 'remove_local_inventories', + ) + 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_product_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.retail_v2alpha.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport( + 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_product_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.retail_v2alpha.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport() + adc.assert_called_once() + + +def test_product_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) + ProductServiceClient() + 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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + ], +) +def test_product_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,grpc_helpers", + [ + (transports.ProductServiceGrpcTransport, grpc_helpers), + (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_product_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_no_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_with_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_product_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcTransport( + 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_product_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcAsyncIOTransport( + 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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_product_service_grpc_lro_client(): + client = ProductServiceClient( + 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_product_service_grpc_lro_async_client(): + client = ProductServiceAsyncClient( + 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" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = ProductServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = ProductServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = ProductServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = ProductServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProductServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ProductServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProductServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ProductServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProductServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ProductServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ProductServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ProductServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ProductServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ProductServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ProductServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py new file mode 100644 index 00000000..feeb37e8 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py @@ -0,0 +1,1496 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.search_service import SearchServiceAsyncClient +from google.cloud.retail_v2alpha.services.search_service import SearchServiceClient +from google.cloud.retail_v2alpha.services.search_service import pagers +from google.cloud.retail_v2alpha.services.search_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SearchServiceClient._get_default_mtls_endpoint(None) is None + assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SearchServiceGrpcTransport, "grpc"), + (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_search_service_client_get_transport_class(): + transport = SearchServiceClient.get_transport_class() + available_transports = [ + transports.SearchServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SearchServiceClient.get_transport_class("grpc") + assert transport == transports.SearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + SearchServiceClient, SearchServiceAsyncClient +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SearchServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + search_service.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + + +def test_search_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = search_service.SearchResponse() + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_search_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('placement', ''), + )), + ) + pager = client.search(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_async_pager(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = SearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_search_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_search_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport() + adc.assert_called_once() + + +def test_search_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SearchServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SearchServiceGrpcTransport, grpc_helpers), + (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_search_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_no_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_with_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_branch_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = SearchServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = SearchServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = SearchServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = SearchServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py new file mode 100644 index 00000000..a4c423fa --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py @@ -0,0 +1,3279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.serving_config_service import ServingConfigServiceAsyncClient +from google.cloud.retail_v2alpha.services.serving_config_service import ServingConfigServiceClient +from google.cloud.retail_v2alpha.services.serving_config_service import pagers +from google.cloud.retail_v2alpha.services.serving_config_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ServingConfigServiceClient._get_default_mtls_endpoint(None) is None + assert ServingConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ServingConfigServiceClient, "grpc"), + (ServingConfigServiceAsyncClient, "grpc_asyncio"), +]) +def test_serving_config_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ServingConfigServiceGrpcTransport, "grpc"), + (transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_serving_config_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", [ + (ServingConfigServiceClient, "grpc"), + (ServingConfigServiceAsyncClient, "grpc_asyncio"), +]) +def test_serving_config_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_serving_config_service_client_get_transport_class(): + transport = ServingConfigServiceClient.get_transport_class() + available_transports = [ + transports.ServingConfigServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ServingConfigServiceClient.get_transport_class("grpc") + assert transport == transports.ServingConfigServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +def test_serving_config_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(ServingConfigServiceClient, '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(ServingConfigServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "true"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "false"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_serving_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + ServingConfigServiceClient, ServingConfigServiceAsyncClient +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +def test_serving_config_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_serving_config_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_serving_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_serving_config_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ServingConfigServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_serving_config_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.CreateServingConfigRequest, + dict, +]) +def test_create_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_create_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.create_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + +@pytest.mark.asyncio +async def test_create_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.CreateServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_create_serving_config_async_from_dict(): + await test_create_serving_config_async(request_type=dict) + + +def test_create_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.CreateServingConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.CreateServingConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_serving_config( + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].serving_config + mock_val = gcr_serving_config.ServingConfig(name='name_value') + assert arg == mock_val + arg = args[0].serving_config_id + mock_val = 'serving_config_id_value' + assert arg == mock_val + + +def test_create_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.CreateServingConfigRequest(), + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_serving_config( + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].serving_config + mock_val = gcr_serving_config.ServingConfig(name='name_value') + assert arg == mock_val + arg = args[0].serving_config_id + mock_val = 'serving_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.CreateServingConfigRequest(), + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.DeleteServingConfigRequest, + dict, +]) +def test_delete_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.delete_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + +@pytest.mark.asyncio +async def test_delete_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.DeleteServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_serving_config_async_from_dict(): + await test_delete_serving_config_async(request_type=dict) + + +def test_delete_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.DeleteServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__call__') as call: + call.return_value = None + client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.DeleteServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__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_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.DeleteServingConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__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_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.DeleteServingConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.UpdateServingConfigRequest, + dict, +]) +def test_update_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_update_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.update_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + +@pytest.mark.asyncio +async def test_update_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.UpdateServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_update_serving_config_async_from_dict(): + await test_update_serving_config_async(request_type=dict) + + +def test_update_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.UpdateServingConfigRequest() + + request.serving_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.UpdateServingConfigRequest() + + request.serving_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config.name=name_value', + ) in kw['metadata'] + + +def test_update_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_serving_config( + serving_config=gcr_serving_config.ServingConfig(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].serving_config + mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_serving_config( + serving_config=gcr_serving_config.ServingConfig(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].serving_config + mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.GetServingConfigRequest, + dict, +]) +def test_get_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_get_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.get_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + +@pytest.mark.asyncio +async def test_get_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.GetServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_get_serving_config_async_from_dict(): + await test_get_serving_config_async(request_type=dict) + + +def test_get_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.GetServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + call.return_value = serving_config.ServingConfig() + client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.GetServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) + await client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.GetServingConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.GetServingConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.ListServingConfigsRequest, + dict, +]) +def test_list_serving_configs(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_serving_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_configs), + '__call__') as call: + client.list_serving_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + +@pytest.mark.asyncio +async def test_list_serving_configs_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.ListServingConfigsRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_serving_configs_async_from_dict(): + await test_list_serving_configs_async(request_type=dict) + + +def test_list_serving_configs_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.ListServingConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + call.return_value = serving_config_service.ListServingConfigsResponse() + client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_serving_configs_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.ListServingConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) + await client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_serving_configs_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_serving_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_serving_configs_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_serving_configs_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_serving_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_serving_configs_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent='parent_value', + ) + + +def test_list_serving_configs_pager(transport_name: str = "grpc"): + client = ServingConfigServiceClient( + 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_serving_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_serving_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, serving_config.ServingConfig) + for i in results) +def test_list_serving_configs_pages(transport_name: str = "grpc"): + client = ServingConfigServiceClient( + 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_serving_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_serving_configs(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_serving_configs_async_pager(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_serving_configs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, serving_config.ServingConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_serving_configs_async_pages(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_serving_configs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + serving_config_service.AddControlRequest, + dict, +]) +def test_add_control(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_add_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + client.add_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + +@pytest.mark.asyncio +async def test_add_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.AddControlRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_add_control_async_from_dict(): + await test_add_control_async(request_type=dict) + + +def test_add_control_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.AddControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_control_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.AddControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_add_control_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + + +def test_add_control_flattened_error(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_control( + serving_config_service.AddControlRequest(), + serving_config='serving_config_value', + ) + +@pytest.mark.asyncio +async def test_add_control_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_control_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_control( + serving_config_service.AddControlRequest(), + serving_config='serving_config_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.RemoveControlRequest, + dict, +]) +def test_remove_control(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_remove_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + client.remove_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + +@pytest.mark.asyncio +async def test_remove_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.RemoveControlRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_remove_control_async_from_dict(): + await test_remove_control_async(request_type=dict) + + +def test_remove_control_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.RemoveControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_control_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.RemoveControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_remove_control_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + + +def test_remove_control_flattened_error(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config='serving_config_value', + ) + +@pytest.mark.asyncio +async def test_remove_control_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_control_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config='serving_config_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServingConfigServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ServingConfigServiceClient.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 = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ServingConfigServiceGrpcTransport, + ) + +def test_serving_config_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ServingConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_serving_config_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ServingConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_serving_config', + 'delete_serving_config', + 'update_serving_config', + 'get_serving_config', + 'list_serving_configs', + 'add_control', + 'remove_control', + ) + 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_serving_config_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.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServingConfigServiceTransport( + 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_serving_config_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.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServingConfigServiceTransport() + adc.assert_called_once() + + +def test_serving_config_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) + ServingConfigServiceClient() + 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.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + ], +) +def test_serving_config_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,grpc_helpers", + [ + (transports.ServingConfigServiceGrpcTransport, grpc_helpers), + (transports.ServingConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_serving_config_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_serving_config_service_host_no_port(transport_name): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_serving_config_service_host_with_port(transport_name): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_serving_config_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServingConfigServiceGrpcTransport( + 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_serving_config_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + 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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = ServingConfigServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = ServingConfigServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + serving_config = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, serving_config=serving_config, ) + actual = ServingConfigServiceClient.serving_config_path(project, location, catalog, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "serving_config": "clam", + } + path = ServingConfigServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ServingConfigServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ServingConfigServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ServingConfigServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ServingConfigServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ServingConfigServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ServingConfigServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ServingConfigServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ServingConfigServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.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 = ServingConfigServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ServingConfigServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.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.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ServingConfigServiceClient.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 = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ServingConfigServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ServingConfigServiceClient( + 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", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py new file mode 100644 index 00000000..88587802 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py @@ -0,0 +1,1988 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.retail_v2alpha.services.user_event_service import UserEventServiceClient +from google.cloud.retail_v2alpha.services.user_event_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + ) + response = client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +def test_write_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) + await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeUserEventsRequest, + dict, +]) +def test_purge_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + client.purge_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + +@pytest.mark.asyncio +async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_user_events_async_from_dict(): + await test_purge_user_events_async(request_type=dict) + + +def test_purge_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_purge_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.RejoinUserEventsRequest, + dict, +]) +def test_rejoin_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_rejoin_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + client.rejoin_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + +@pytest.mark.asyncio +async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_rejoin_user_events_async_from_dict(): + await test_rejoin_user_events_async(request_type=dict) + + +def test_rejoin_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_rejoin_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'purge_user_events', + 'import_user_events', + 'rejoin_user_events', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_user_event_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_user_event_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +def test_user_event_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + UserEventServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = UserEventServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = UserEventServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_product_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + product = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + "branch": "whelk", + "product": "octopus", + } + path = UserEventServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2beta/.coveragerc b/owl-bot-staging/v2beta/.coveragerc new file mode 100644 index 00000000..a8b114f0 --- /dev/null +++ b/owl-bot-staging/v2beta/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/retail/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2beta/.flake8 b/owl-bot-staging/v2beta/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v2beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v2beta/MANIFEST.in b/owl-bot-staging/v2beta/MANIFEST.in new file mode 100644 index 00000000..43074617 --- /dev/null +++ b/owl-bot-staging/v2beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/retail *.py +recursive-include google/cloud/retail_v2beta *.py diff --git a/owl-bot-staging/v2beta/README.rst b/owl-bot-staging/v2beta/README.rst new file mode 100644 index 00000000..cb039760 --- /dev/null +++ b/owl-bot-staging/v2beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Retail API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Retail API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2beta/docs/conf.py b/owl-bot-staging/v2beta/docs/conf.py new file mode 100644 index 00000000..5be9eb4b --- /dev/null +++ b/owl-bot-staging/v2beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-retail documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-retail" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-retail-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-retail.tex", + u"google-cloud-retail Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-retail", + u"Google Cloud Retail Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-retail", + u"google-cloud-retail Documentation", + author, + "google-cloud-retail", + "GAPIC library for Google Cloud Retail API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v2beta/docs/index.rst b/owl-bot-staging/v2beta/docs/index.rst new file mode 100644 index 00000000..fd60fc85 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + retail_v2beta/services + retail_v2beta/types diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst new file mode 100644 index 00000000..3a7c19e6 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst @@ -0,0 +1,10 @@ +CatalogService +-------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.catalog_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.catalog_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst new file mode 100644 index 00000000..1f6782ed --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst @@ -0,0 +1,6 @@ +CompletionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.completion_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst new file mode 100644 index 00000000..86cfcba1 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst @@ -0,0 +1,10 @@ +ControlService +-------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.control_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.control_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst new file mode 100644 index 00000000..903c951d --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst @@ -0,0 +1,6 @@ +PredictionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.prediction_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst new file mode 100644 index 00000000..489daa22 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst @@ -0,0 +1,10 @@ +ProductService +-------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.product_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.product_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst new file mode 100644 index 00000000..591f5c86 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst @@ -0,0 +1,10 @@ +SearchService +------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst new file mode 100644 index 00000000..04251720 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst @@ -0,0 +1,13 @@ +Services for Google Cloud Retail v2beta API +=========================================== +.. toctree:: + :maxdepth: 2 + + catalog_service + completion_service + control_service + prediction_service + product_service + search_service + serving_config_service + user_event_service diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst new file mode 100644 index 00000000..c074749c --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst @@ -0,0 +1,10 @@ +ServingConfigService +-------------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.serving_config_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.serving_config_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst new file mode 100644 index 00000000..ae17ce43 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Retail v2beta API +======================================== + +.. automodule:: google.cloud.retail_v2beta.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst new file mode 100644 index 00000000..11ab3794 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst @@ -0,0 +1,6 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.user_event_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/google/cloud/retail/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail/__init__.py new file mode 100644 index 00000000..07f795e3 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail/__init__.py @@ -0,0 +1,275 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.retail_v2beta.services.catalog_service.client import CatalogServiceClient +from google.cloud.retail_v2beta.services.catalog_service.async_client import CatalogServiceAsyncClient +from google.cloud.retail_v2beta.services.completion_service.client import CompletionServiceClient +from google.cloud.retail_v2beta.services.completion_service.async_client import CompletionServiceAsyncClient +from google.cloud.retail_v2beta.services.control_service.client import ControlServiceClient +from google.cloud.retail_v2beta.services.control_service.async_client import ControlServiceAsyncClient +from google.cloud.retail_v2beta.services.prediction_service.client import PredictionServiceClient +from google.cloud.retail_v2beta.services.prediction_service.async_client import PredictionServiceAsyncClient +from google.cloud.retail_v2beta.services.product_service.client import ProductServiceClient +from google.cloud.retail_v2beta.services.product_service.async_client import ProductServiceAsyncClient +from google.cloud.retail_v2beta.services.search_service.client import SearchServiceClient +from google.cloud.retail_v2beta.services.search_service.async_client import SearchServiceAsyncClient +from google.cloud.retail_v2beta.services.serving_config_service.client import ServingConfigServiceClient +from google.cloud.retail_v2beta.services.serving_config_service.async_client import ServingConfigServiceAsyncClient +from google.cloud.retail_v2beta.services.user_event_service.client import UserEventServiceClient +from google.cloud.retail_v2beta.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.retail_v2beta.types.catalog import AttributesConfig +from google.cloud.retail_v2beta.types.catalog import Catalog +from google.cloud.retail_v2beta.types.catalog import CatalogAttribute +from google.cloud.retail_v2beta.types.catalog import CompletionConfig +from google.cloud.retail_v2beta.types.catalog import MerchantCenterLink +from google.cloud.retail_v2beta.types.catalog import MerchantCenterLinkingConfig +from google.cloud.retail_v2beta.types.catalog import ProductLevelConfig +from google.cloud.retail_v2beta.types.catalog_service import AddCatalogAttributeRequest +from google.cloud.retail_v2beta.types.catalog_service import GetAttributesConfigRequest +from google.cloud.retail_v2beta.types.catalog_service import GetCompletionConfigRequest +from google.cloud.retail_v2beta.types.catalog_service import GetDefaultBranchRequest +from google.cloud.retail_v2beta.types.catalog_service import GetDefaultBranchResponse +from google.cloud.retail_v2beta.types.catalog_service import ListCatalogsRequest +from google.cloud.retail_v2beta.types.catalog_service import ListCatalogsResponse +from google.cloud.retail_v2beta.types.catalog_service import RemoveCatalogAttributeRequest +from google.cloud.retail_v2beta.types.catalog_service import ReplaceCatalogAttributeRequest +from google.cloud.retail_v2beta.types.catalog_service import SetDefaultBranchRequest +from google.cloud.retail_v2beta.types.catalog_service import UpdateAttributesConfigRequest +from google.cloud.retail_v2beta.types.catalog_service import UpdateCatalogRequest +from google.cloud.retail_v2beta.types.catalog_service import UpdateCompletionConfigRequest +from google.cloud.retail_v2beta.types.common import Audience +from google.cloud.retail_v2beta.types.common import ColorInfo +from google.cloud.retail_v2beta.types.common import Condition +from google.cloud.retail_v2beta.types.common import CustomAttribute +from google.cloud.retail_v2beta.types.common import FulfillmentInfo +from google.cloud.retail_v2beta.types.common import Image +from google.cloud.retail_v2beta.types.common import Interval +from google.cloud.retail_v2beta.types.common import LocalInventory +from google.cloud.retail_v2beta.types.common import PriceInfo +from google.cloud.retail_v2beta.types.common import Rating +from google.cloud.retail_v2beta.types.common import Rule +from google.cloud.retail_v2beta.types.common import UserInfo +from google.cloud.retail_v2beta.types.common import AttributeConfigLevel +from google.cloud.retail_v2beta.types.common import SearchSolutionUseCase +from google.cloud.retail_v2beta.types.common import SolutionType +from google.cloud.retail_v2beta.types.completion_service import CompleteQueryRequest +from google.cloud.retail_v2beta.types.completion_service import CompleteQueryResponse +from google.cloud.retail_v2beta.types.control import Control +from google.cloud.retail_v2beta.types.control_service import CreateControlRequest +from google.cloud.retail_v2beta.types.control_service import DeleteControlRequest +from google.cloud.retail_v2beta.types.control_service import GetControlRequest +from google.cloud.retail_v2beta.types.control_service import ListControlsRequest +from google.cloud.retail_v2beta.types.control_service import ListControlsResponse +from google.cloud.retail_v2beta.types.control_service import UpdateControlRequest +from google.cloud.retail_v2beta.types.export_config import ExportErrorsConfig +from google.cloud.retail_v2beta.types.export_config import ExportMetadata +from google.cloud.retail_v2beta.types.export_config import ExportProductsResponse +from google.cloud.retail_v2beta.types.export_config import ExportUserEventsResponse +from google.cloud.retail_v2beta.types.import_config import BigQuerySource +from google.cloud.retail_v2beta.types.import_config import CompletionDataInputConfig +from google.cloud.retail_v2beta.types.import_config import GcsSource +from google.cloud.retail_v2beta.types.import_config import ImportCompletionDataRequest +from google.cloud.retail_v2beta.types.import_config import ImportCompletionDataResponse +from google.cloud.retail_v2beta.types.import_config import ImportErrorsConfig +from google.cloud.retail_v2beta.types.import_config import ImportMetadata +from google.cloud.retail_v2beta.types.import_config import ImportProductsRequest +from google.cloud.retail_v2beta.types.import_config import ImportProductsResponse +from google.cloud.retail_v2beta.types.import_config import ImportUserEventsRequest +from google.cloud.retail_v2beta.types.import_config import ImportUserEventsResponse +from google.cloud.retail_v2beta.types.import_config import ProductInlineSource +from google.cloud.retail_v2beta.types.import_config import ProductInputConfig +from google.cloud.retail_v2beta.types.import_config import UserEventImportSummary +from google.cloud.retail_v2beta.types.import_config import UserEventInlineSource +from google.cloud.retail_v2beta.types.import_config import UserEventInputConfig +from google.cloud.retail_v2beta.types.prediction_service import PredictRequest +from google.cloud.retail_v2beta.types.prediction_service import PredictResponse +from google.cloud.retail_v2beta.types.product import Product +from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesMetadata +from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesRequest +from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesResponse +from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesMetadata +from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesRequest +from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesResponse +from google.cloud.retail_v2beta.types.product_service import CreateProductRequest +from google.cloud.retail_v2beta.types.product_service import DeleteProductRequest +from google.cloud.retail_v2beta.types.product_service import GetProductRequest +from google.cloud.retail_v2beta.types.product_service import ListProductsRequest +from google.cloud.retail_v2beta.types.product_service import ListProductsResponse +from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesMetadata +from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesRequest +from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesResponse +from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesMetadata +from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesRequest +from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesResponse +from google.cloud.retail_v2beta.types.product_service import SetInventoryMetadata +from google.cloud.retail_v2beta.types.product_service import SetInventoryRequest +from google.cloud.retail_v2beta.types.product_service import SetInventoryResponse +from google.cloud.retail_v2beta.types.product_service import UpdateProductRequest +from google.cloud.retail_v2beta.types.promotion import Promotion +from google.cloud.retail_v2beta.types.purge_config import PurgeMetadata +from google.cloud.retail_v2beta.types.purge_config import PurgeUserEventsRequest +from google.cloud.retail_v2beta.types.purge_config import PurgeUserEventsResponse +from google.cloud.retail_v2beta.types.search_service import SearchRequest +from google.cloud.retail_v2beta.types.search_service import SearchResponse +from google.cloud.retail_v2beta.types.serving_config import ServingConfig +from google.cloud.retail_v2beta.types.serving_config_service import AddControlRequest +from google.cloud.retail_v2beta.types.serving_config_service import CreateServingConfigRequest +from google.cloud.retail_v2beta.types.serving_config_service import DeleteServingConfigRequest +from google.cloud.retail_v2beta.types.serving_config_service import GetServingConfigRequest +from google.cloud.retail_v2beta.types.serving_config_service import ListServingConfigsRequest +from google.cloud.retail_v2beta.types.serving_config_service import ListServingConfigsResponse +from google.cloud.retail_v2beta.types.serving_config_service import RemoveControlRequest +from google.cloud.retail_v2beta.types.serving_config_service import UpdateServingConfigRequest +from google.cloud.retail_v2beta.types.user_event import CompletionDetail +from google.cloud.retail_v2beta.types.user_event import ProductDetail +from google.cloud.retail_v2beta.types.user_event import PurchaseTransaction +from google.cloud.retail_v2beta.types.user_event import UserEvent +from google.cloud.retail_v2beta.types.user_event_service import CollectUserEventRequest +from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsMetadata +from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsRequest +from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsResponse +from google.cloud.retail_v2beta.types.user_event_service import WriteUserEventRequest + +__all__ = ('CatalogServiceClient', + 'CatalogServiceAsyncClient', + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', + 'ControlServiceClient', + 'ControlServiceAsyncClient', + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', + 'ProductServiceClient', + 'ProductServiceAsyncClient', + 'SearchServiceClient', + 'SearchServiceAsyncClient', + 'ServingConfigServiceClient', + 'ServingConfigServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'AttributesConfig', + 'Catalog', + 'CatalogAttribute', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'ProductLevelConfig', + 'AddCatalogAttributeRequest', + 'GetAttributesConfigRequest', + 'GetCompletionConfigRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + 'SetDefaultBranchRequest', + 'UpdateAttributesConfigRequest', + 'UpdateCatalogRequest', + 'UpdateCompletionConfigRequest', + 'Audience', + 'ColorInfo', + 'Condition', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'Rule', + 'UserInfo', + 'AttributeConfigLevel', + 'SearchSolutionUseCase', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Control', + 'CreateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + 'UpdateControlRequest', + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'ServingConfig', + 'AddControlRequest', + 'CreateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'RemoveControlRequest', + 'UpdateServingConfigRequest', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail/py.typed b/owl-bot-staging/v2beta/google/cloud/retail/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py new file mode 100644 index 00000000..3ad83ab4 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.catalog_service import CatalogServiceClient +from .services.catalog_service import CatalogServiceAsyncClient +from .services.completion_service import CompletionServiceClient +from .services.completion_service import CompletionServiceAsyncClient +from .services.control_service import ControlServiceClient +from .services.control_service import ControlServiceAsyncClient +from .services.prediction_service import PredictionServiceClient +from .services.prediction_service import PredictionServiceAsyncClient +from .services.product_service import ProductServiceClient +from .services.product_service import ProductServiceAsyncClient +from .services.search_service import SearchServiceClient +from .services.search_service import SearchServiceAsyncClient +from .services.serving_config_service import ServingConfigServiceClient +from .services.serving_config_service import ServingConfigServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.catalog import AttributesConfig +from .types.catalog import Catalog +from .types.catalog import CatalogAttribute +from .types.catalog import CompletionConfig +from .types.catalog import MerchantCenterLink +from .types.catalog import MerchantCenterLinkingConfig +from .types.catalog import ProductLevelConfig +from .types.catalog_service import AddCatalogAttributeRequest +from .types.catalog_service import GetAttributesConfigRequest +from .types.catalog_service import GetCompletionConfigRequest +from .types.catalog_service import GetDefaultBranchRequest +from .types.catalog_service import GetDefaultBranchResponse +from .types.catalog_service import ListCatalogsRequest +from .types.catalog_service import ListCatalogsResponse +from .types.catalog_service import RemoveCatalogAttributeRequest +from .types.catalog_service import ReplaceCatalogAttributeRequest +from .types.catalog_service import SetDefaultBranchRequest +from .types.catalog_service import UpdateAttributesConfigRequest +from .types.catalog_service import UpdateCatalogRequest +from .types.catalog_service import UpdateCompletionConfigRequest +from .types.common import Audience +from .types.common import ColorInfo +from .types.common import Condition +from .types.common import CustomAttribute +from .types.common import FulfillmentInfo +from .types.common import Image +from .types.common import Interval +from .types.common import LocalInventory +from .types.common import PriceInfo +from .types.common import Rating +from .types.common import Rule +from .types.common import UserInfo +from .types.common import AttributeConfigLevel +from .types.common import SearchSolutionUseCase +from .types.common import SolutionType +from .types.completion_service import CompleteQueryRequest +from .types.completion_service import CompleteQueryResponse +from .types.control import Control +from .types.control_service import CreateControlRequest +from .types.control_service import DeleteControlRequest +from .types.control_service import GetControlRequest +from .types.control_service import ListControlsRequest +from .types.control_service import ListControlsResponse +from .types.control_service import UpdateControlRequest +from .types.export_config import ExportErrorsConfig +from .types.export_config import ExportMetadata +from .types.export_config import ExportProductsResponse +from .types.export_config import ExportUserEventsResponse +from .types.import_config import BigQuerySource +from .types.import_config import CompletionDataInputConfig +from .types.import_config import GcsSource +from .types.import_config import ImportCompletionDataRequest +from .types.import_config import ImportCompletionDataResponse +from .types.import_config import ImportErrorsConfig +from .types.import_config import ImportMetadata +from .types.import_config import ImportProductsRequest +from .types.import_config import ImportProductsResponse +from .types.import_config import ImportUserEventsRequest +from .types.import_config import ImportUserEventsResponse +from .types.import_config import ProductInlineSource +from .types.import_config import ProductInputConfig +from .types.import_config import UserEventImportSummary +from .types.import_config import UserEventInlineSource +from .types.import_config import UserEventInputConfig +from .types.prediction_service import PredictRequest +from .types.prediction_service import PredictResponse +from .types.product import Product +from .types.product_service import AddFulfillmentPlacesMetadata +from .types.product_service import AddFulfillmentPlacesRequest +from .types.product_service import AddFulfillmentPlacesResponse +from .types.product_service import AddLocalInventoriesMetadata +from .types.product_service import AddLocalInventoriesRequest +from .types.product_service import AddLocalInventoriesResponse +from .types.product_service import CreateProductRequest +from .types.product_service import DeleteProductRequest +from .types.product_service import GetProductRequest +from .types.product_service import ListProductsRequest +from .types.product_service import ListProductsResponse +from .types.product_service import RemoveFulfillmentPlacesMetadata +from .types.product_service import RemoveFulfillmentPlacesRequest +from .types.product_service import RemoveFulfillmentPlacesResponse +from .types.product_service import RemoveLocalInventoriesMetadata +from .types.product_service import RemoveLocalInventoriesRequest +from .types.product_service import RemoveLocalInventoriesResponse +from .types.product_service import SetInventoryMetadata +from .types.product_service import SetInventoryRequest +from .types.product_service import SetInventoryResponse +from .types.product_service import UpdateProductRequest +from .types.promotion import Promotion +from .types.purge_config import PurgeMetadata +from .types.purge_config import PurgeUserEventsRequest +from .types.purge_config import PurgeUserEventsResponse +from .types.search_service import SearchRequest +from .types.search_service import SearchResponse +from .types.serving_config import ServingConfig +from .types.serving_config_service import AddControlRequest +from .types.serving_config_service import CreateServingConfigRequest +from .types.serving_config_service import DeleteServingConfigRequest +from .types.serving_config_service import GetServingConfigRequest +from .types.serving_config_service import ListServingConfigsRequest +from .types.serving_config_service import ListServingConfigsResponse +from .types.serving_config_service import RemoveControlRequest +from .types.serving_config_service import UpdateServingConfigRequest +from .types.user_event import CompletionDetail +from .types.user_event import ProductDetail +from .types.user_event import PurchaseTransaction +from .types.user_event import UserEvent +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import RejoinUserEventsMetadata +from .types.user_event_service import RejoinUserEventsRequest +from .types.user_event_service import RejoinUserEventsResponse +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CatalogServiceAsyncClient', + 'CompletionServiceAsyncClient', + 'ControlServiceAsyncClient', + 'PredictionServiceAsyncClient', + 'ProductServiceAsyncClient', + 'SearchServiceAsyncClient', + 'ServingConfigServiceAsyncClient', + 'UserEventServiceAsyncClient', +'AddCatalogAttributeRequest', +'AddControlRequest', +'AddFulfillmentPlacesMetadata', +'AddFulfillmentPlacesRequest', +'AddFulfillmentPlacesResponse', +'AddLocalInventoriesMetadata', +'AddLocalInventoriesRequest', +'AddLocalInventoriesResponse', +'AttributeConfigLevel', +'AttributesConfig', +'Audience', +'BigQuerySource', +'Catalog', +'CatalogAttribute', +'CatalogServiceClient', +'CollectUserEventRequest', +'ColorInfo', +'CompleteQueryRequest', +'CompleteQueryResponse', +'CompletionConfig', +'CompletionDataInputConfig', +'CompletionDetail', +'CompletionServiceClient', +'Condition', +'Control', +'ControlServiceClient', +'CreateControlRequest', +'CreateProductRequest', +'CreateServingConfigRequest', +'CustomAttribute', +'DeleteControlRequest', +'DeleteProductRequest', +'DeleteServingConfigRequest', +'ExportErrorsConfig', +'ExportMetadata', +'ExportProductsResponse', +'ExportUserEventsResponse', +'FulfillmentInfo', +'GcsSource', +'GetAttributesConfigRequest', +'GetCompletionConfigRequest', +'GetControlRequest', +'GetDefaultBranchRequest', +'GetDefaultBranchResponse', +'GetProductRequest', +'GetServingConfigRequest', +'Image', +'ImportCompletionDataRequest', +'ImportCompletionDataResponse', +'ImportErrorsConfig', +'ImportMetadata', +'ImportProductsRequest', +'ImportProductsResponse', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'Interval', +'ListCatalogsRequest', +'ListCatalogsResponse', +'ListControlsRequest', +'ListControlsResponse', +'ListProductsRequest', +'ListProductsResponse', +'ListServingConfigsRequest', +'ListServingConfigsResponse', +'LocalInventory', +'MerchantCenterLink', +'MerchantCenterLinkingConfig', +'PredictRequest', +'PredictResponse', +'PredictionServiceClient', +'PriceInfo', +'Product', +'ProductDetail', +'ProductInlineSource', +'ProductInputConfig', +'ProductLevelConfig', +'ProductServiceClient', +'Promotion', +'PurchaseTransaction', +'PurgeMetadata', +'PurgeUserEventsRequest', +'PurgeUserEventsResponse', +'Rating', +'RejoinUserEventsMetadata', +'RejoinUserEventsRequest', +'RejoinUserEventsResponse', +'RemoveCatalogAttributeRequest', +'RemoveControlRequest', +'RemoveFulfillmentPlacesMetadata', +'RemoveFulfillmentPlacesRequest', +'RemoveFulfillmentPlacesResponse', +'RemoveLocalInventoriesMetadata', +'RemoveLocalInventoriesRequest', +'RemoveLocalInventoriesResponse', +'ReplaceCatalogAttributeRequest', +'Rule', +'SearchRequest', +'SearchResponse', +'SearchServiceClient', +'SearchSolutionUseCase', +'ServingConfig', +'ServingConfigServiceClient', +'SetDefaultBranchRequest', +'SetInventoryMetadata', +'SetInventoryRequest', +'SetInventoryResponse', +'SolutionType', +'UpdateAttributesConfigRequest', +'UpdateCatalogRequest', +'UpdateCompletionConfigRequest', +'UpdateControlRequest', +'UpdateProductRequest', +'UpdateServingConfigRequest', +'UserEvent', +'UserEventImportSummary', +'UserEventInlineSource', +'UserEventInputConfig', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json new file mode 100644 index 00000000..bf3205b9 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json @@ -0,0 +1,551 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.retail_v2beta", + "protoPackage": "google.cloud.retail.v2beta", + "schema": "1.0", + "services": { + "CatalogService": { + "clients": { + "grpc": { + "libraryClient": "CatalogServiceClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "add_catalog_attribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "get_attributes_config" + ] + }, + "GetCompletionConfig": { + "methods": [ + "get_completion_config" + ] + }, + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "remove_catalog_attribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "replace_catalog_attribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "update_attributes_config" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "update_completion_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CatalogServiceAsyncClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "add_catalog_attribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "get_attributes_config" + ] + }, + "GetCompletionConfig": { + "methods": [ + "get_completion_config" + ] + }, + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "remove_catalog_attribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "replace_catalog_attribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "update_attributes_config" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "update_completion_config" + ] + } + } + } + } + }, + "CompletionService": { + "clients": { + "grpc": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CompletionServiceAsyncClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + } + } + }, + "ControlService": { + "clients": { + "grpc": { + "libraryClient": "ControlServiceClient", + "rpcs": { + "CreateControl": { + "methods": [ + "create_control" + ] + }, + "DeleteControl": { + "methods": [ + "delete_control" + ] + }, + "GetControl": { + "methods": [ + "get_control" + ] + }, + "ListControls": { + "methods": [ + "list_controls" + ] + }, + "UpdateControl": { + "methods": [ + "update_control" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ControlServiceAsyncClient", + "rpcs": { + "CreateControl": { + "methods": [ + "create_control" + ] + }, + "DeleteControl": { + "methods": [ + "delete_control" + ] + }, + "GetControl": { + "methods": [ + "get_control" + ] + }, + "ListControls": { + "methods": [ + "list_controls" + ] + }, + "UpdateControl": { + "methods": [ + "update_control" + ] + } + } + } + } + }, + "PredictionService": { + "clients": { + "grpc": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionServiceAsyncClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + } + } + }, + "ProductService": { + "clients": { + "grpc": { + "libraryClient": "ProductServiceClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductServiceAsyncClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + } + } + }, + "SearchService": { + "clients": { + "grpc": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SearchServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + }, + "ServingConfigService": { + "clients": { + "grpc": { + "libraryClient": "ServingConfigServiceClient", + "rpcs": { + "AddControl": { + "methods": [ + "add_control" + ] + }, + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, + "RemoveControl": { + "methods": [ + "remove_control" + ] + }, + "UpdateServingConfig": { + "methods": [ + "update_serving_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServingConfigServiceAsyncClient", + "rpcs": { + "AddControl": { + "methods": [ + "add_control" + ] + }, + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, + "RemoveControl": { + "methods": [ + "remove_control" + ] + }, + "UpdateServingConfig": { + "methods": [ + "update_serving_config" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py new file mode 100644 index 00000000..d276b897 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CatalogServiceClient +from .async_client import CatalogServiceAsyncClient + +__all__ = ( + 'CatalogServiceClient', + 'CatalogServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py new file mode 100644 index 00000000..dfff033b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py @@ -0,0 +1,1350 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.catalog_service import pagers +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport +from .client import CatalogServiceClient + + +class CatalogServiceAsyncClient: + """Service for managing catalog configuration.""" + + _client: CatalogServiceClient + + DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT + + attributes_config_path = staticmethod(CatalogServiceClient.attributes_config_path) + parse_attributes_config_path = staticmethod(CatalogServiceClient.parse_attributes_config_path) + branch_path = staticmethod(CatalogServiceClient.branch_path) + parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) + catalog_path = staticmethod(CatalogServiceClient.catalog_path) + parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) + completion_config_path = staticmethod(CatalogServiceClient.completion_config_path) + parse_completion_config_path = staticmethod(CatalogServiceClient.parse_completion_config_path) + common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CatalogServiceClient.common_project_path) + parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) + common_location_path = staticmethod(CatalogServiceClient.common_location_path) + parse_common_location_path = staticmethod(CatalogServiceClient.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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CatalogServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsAsyncPager: + r"""Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_list_catalogs(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + parent (:class:`str`): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2beta.Catalog]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.retail_v2beta.services.catalog_service.pagers.ListCatalogsAsyncPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.ListCatalogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_catalogs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCatalogsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_catalog(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2beta.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2beta.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] + method. + catalog (:class:`google.cloud.retail_v2beta.types.Catalog`): + Required. The + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2beta.Catalog], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Catalog][google.cloud.retail.v2beta.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_catalog, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_set_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (:class:`str`): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.SetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (:class:`str`): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # 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_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_completion_config(self, + request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Gets a + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] + method. + name (:class:`str`): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + + 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.retail_v2beta.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetCompletionConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_completion_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_completion_config(self, + request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, + *, + completion_config: catalog.CompletionConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Updates the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + completion_config = retail_v2beta.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2beta.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = await client.update_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] + method. + completion_config (:class:`google.cloud.retail_v2beta.types.CompletionConfig`): + Required. The + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``completion_config`` 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 + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([completion_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCompletionConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if completion_config is not None: + request.completion_config = completion_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_completion_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("completion_config.name", request.completion_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_attributes_config(self, + request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Gets an + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] + method. + name (:class:`str`): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + + 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.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetAttributesConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_attributes_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_attributes_config(self, + request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, + *, + attributes_config: catalog.AttributesConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Updates the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + attributes_config = retail_v2beta.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2beta.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = await client.update_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] + method. + attributes_config (:class:`google.cloud.retail_v2beta.types.AttributesConfig`): + Required. The + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. + + This corresponds to the ``attributes_config`` 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 + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attributes_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateAttributesConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attributes_config is not None: + request.attributes_config = attributes_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_attributes_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config.name", request.attributes_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_catalog_attribute(self, + request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Adds the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_add_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.AddCatalogAttributeRequest(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.add_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_catalog_attribute(self, + request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Removes the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = await client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.RemoveCatalogAttributeRequest(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.remove_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def replace_catalog_attribute(self, + request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Replaces the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.ReplaceCatalogAttributeRequest(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.replace_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py new file mode 100644 index 00000000..bae42088 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py @@ -0,0 +1,1579 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.catalog_service import pagers +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CatalogServiceGrpcTransport +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +class CatalogServiceClientMeta(type): + """Metaclass for the CatalogService 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[CatalogServiceTransport]] + _transport_registry["grpc"] = CatalogServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CatalogServiceTransport]: + """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): + """Service for managing catalog configuration.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CatalogServiceClient: 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: + CatalogServiceClient: 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) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def attributes_config_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified attributes_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_attributes_config_path(path: str) -> Dict[str,str]: + """Parses a attributes_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/attributesConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def completion_config_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified completion_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_completion_config_path(path: str) -> Dict[str,str]: + """Parses a completion_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/completionConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CatalogServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CatalogServiceTransport): + # transport is a CatalogServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsPager: + r"""Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_list_catalogs(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2beta.Catalog]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.retail_v2beta.services.catalog_service.pagers.ListCatalogsPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ListCatalogsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ListCatalogsRequest): + request = catalog_service.ListCatalogsRequest(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_catalogs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCatalogsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_catalog(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2beta.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2beta.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] + method. + catalog (google.cloud.retail_v2beta.types.Catalog): + Required. The + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2beta.Catalog], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Catalog][google.cloud.retail.v2beta.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCatalogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCatalogRequest): + request = catalog_service.UpdateCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + 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_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_set_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.SetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.SetDefaultBranchRequest): + request = catalog_service.SetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetDefaultBranchRequest): + request = catalog_service.GetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_completion_config(self, + request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Gets a + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] + method. + name (str): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + + 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.retail_v2beta.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetCompletionConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetCompletionConfigRequest): + request = catalog_service.GetCompletionConfigRequest(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_completion_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_completion_config(self, + request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, + *, + completion_config: catalog.CompletionConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Updates the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + completion_config = retail_v2beta.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2beta.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = client.update_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] + method. + completion_config (google.cloud.retail_v2beta.types.CompletionConfig): + Required. The + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``completion_config`` 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 + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([completion_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCompletionConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCompletionConfigRequest): + request = catalog_service.UpdateCompletionConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if completion_config is not None: + request.completion_config = completion_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_completion_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("completion_config.name", request.completion_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_attributes_config(self, + request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Gets an + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] + method. + name (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + + 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.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetAttributesConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetAttributesConfigRequest): + request = catalog_service.GetAttributesConfigRequest(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_attributes_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_attributes_config(self, + request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, + *, + attributes_config: catalog.AttributesConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Updates the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + attributes_config = retail_v2beta.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2beta.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = client.update_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] + method. + attributes_config (google.cloud.retail_v2beta.types.AttributesConfig): + Required. The + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. + + This corresponds to the ``attributes_config`` 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 + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attributes_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateAttributesConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateAttributesConfigRequest): + request = catalog_service.UpdateAttributesConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attributes_config is not None: + request.attributes_config = attributes_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_attributes_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config.name", request.attributes_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_catalog_attribute(self, + request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Adds the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_add_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.AddCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.AddCatalogAttributeRequest): + request = catalog_service.AddCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_catalog_attribute(self, + request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Removes the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.RemoveCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.RemoveCatalogAttributeRequest): + request = catalog_service.RemoveCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def replace_catalog_attribute(self, + request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Replaces the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ReplaceCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ReplaceCatalogAttributeRequest): + request = catalog_service.ReplaceCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.replace_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py new file mode 100644 index 00000000..0ca25546 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog_service + + +class ListCatalogsPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` + 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[..., catalog_service.ListCatalogsResponse], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2beta.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + for page in self.pages: + yield from page.catalogs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCatalogsAsyncPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` + 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[catalog_service.ListCatalogsResponse]], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2beta.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + async def async_generator(): + async for page in self.pages: + for response in page.catalogs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py new file mode 100644 index 00000000..0cffa336 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 CatalogServiceTransport +from .grpc import CatalogServiceGrpcTransport +from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] +_transport_registry['grpc'] = CatalogServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport + +__all__ = ( + 'CatalogServiceTransport', + 'CatalogServiceGrpcTransport', + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py new file mode 100644 index 00000000..dfced0db --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py @@ -0,0 +1,293 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CatalogServiceTransport(abc.ABC): + """Abstract transport class for CatalogService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_catalogs: gapic_v1.method.wrap_method( + self.list_catalogs, + default_timeout=None, + client_info=client_info, + ), + self.update_catalog: gapic_v1.method.wrap_method( + self.update_catalog, + default_timeout=None, + client_info=client_info, + ), + self.set_default_branch: gapic_v1.method.wrap_method( + self.set_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_default_branch: gapic_v1.method.wrap_method( + self.get_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_completion_config: gapic_v1.method.wrap_method( + self.get_completion_config, + default_timeout=None, + client_info=client_info, + ), + self.update_completion_config: gapic_v1.method.wrap_method( + self.update_completion_config, + default_timeout=None, + client_info=client_info, + ), + self.get_attributes_config: gapic_v1.method.wrap_method( + self.get_attributes_config, + default_timeout=None, + client_info=client_info, + ), + self.update_attributes_config: gapic_v1.method.wrap_method( + self.update_attributes_config, + default_timeout=None, + client_info=client_info, + ), + self.add_catalog_attribute: gapic_v1.method.wrap_method( + self.add_catalog_attribute, + default_timeout=None, + client_info=client_info, + ), + self.remove_catalog_attribute: gapic_v1.method.wrap_method( + self.remove_catalog_attribute, + default_timeout=None, + client_info=client_info, + ), + self.replace_catalog_attribute: gapic_v1.method.wrap_method( + self.replace_catalog_attribute, + 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Union[ + catalog_service.ListCatalogsResponse, + Awaitable[catalog_service.ListCatalogsResponse] + ]]: + raise NotImplementedError() + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Union[ + gcr_catalog.Catalog, + Awaitable[gcr_catalog.Catalog] + ]]: + raise NotImplementedError() + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Union[ + catalog_service.GetDefaultBranchResponse, + Awaitable[catalog_service.GetDefaultBranchResponse] + ]]: + raise NotImplementedError() + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + Union[ + catalog.CompletionConfig, + Awaitable[catalog.CompletionConfig] + ]]: + raise NotImplementedError() + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + Union[ + catalog.CompletionConfig, + Awaitable[catalog.CompletionConfig] + ]]: + raise NotImplementedError() + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CatalogServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py new file mode 100644 index 00000000..0f431d97 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py @@ -0,0 +1,598 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO + + +class CatalogServiceGrpcTransport(CatalogServiceTransport): + """gRPC backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + catalog_service.ListCatalogsResponse]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + ~.ListCatalogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + gcr_catalog.Catalog]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + ~.Catalog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + empty_pb2.Empty]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + ~.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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + catalog_service.GetDefaultBranchResponse]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + ~.GetDefaultBranchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + catalog.CompletionConfig]: + r"""Return a callable for the get completion config method over gRPC. + + Gets a + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. + + Returns: + Callable[[~.GetCompletionConfigRequest], + ~.CompletionConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetCompletionConfig', + request_serializer=catalog_service.GetCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['get_completion_config'] + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + catalog.CompletionConfig]: + r"""Return a callable for the update completion config method over gRPC. + + Updates the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. + + Returns: + Callable[[~.UpdateCompletionConfigRequest], + ~.CompletionConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateCompletionConfig', + request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['update_completion_config'] + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + catalog.AttributesConfig]: + r"""Return a callable for the get attributes config method over gRPC. + + Gets an + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + Returns: + Callable[[~.GetAttributesConfigRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetAttributesConfig', + request_serializer=catalog_service.GetAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['get_attributes_config'] + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + catalog.AttributesConfig]: + r"""Return a callable for the update attributes config method over gRPC. + + Updates the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + Returns: + Callable[[~.UpdateAttributesConfigRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateAttributesConfig', + request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['update_attributes_config'] + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the add catalog attribute method over gRPC. + + Adds the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.AddCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_catalog_attribute' not in self._stubs: + self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/AddCatalogAttribute', + request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['add_catalog_attribute'] + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the remove catalog attribute method over gRPC. + + Removes the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.RemoveCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_catalog_attribute' not in self._stubs: + self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/RemoveCatalogAttribute', + request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['remove_catalog_attribute'] + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the replace catalog attribute method over gRPC. + + Replaces the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.ReplaceCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_catalog_attribute' not in self._stubs: + self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/ReplaceCatalogAttribute', + request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['replace_catalog_attribute'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CatalogServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..ca9f808e --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py @@ -0,0 +1,597 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CatalogServiceGrpcTransport + + +class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): + """gRPC AsyncIO backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Awaitable[catalog_service.ListCatalogsResponse]]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + Awaitable[~.ListCatalogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Awaitable[gcr_catalog.Catalog]]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + Awaitable[~.Catalog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + 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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Awaitable[catalog_service.GetDefaultBranchResponse]]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + Awaitable[~.GetDefaultBranchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + Awaitable[catalog.CompletionConfig]]: + r"""Return a callable for the get completion config method over gRPC. + + Gets a + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. + + Returns: + Callable[[~.GetCompletionConfigRequest], + Awaitable[~.CompletionConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetCompletionConfig', + request_serializer=catalog_service.GetCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['get_completion_config'] + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + Awaitable[catalog.CompletionConfig]]: + r"""Return a callable for the update completion config method over gRPC. + + Updates the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. + + Returns: + Callable[[~.UpdateCompletionConfigRequest], + Awaitable[~.CompletionConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateCompletionConfig', + request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['update_completion_config'] + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the get attributes config method over gRPC. + + Gets an + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + Returns: + Callable[[~.GetAttributesConfigRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetAttributesConfig', + request_serializer=catalog_service.GetAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['get_attributes_config'] + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the update attributes config method over gRPC. + + Updates the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + Returns: + Callable[[~.UpdateAttributesConfigRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateAttributesConfig', + request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['update_attributes_config'] + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the add catalog attribute method over gRPC. + + Adds the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.AddCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_catalog_attribute' not in self._stubs: + self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/AddCatalogAttribute', + request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['add_catalog_attribute'] + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the remove catalog attribute method over gRPC. + + Removes the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.RemoveCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_catalog_attribute' not in self._stubs: + self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/RemoveCatalogAttribute', + request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['remove_catalog_attribute'] + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the replace catalog attribute method over gRPC. + + Replaces the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.ReplaceCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_catalog_attribute' not in self._stubs: + self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/ReplaceCatalogAttribute', + request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['replace_catalog_attribute'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py new file mode 100644 index 00000000..b8af95bd --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CompletionServiceClient +from .async_client import CompletionServiceAsyncClient + +__all__ = ( + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py new file mode 100644 index 00000000..66c91320 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .client import CompletionServiceClient + + +class CompletionServiceAsyncClient: + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: CompletionServiceClient + + DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(CompletionServiceClient.catalog_path) + parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) + common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CompletionServiceClient.common_project_path) + parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) + common_location_path = staticmethod(CompletionServiceClient.common_location_path) + parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CompletionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_complete_query(): + # Create a client + client = retail_v2beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_query, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_import_completion_data(): + # Create a client + client = retail_v2beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2beta.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. + 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. + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_completion_data, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py new file mode 100644 index 00000000..9652a4f0 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py @@ -0,0 +1,592 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CompletionServiceGrpcTransport +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +class CompletionServiceClientMeta(type): + """Metaclass for the CompletionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] + _transport_registry["grpc"] = CompletionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CompletionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CompletionServiceClient(metaclass=CompletionServiceClientMeta): + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CompletionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CompletionServiceTransport): + # transport is a CompletionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_complete_query(): + # Create a client + client = retail_v2beta.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a completion_service.CompleteQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, completion_service.CompleteQueryRequest): + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_import_completion_data(): + # Create a client + client = retail_v2beta.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2beta.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. + 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. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportCompletionDataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportCompletionDataRequest): + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_completion_data] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py new file mode 100644 index 00000000..a0c9542f --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CompletionServiceTransport +from .grpc import CompletionServiceGrpcTransport +from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] +_transport_registry['grpc'] = CompletionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport + +__all__ = ( + 'CompletionServiceTransport', + 'CompletionServiceGrpcTransport', + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py new file mode 100644 index 00000000..464b0bad --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CompletionServiceTransport(abc.ABC): + """Abstract transport class for CompletionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.complete_query: gapic_v1.method.wrap_method( + self.complete_query, + default_timeout=None, + client_info=client_info, + ), + self.import_completion_data: gapic_v1.method.wrap_method( + self.import_completion_data, + 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Union[ + completion_service.CompleteQueryResponse, + Awaitable[completion_service.CompleteQueryResponse] + ]]: + raise NotImplementedError() + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CompletionServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py new file mode 100644 index 00000000..916e8bec --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py @@ -0,0 +1,323 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO + + +class CompletionServiceGrpcTransport(CompletionServiceTransport): + """gRPC backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + ~.CompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + operations_pb2.Operation]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CompletionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..b8d0ffbd --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py @@ -0,0 +1,322 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CompletionServiceGrpcTransport + + +class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): + """gRPC AsyncIO backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Awaitable[completion_service.CompleteQueryResponse]]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + Awaitable[~.CompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + 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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py new file mode 100644 index 00000000..e9a7be2f --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ControlServiceClient +from .async_client import ControlServiceAsyncClient + +__all__ = ( + 'ControlServiceClient', + 'ControlServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py new file mode 100644 index 00000000..5d3cfeb7 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py @@ -0,0 +1,742 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.control_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.cloud.retail_v2beta.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport +from .client import ControlServiceClient + + +class ControlServiceAsyncClient: + """Service for modifying Control.""" + + _client: ControlServiceClient + + DEFAULT_ENDPOINT = ControlServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ControlServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(ControlServiceClient.catalog_path) + parse_catalog_path = staticmethod(ControlServiceClient.parse_catalog_path) + control_path = staticmethod(ControlServiceClient.control_path) + parse_control_path = staticmethod(ControlServiceClient.parse_control_path) + common_billing_account_path = staticmethod(ControlServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ControlServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ControlServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ControlServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ControlServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ControlServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ControlServiceClient.common_project_path) + parse_common_project_path = staticmethod(ControlServiceClient.parse_common_project_path) + common_location_path = staticmethod(ControlServiceClient.common_location_path) + parse_common_location_path = staticmethod(ControlServiceClient.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: + ControlServiceAsyncClient: The constructed client. + """ + return ControlServiceClient.from_service_account_info.__func__(ControlServiceAsyncClient, 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: + ControlServiceAsyncClient: The constructed client. + """ + return ControlServiceClient.from_service_account_file.__func__(ControlServiceAsyncClient, 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 variabel 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 ControlServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ControlServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ControlServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ControlServiceClient).get_transport_class, type(ControlServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ControlServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the control service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ControlServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ControlServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_control(self, + request: Union[control_service.CreateControlRequest, dict] = None, + *, + parent: str = None, + control: gcr_control.Control = None, + control_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Creates a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_create_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = await client.create_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateControlRequest, dict]): + The request object. Request for CreateControl method. + parent (:class:`str`): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control (:class:`google.cloud.retail_v2beta.types.Control`): + Required. The Control to create. + This corresponds to the ``control`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control_id (:class:`str`): + Required. The ID to use for the Control, which will + become the final component of the Control's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``control_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.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, control, control_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.CreateControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if control is not None: + request.control = control + if control_id is not None: + request.control_id = control_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_control(self, + request: Union[control_service.DeleteControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_delete_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteControlRequest( + name="name_value", + ) + + # Make the request + await client.delete_control(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteControlRequest, dict]): + The request object. Request for DeleteControl method. + name (:class:`str`): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.DeleteControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_control(self, + request: Union[control_service.UpdateControlRequest, dict] = None, + *, + control: gcr_control.Control = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Updates a Control. + + [Control][google.cloud.retail.v2beta.Control] cannot be set to a + different oneof field, if so an INVALID_ARGUMENT is returned. If + the [Control][google.cloud.retail.v2beta.Control] to delete does + not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateControlRequest( + control=control, + ) + + # Make the request + response = await client.update_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateControlRequest, dict]): + The request object. Request for UpdateControl method. + control (:class:`google.cloud.retail_v2beta.types.Control`): + Required. The Control to update. + This corresponds to the ``control`` 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 + [Control][google.cloud.retail.v2beta.Control] to update. + The following are NOT supported: + + - [Control.name][google.cloud.retail.v2beta.Control.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([control, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.UpdateControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if control is not None: + request.control = control + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("control.name", request.control.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_control(self, + request: Union[control_service.GetControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> control.Control: + r"""Gets a Control. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetControlRequest( + name="name_value", + ) + + # Make the request + response = await client.get_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetControlRequest, dict]): + The request object. Request for GetControl method. + name (:class:`str`): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.GetControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_controls(self, + request: Union[control_service.ListControlsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListControlsAsyncPager: + r"""Lists all Controls linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_list_controls(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListControlsRequest, dict]): + The request object. Request for ListControls method. + parent (:class:`str`): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.control_service.pagers.ListControlsAsyncPager: + Response for ListControls method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.ListControlsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_controls, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListControlsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ControlServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py new file mode 100644 index 00000000..39e7a70e --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py @@ -0,0 +1,950 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.control_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.cloud.retail_v2beta.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ControlServiceGrpcTransport +from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport + + +class ControlServiceClientMeta(type): + """Metaclass for the ControlService 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[ControlServiceTransport]] + _transport_registry["grpc"] = ControlServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ControlServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ControlServiceTransport]: + """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 ControlServiceClient(metaclass=ControlServiceClientMeta): + """Service for modifying Control.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ControlServiceClient: 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: + ControlServiceClient: 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) -> ControlServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ControlServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def control_path(project: str,location: str,catalog: str,control: str,) -> str: + """Returns a fully-qualified control string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) + + @staticmethod + def parse_control_path(path: str) -> Dict[str,str]: + """Parses a control path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/controls/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ControlServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the control service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ControlServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ControlServiceTransport): + # transport is a ControlServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_control(self, + request: Union[control_service.CreateControlRequest, dict] = None, + *, + parent: str = None, + control: gcr_control.Control = None, + control_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Creates a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_create_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = client.create_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateControlRequest, dict]): + The request object. Request for CreateControl method. + parent (str): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control (google.cloud.retail_v2beta.types.Control): + Required. The Control to create. + This corresponds to the ``control`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control_id (str): + Required. The ID to use for the Control, which will + become the final component of the Control's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``control_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.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, control, control_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.CreateControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.CreateControlRequest): + request = control_service.CreateControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if control is not None: + request.control = control + if control_id is not None: + request.control_id = control_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_control(self, + request: Union[control_service.DeleteControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_delete_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteControlRequest( + name="name_value", + ) + + # Make the request + client.delete_control(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteControlRequest, dict]): + The request object. Request for DeleteControl method. + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.DeleteControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.DeleteControlRequest): + request = control_service.DeleteControlRequest(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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_control(self, + request: Union[control_service.UpdateControlRequest, dict] = None, + *, + control: gcr_control.Control = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Updates a Control. + + [Control][google.cloud.retail.v2beta.Control] cannot be set to a + different oneof field, if so an INVALID_ARGUMENT is returned. If + the [Control][google.cloud.retail.v2beta.Control] to delete does + not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateControlRequest( + control=control, + ) + + # Make the request + response = client.update_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateControlRequest, dict]): + The request object. Request for UpdateControl method. + control (google.cloud.retail_v2beta.types.Control): + Required. The Control to update. + This corresponds to the ``control`` 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 + [Control][google.cloud.retail.v2beta.Control] to update. + The following are NOT supported: + + - [Control.name][google.cloud.retail.v2beta.Control.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([control, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.UpdateControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.UpdateControlRequest): + request = control_service.UpdateControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if control is not None: + request.control = control + 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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("control.name", request.control.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_control(self, + request: Union[control_service.GetControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> control.Control: + r"""Gets a Control. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetControlRequest( + name="name_value", + ) + + # Make the request + response = client.get_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetControlRequest, dict]): + The request object. Request for GetControl method. + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.GetControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.GetControlRequest): + request = control_service.GetControlRequest(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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_controls(self, + request: Union[control_service.ListControlsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListControlsPager: + r"""Lists all Controls linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_list_controls(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListControlsRequest, dict]): + The request object. Request for ListControls method. + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.control_service.pagers.ListControlsPager: + Response for ListControls method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.ListControlsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.ListControlsRequest): + request = control_service.ListControlsRequest(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_controls] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListControlsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ControlServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py new file mode 100644 index 00000000..f51a3970 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control_service + + +class ListControlsPager: + """A pager for iterating through ``list_controls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListControlsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``controls`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListControls`` requests and continue to iterate + through the ``controls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListControlsResponse` + 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[..., control_service.ListControlsResponse], + request: control_service.ListControlsRequest, + response: control_service.ListControlsResponse, + *, + 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.retail_v2beta.types.ListControlsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListControlsResponse): + 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 = control_service.ListControlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[control_service.ListControlsResponse]: + 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[control.Control]: + for page in self.pages: + yield from page.controls + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListControlsAsyncPager: + """A pager for iterating through ``list_controls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListControlsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``controls`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListControls`` requests and continue to iterate + through the ``controls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListControlsResponse` + 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[control_service.ListControlsResponse]], + request: control_service.ListControlsRequest, + response: control_service.ListControlsResponse, + *, + 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.retail_v2beta.types.ListControlsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListControlsResponse): + 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 = control_service.ListControlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[control_service.ListControlsResponse]: + 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[control.Control]: + async def async_generator(): + async for page in self.pages: + for response in page.controls: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py new file mode 100644 index 00000000..3622876b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ControlServiceTransport +from .grpc import ControlServiceGrpcTransport +from .grpc_asyncio import ControlServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ControlServiceTransport]] +_transport_registry['grpc'] = ControlServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ControlServiceGrpcAsyncIOTransport + +__all__ = ( + 'ControlServiceTransport', + 'ControlServiceGrpcTransport', + 'ControlServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py new file mode 100644 index 00000000..3c75d59f --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py @@ -0,0 +1,209 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ControlServiceTransport(abc.ABC): + """Abstract transport class for ControlService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_control: gapic_v1.method.wrap_method( + self.create_control, + default_timeout=None, + client_info=client_info, + ), + self.delete_control: gapic_v1.method.wrap_method( + self.delete_control, + default_timeout=None, + client_info=client_info, + ), + self.update_control: gapic_v1.method.wrap_method( + self.update_control, + default_timeout=None, + client_info=client_info, + ), + self.get_control: gapic_v1.method.wrap_method( + self.get_control, + default_timeout=None, + client_info=client_info, + ), + self.list_controls: gapic_v1.method.wrap_method( + self.list_controls, + 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 create_control(self) -> Callable[ + [control_service.CreateControlRequest], + Union[ + gcr_control.Control, + Awaitable[gcr_control.Control] + ]]: + raise NotImplementedError() + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + Union[ + gcr_control.Control, + Awaitable[gcr_control.Control] + ]]: + raise NotImplementedError() + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + Union[ + control.Control, + Awaitable[control.Control] + ]]: + raise NotImplementedError() + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + Union[ + control_service.ListControlsResponse, + Awaitable[control_service.ListControlsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ControlServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py new file mode 100644 index 00000000..33482592 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py @@ -0,0 +1,380 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO + + +class ControlServiceGrpcTransport(ControlServiceTransport): + """gRPC backend transport for ControlService. + + Service for modifying Control. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_control(self) -> Callable[ + [control_service.CreateControlRequest], + gcr_control.Control]: + r"""Return a callable for the create control method over gRPC. + + Creates a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['create_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/CreateControl', + request_serializer=control_service.CreateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['create_control'] + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete control method over gRPC. + + Deletes a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteControlRequest], + ~.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_control' not in self._stubs: + self._stubs['delete_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/DeleteControl', + request_serializer=control_service.DeleteControlRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_control'] + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + gcr_control.Control]: + r"""Return a callable for the update control method over gRPC. + + Updates a Control. + + [Control][google.cloud.retail.v2beta.Control] cannot be set to a + different oneof field, if so an INVALID_ARGUMENT is returned. If + the [Control][google.cloud.retail.v2beta.Control] to delete does + not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['update_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/UpdateControl', + request_serializer=control_service.UpdateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['update_control'] + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + control.Control]: + r"""Return a callable for the get control method over gRPC. + + Gets a Control. + + Returns: + Callable[[~.GetControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['get_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/GetControl', + request_serializer=control_service.GetControlRequest.serialize, + response_deserializer=control.Control.deserialize, + ) + return self._stubs['get_control'] + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + control_service.ListControlsResponse]: + r"""Return a callable for the list controls method over gRPC. + + Lists all Controls linked to this catalog. + + Returns: + Callable[[~.ListControlsRequest], + ~.ListControlsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_controls' not in self._stubs: + self._stubs['list_controls'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/ListControls', + request_serializer=control_service.ListControlsRequest.serialize, + response_deserializer=control_service.ListControlsResponse.deserialize, + ) + return self._stubs['list_controls'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ControlServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..2696c131 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py @@ -0,0 +1,379 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ControlServiceGrpcTransport + + +class ControlServiceGrpcAsyncIOTransport(ControlServiceTransport): + """gRPC AsyncIO backend transport for ControlService. + + Service for modifying Control. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_control(self) -> Callable[ + [control_service.CreateControlRequest], + Awaitable[gcr_control.Control]]: + r"""Return a callable for the create control method over gRPC. + + Creates a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['create_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/CreateControl', + request_serializer=control_service.CreateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['create_control'] + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete control method over gRPC. + + Deletes a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteControlRequest], + 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_control' not in self._stubs: + self._stubs['delete_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/DeleteControl', + request_serializer=control_service.DeleteControlRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_control'] + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + Awaitable[gcr_control.Control]]: + r"""Return a callable for the update control method over gRPC. + + Updates a Control. + + [Control][google.cloud.retail.v2beta.Control] cannot be set to a + different oneof field, if so an INVALID_ARGUMENT is returned. If + the [Control][google.cloud.retail.v2beta.Control] to delete does + not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['update_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/UpdateControl', + request_serializer=control_service.UpdateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['update_control'] + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + Awaitable[control.Control]]: + r"""Return a callable for the get control method over gRPC. + + Gets a Control. + + Returns: + Callable[[~.GetControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['get_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/GetControl', + request_serializer=control_service.GetControlRequest.serialize, + response_deserializer=control.Control.deserialize, + ) + return self._stubs['get_control'] + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + Awaitable[control_service.ListControlsResponse]]: + r"""Return a callable for the list controls method over gRPC. + + Lists all Controls linked to this catalog. + + Returns: + Callable[[~.ListControlsRequest], + Awaitable[~.ListControlsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_controls' not in self._stubs: + self._stubs['list_controls'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/ListControls', + request_serializer=control_service.ListControlsRequest.serialize, + response_deserializer=control_service.ListControlsResponse.deserialize, + ) + return self._stubs['list_controls'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ControlServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py new file mode 100644 index 00000000..7c079c80 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import PredictionServiceClient +from .async_client import PredictionServiceAsyncClient + +__all__ = ( + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py new file mode 100644 index 00000000..d8a1a148 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport +from .client import PredictionServiceClient + + +class PredictionServiceAsyncClient: + """Service for making recommendation prediction.""" + + _client: PredictionServiceClient + + DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT + + product_path = staticmethod(PredictionServiceClient.product_path) + parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) + common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(PredictionServiceClient.common_project_path) + parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) + common_location_path = staticmethod(PredictionServiceClient.common_location_path) + parse_common_location_path = staticmethod(PredictionServiceClient.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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PredictionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_predict(): + # Create a client + client = retail_v2beta.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + request = prediction_service.PredictRequest(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.predict, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py new file mode 100644 index 00000000..458e6650 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py @@ -0,0 +1,479 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionServiceGrpcTransport +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +class PredictionServiceClientMeta(type): + """Metaclass for the PredictionService 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[PredictionServiceTransport]] + _transport_registry["grpc"] = PredictionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PredictionServiceTransport]: + """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): + """Service for making recommendation prediction.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PredictionServiceClient: 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: + PredictionServiceClient: 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) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PredictionServiceTransport): + # transport is a PredictionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_predict(): + # Create a client + client = retail_v2beta.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a prediction_service.PredictRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_service.PredictRequest): + request = prediction_service.PredictRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.predict] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py new file mode 100644 index 00000000..bb65c664 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PredictionServiceTransport +from .grpc import PredictionServiceGrpcTransport +from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] +_transport_registry['grpc'] = PredictionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport + +__all__ = ( + 'PredictionServiceTransport', + 'PredictionServiceGrpcTransport', + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py new file mode 100644 index 00000000..d4f07f59 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PredictionServiceTransport(abc.ABC): + """Abstract transport class for PredictionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.predict: gapic_v1.method.wrap_method( + self.predict, + 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + Union[ + prediction_service.PredictResponse, + Awaitable[prediction_service.PredictResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'PredictionServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py new file mode 100644 index 00000000..500a4a04 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO + + +class PredictionServiceGrpcTransport(PredictionServiceTransport): + """gRPC backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + prediction_service.PredictResponse]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + ~.PredictResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'PredictionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..49d0872c --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import PredictionServiceGrpcTransport + + +class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): + """gRPC AsyncIO backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + Awaitable[prediction_service.PredictResponse]]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + Awaitable[~.PredictResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py new file mode 100644 index 00000000..0fa6330a --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ProductServiceClient +from .async_client import ProductServiceAsyncClient + +__all__ = ( + 'ProductServiceClient', + 'ProductServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py new file mode 100644 index 00000000..493936e0 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py @@ -0,0 +1,1692 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.services.product_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.cloud.retail_v2beta.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport +from .client import ProductServiceClient + + +class ProductServiceAsyncClient: + """Service for ingesting [Product][google.cloud.retail.v2beta.Product] + information of the customer's website. + """ + + _client: ProductServiceClient + + DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(ProductServiceClient.branch_path) + parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) + product_path = staticmethod(ProductServiceClient.product_path) + parse_product_path = staticmethod(ProductServiceClient.parse_product_path) + common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProductServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProductServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProductServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProductServiceClient.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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ProductServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ProductServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_create_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`google.cloud.retail_v2beta.types.Product`): + Required. The + [Product][google.cloud.retail.v2beta.Product] to create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + Required. The ID to use for the + [Product][google.cloud.retail.v2beta.Product], which + will become the final component of the + [Product.name][google.cloud.retail.v2beta.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This field must be unique among all + [Product][google.cloud.retail.v2beta.Product]s with the + same + [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Product][google.cloud.retail.v2beta.Product] 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.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Gets a list of [Product][google.cloud.retail.v2beta.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_list_products(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2beta.Product]s under + this branch, regardless of whether or not this branch + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.product_service.pagers.ListProductsAsyncPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (:class:`google.cloud.retail_v2beta.types.Product`): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2beta.Product] to update. + The immutable and output only fields are NOT supported. + If not set, all supported fields (the fields that are + neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_delete_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2beta.Product] to + delete can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product] member nor + a + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] with more + than one + [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2beta.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2beta.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2beta.Product]s to be + successfully updated. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_import_products(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2beta.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2beta.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_set_inventory(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2beta.Product() + inventory.title = "title_value" + + request = retail_v2beta.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (:class:`google.cloud.retail_v2beta.types.Product`): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product] named in + [Product.name][google.cloud.retail.v2beta.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2beta.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2beta.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.SetInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_inventory, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + async def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [AddFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_add_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [AddLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_remove_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py new file mode 100644 index 00000000..e048bbc8 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py @@ -0,0 +1,1894 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.services.product_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.cloud.retail_v2beta.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductServiceGrpcTransport +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +class ProductServiceClientMeta(type): + """Metaclass for the ProductService 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[ProductServiceTransport]] + _transport_registry["grpc"] = ProductServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ProductServiceTransport]: + """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 ProductServiceClient(metaclass=ProductServiceClientMeta): + """Service for ingesting [Product][google.cloud.retail.v2beta.Product] + information of the customer's website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProductServiceClient: 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: + ProductServiceClient: 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) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ProductServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProductServiceTransport): + # transport is a ProductServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_create_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (google.cloud.retail_v2beta.types.Product): + Required. The + [Product][google.cloud.retail.v2beta.Product] to create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2beta.Product], which + will become the final component of the + [Product.name][google.cloud.retail.v2beta.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This field must be unique among all + [Product][google.cloud.retail.v2beta.Product]s with the + same + [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.CreateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.CreateProductRequest): + request = product_service.CreateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Product][google.cloud.retail.v2beta.Product] 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.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.GetProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.GetProductRequest): + request = product_service.GetProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Gets a list of [Product][google.cloud.retail.v2beta.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_list_products(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2beta.Product]s under + this branch, regardless of whether or not this branch + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.product_service.pagers.ListProductsPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.ListProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.ListProductsRequest): + request = product_service.ListProductsRequest(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_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (google.cloud.retail_v2beta.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2beta.Product] to update. + The immutable and output only fields are NOT supported. + If not set, all supported fields (the fields that are + neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.UpdateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.UpdateProductRequest): + request = product_service.UpdateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + 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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_delete_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2beta.Product] to + delete can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product] member nor + a + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] with more + than one + [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2beta.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.DeleteProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.DeleteProductRequest): + request = product_service.DeleteProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2beta.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2beta.Product]s to be + successfully updated. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_import_products(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2beta.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportProductsRequest): + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2beta.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_set_inventory(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2beta.Product() + inventory.title = "title_value" + + request = retail_v2beta.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (google.cloud.retail_v2beta.types.Product): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product] named in + [Product.name][google.cloud.retail.v2beta.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2beta.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2beta.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.SetInventoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.SetInventoryRequest): + request = product_service.SetInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_add_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [AddFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddFulfillmentPlacesRequest): + request = product_service.AddFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): + request = product_service.RemoveFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_add_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [AddLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddLocalInventoriesRequest): + request = product_service.AddLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_remove_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveLocalInventoriesRequest): + request = product_service.RemoveLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py new file mode 100644 index 00000000..552c2bfa --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product_service + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListProductsResponse` + 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[..., product_service.ListProductsResponse], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2beta.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[product_service.ListProductsResponse]: + 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[product.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListProductsResponse` + 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[product_service.ListProductsResponse]], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2beta.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: + 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[product.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py new file mode 100644 index 00000000..db824dec --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ProductServiceTransport +from .grpc import ProductServiceGrpcTransport +from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] +_transport_registry['grpc'] = ProductServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport + +__all__ = ( + 'ProductServiceTransport', + 'ProductServiceGrpcTransport', + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py new file mode 100644 index 00000000..8e3d5c7e --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py @@ -0,0 +1,308 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ProductServiceTransport(abc.ABC): + """Abstract transport class for ProductService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_product: gapic_v1.method.wrap_method( + self.create_product, + default_timeout=None, + client_info=client_info, + ), + self.get_product: gapic_v1.method.wrap_method( + self.get_product, + default_timeout=None, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + default_timeout=None, + client_info=client_info, + ), + self.update_product: gapic_v1.method.wrap_method( + self.update_product, + default_timeout=None, + client_info=client_info, + ), + self.delete_product: gapic_v1.method.wrap_method( + self.delete_product, + default_timeout=None, + client_info=client_info, + ), + self.import_products: gapic_v1.method.wrap_method( + self.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.set_inventory: gapic_v1.method.wrap_method( + self.set_inventory, + default_timeout=None, + client_info=client_info, + ), + self.add_fulfillment_places: gapic_v1.method.wrap_method( + self.add_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.remove_fulfillment_places: gapic_v1.method.wrap_method( + self.remove_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.add_local_inventories: gapic_v1.method.wrap_method( + self.add_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.remove_local_inventories: gapic_v1.method.wrap_method( + self.remove_local_inventories, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Union[ + product.Product, + Awaitable[product.Product] + ]]: + raise NotImplementedError() + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Union[ + product_service.ListProductsResponse, + Awaitable[product_service.ListProductsResponse] + ]]: + raise NotImplementedError() + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProductServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py new file mode 100644 index 00000000..b4f474cd --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py @@ -0,0 +1,678 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO + + +class ProductServiceGrpcTransport(ProductServiceTransport): + """gRPC backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2beta.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + gcr_product.Product]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.CreateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + product.Product]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + product_service.ListProductsResponse]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2beta.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + gcr_product.Product]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + ~.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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2beta.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2beta.Product]s to be + successfully updated. + + Returns: + Callable[[~.ImportProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + operations_pb2.Operation]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2beta.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProductServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..aad12324 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py @@ -0,0 +1,677 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductServiceGrpcTransport + + +class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): + """gRPC AsyncIO backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2beta.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.CreateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Awaitable[product.Product]]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Awaitable[product_service.ListProductsResponse]]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2beta.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + 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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2beta.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2beta.Product]s to be + successfully updated. + + Returns: + Callable[[~.ImportProductsRequest], + 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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2beta.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + 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 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + 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 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + 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 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + 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 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py new file mode 100644 index 00000000..2f63fc22 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SearchServiceClient +from .async_client import SearchServiceAsyncClient + +__all__ = ( + 'SearchServiceClient', + 'SearchServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py new file mode 100644 index 00000000..4943cff9 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.search_service import pagers +from google.cloud.retail_v2beta.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .client import SearchServiceClient + + +class SearchServiceAsyncClient: + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: SearchServiceClient + + DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(SearchServiceClient.branch_path) + parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + product_path = staticmethod(SearchServiceClient.product_path) + parse_product_path = staticmethod(SearchServiceClient.parse_product_path) + common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(SearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SearchServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAsyncPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_search(): + # Create a client + client = retail_v2beta.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.search_service.pagers.SearchAsyncPager: + Response message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py new file mode 100644 index 00000000..b564fd9b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.search_service import pagers +from google.cloud.retail_v2beta.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SearchServiceGrpcTransport +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +class SearchServiceClientMeta(type): + """Metaclass for the SearchService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] + _transport_registry["grpc"] = SearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SearchServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SearchServiceClient(metaclass=SearchServiceClientMeta): + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SearchServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SearchServiceTransport): + # transport is a SearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_search(): + # Create a client + client = retail_v2beta.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.search_service.pagers.SearchPager: + Response message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a search_service.SearchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py new file mode 100644 index 00000000..6ff03162 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import search_service + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2beta.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2beta.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py new file mode 100644 index 00000000..7917cd1d --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SearchServiceTransport +from .grpc import SearchServiceGrpcTransport +from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] +_transport_registry['grpc'] = SearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport + +__all__ = ( + 'SearchServiceTransport', + 'SearchServiceGrpcTransport', + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py new file mode 100644 index 00000000..26e7d5f2 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import search_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SearchServiceTransport(abc.ABC): + """Abstract transport class for SearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search: gapic_v1.method.wrap_method( + self.search, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Union[ + search_service.SearchResponse, + Awaitable[search_service.SearchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SearchServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py new file mode 100644 index 00000000..f21185b4 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py @@ -0,0 +1,268 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO + + +class SearchServiceGrpcTransport(SearchServiceTransport): + """gRPC backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..33943b61 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py @@ -0,0 +1,267 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SearchServiceGrpcTransport + + +class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): + """gRPC AsyncIO backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Awaitable[search_service.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py new file mode 100644 index 00000000..d1a0a023 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ServingConfigServiceClient +from .async_client import ServingConfigServiceAsyncClient + +__all__ = ( + 'ServingConfigServiceClient', + 'ServingConfigServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py new file mode 100644 index 00000000..cfdace1d --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py @@ -0,0 +1,954 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.serving_config_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport +from .client import ServingConfigServiceClient + + +class ServingConfigServiceAsyncClient: + """Service for modifying ServingConfig.""" + + _client: ServingConfigServiceClient + + DEFAULT_ENDPOINT = ServingConfigServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ServingConfigServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(ServingConfigServiceClient.catalog_path) + parse_catalog_path = staticmethod(ServingConfigServiceClient.parse_catalog_path) + serving_config_path = staticmethod(ServingConfigServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(ServingConfigServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(ServingConfigServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ServingConfigServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ServingConfigServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ServingConfigServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ServingConfigServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ServingConfigServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ServingConfigServiceClient.common_project_path) + parse_common_project_path = staticmethod(ServingConfigServiceClient.parse_common_project_path) + common_location_path = staticmethod(ServingConfigServiceClient.common_location_path) + parse_common_location_path = staticmethod(ServingConfigServiceClient.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: + ServingConfigServiceAsyncClient: The constructed client. + """ + return ServingConfigServiceClient.from_service_account_info.__func__(ServingConfigServiceAsyncClient, 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: + ServingConfigServiceAsyncClient: The constructed client. + """ + return ServingConfigServiceClient.from_service_account_file.__func__(ServingConfigServiceAsyncClient, 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 variabel 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 ServingConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ServingConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ServingConfigServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ServingConfigServiceClient).get_transport_class, type(ServingConfigServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ServingConfigServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the serving config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ServingConfigServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ServingConfigServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_serving_config(self, + request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, + *, + parent: str = None, + serving_config: gcr_serving_config.ServingConfig = None, + serving_config_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_create_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = await client.create_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateServingConfigRequest, dict]): + The request object. Request for CreateServingConfig + method. + parent (:class:`str`): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config (:class:`google.cloud.retail_v2beta.types.ServingConfig`): + Required. The ServingConfig to + create. + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config_id (:class:`str`): + Required. The ID to use for the ServingConfig, which + will become the final component of the ServingConfig's + resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``serving_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, serving_config, serving_config_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.CreateServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if serving_config is not None: + request.serving_config = serving_config + if serving_config_id is not None: + request.serving_config_id = serving_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_serving_config(self, + request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_delete_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_serving_config(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteServingConfigRequest, dict]): + The request object. Request for DeleteServingConfig + method. + name (:class:`str`): + Required. The resource name of the ServingConfig to + delete. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.DeleteServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_serving_config(self, + request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, + *, + serving_config: gcr_serving_config.ServingConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Updates a ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = await client.update_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateServingConfigRequest, dict]): + The request object. Request for UpdateServingConfig + method. + serving_config (:class:`google.cloud.retail_v2beta.types.ServingConfig`): + Required. The ServingConfig to + update. + + This corresponds to the ``serving_config`` 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 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.UpdateServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config.name", request.serving_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_serving_config(self, + request: Union[serving_config_service.GetServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> serving_config.ServingConfig: + r"""Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetServingConfigRequest, dict]): + The request object. Request for GetServingConfig method. + name (:class:`str`): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.GetServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_serving_configs(self, + request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServingConfigsAsyncPager: + r"""Lists all ServingConfigs linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_list_serving_configs(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListServingConfigsRequest, dict]): + The request object. Request for ListServingConfigs + method. + parent (:class:`str`): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager: + Response for ListServingConfigs + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.ListServingConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_serving_configs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServingConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_control(self, + request: Union[serving_config_service.AddControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_add_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.add_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddControlRequest, dict]): + The request object. Request for AddControl method. + serving_config (:class:`str`): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.AddControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_control(self, + request: Union[serving_config_service.RemoveControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_remove_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.remove_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveControlRequest, dict]): + The request object. Request for RemoveControl method. + serving_config (:class:`str`): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.RemoveControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServingConfigServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py new file mode 100644 index 00000000..122021ae --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py @@ -0,0 +1,1162 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.serving_config_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ServingConfigServiceGrpcTransport +from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport + + +class ServingConfigServiceClientMeta(type): + """Metaclass for the ServingConfigService 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[ServingConfigServiceTransport]] + _transport_registry["grpc"] = ServingConfigServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ServingConfigServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ServingConfigServiceTransport]: + """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 ServingConfigServiceClient(metaclass=ServingConfigServiceClientMeta): + """Service for modifying ServingConfig.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServingConfigServiceClient: 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: + ServingConfigServiceClient: 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) -> ServingConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ServingConfigServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,catalog: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ServingConfigServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the serving config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ServingConfigServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ServingConfigServiceTransport): + # transport is a ServingConfigServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_serving_config(self, + request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, + *, + parent: str = None, + serving_config: gcr_serving_config.ServingConfig = None, + serving_config_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_create_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = client.create_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateServingConfigRequest, dict]): + The request object. Request for CreateServingConfig + method. + parent (str): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config (google.cloud.retail_v2beta.types.ServingConfig): + Required. The ServingConfig to + create. + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config_id (str): + Required. The ID to use for the ServingConfig, which + will become the final component of the ServingConfig's + resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``serving_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, serving_config, serving_config_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.CreateServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.CreateServingConfigRequest): + request = serving_config_service.CreateServingConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if serving_config is not None: + request.serving_config = serving_config + if serving_config_id is not None: + request.serving_config_id = serving_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_serving_config(self, + request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_delete_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_serving_config(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteServingConfigRequest, dict]): + The request object. Request for DeleteServingConfig + method. + name (str): + Required. The resource name of the ServingConfig to + delete. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.DeleteServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.DeleteServingConfigRequest): + request = serving_config_service.DeleteServingConfigRequest(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_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_serving_config(self, + request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, + *, + serving_config: gcr_serving_config.ServingConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Updates a ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = client.update_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateServingConfigRequest, dict]): + The request object. Request for UpdateServingConfig + method. + serving_config (google.cloud.retail_v2beta.types.ServingConfig): + Required. The ServingConfig to + update. + + This corresponds to the ``serving_config`` 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 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.UpdateServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.UpdateServingConfigRequest): + request = serving_config_service.UpdateServingConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config.name", request.serving_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_serving_config(self, + request: Union[serving_config_service.GetServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> serving_config.ServingConfig: + r"""Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetServingConfigRequest, dict]): + The request object. Request for GetServingConfig method. + name (str): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.GetServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.GetServingConfigRequest): + request = serving_config_service.GetServingConfigRequest(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_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_serving_configs(self, + request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServingConfigsPager: + r"""Lists all ServingConfigs linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_list_serving_configs(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListServingConfigsRequest, dict]): + The request object. Request for ListServingConfigs + method. + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsPager: + Response for ListServingConfigs + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.ListServingConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.ListServingConfigsRequest): + request = serving_config_service.ListServingConfigsRequest(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_serving_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListServingConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_control(self, + request: Union[serving_config_service.AddControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_add_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.add_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddControlRequest, dict]): + The request object. Request for AddControl method. + serving_config (str): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.AddControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.AddControlRequest): + request = serving_config_service.AddControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_control(self, + request: Union[serving_config_service.RemoveControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_remove_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.remove_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveControlRequest, dict]): + The request object. Request for RemoveControl method. + serving_config (str): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.RemoveControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.RemoveControlRequest): + request = serving_config_service.RemoveControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServingConfigServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py new file mode 100644 index 00000000..a45bf88c --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config_service + + +class ListServingConfigsPager: + """A pager for iterating through ``list_serving_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``serving_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServingConfigs`` requests and continue to iterate + through the ``serving_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` + 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[..., serving_config_service.ListServingConfigsResponse], + request: serving_config_service.ListServingConfigsRequest, + response: serving_config_service.ListServingConfigsResponse, + *, + 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.retail_v2beta.types.ListServingConfigsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListServingConfigsResponse): + 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 = serving_config_service.ListServingConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[serving_config_service.ListServingConfigsResponse]: + 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[serving_config.ServingConfig]: + for page in self.pages: + yield from page.serving_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServingConfigsAsyncPager: + """A pager for iterating through ``list_serving_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``serving_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServingConfigs`` requests and continue to iterate + through the ``serving_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` + 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[serving_config_service.ListServingConfigsResponse]], + request: serving_config_service.ListServingConfigsRequest, + response: serving_config_service.ListServingConfigsResponse, + *, + 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.retail_v2beta.types.ListServingConfigsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListServingConfigsResponse): + 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 = serving_config_service.ListServingConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[serving_config_service.ListServingConfigsResponse]: + 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[serving_config.ServingConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.serving_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py new file mode 100644 index 00000000..3726ac83 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ServingConfigServiceTransport +from .grpc import ServingConfigServiceGrpcTransport +from .grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ServingConfigServiceTransport]] +_transport_registry['grpc'] = ServingConfigServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ServingConfigServiceGrpcAsyncIOTransport + +__all__ = ( + 'ServingConfigServiceTransport', + 'ServingConfigServiceGrpcTransport', + 'ServingConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py new file mode 100644 index 00000000..b6f20733 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py @@ -0,0 +1,237 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ServingConfigServiceTransport(abc.ABC): + """Abstract transport class for ServingConfigService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_serving_config: gapic_v1.method.wrap_method( + self.create_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_serving_config: gapic_v1.method.wrap_method( + self.delete_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.update_serving_config: gapic_v1.method.wrap_method( + self.update_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.get_serving_config: gapic_v1.method.wrap_method( + self.get_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.list_serving_configs: gapic_v1.method.wrap_method( + self.list_serving_configs, + default_timeout=None, + client_info=client_info, + ), + self.add_control: gapic_v1.method.wrap_method( + self.add_control, + default_timeout=None, + client_info=client_info, + ), + self.remove_control: gapic_v1.method.wrap_method( + self.remove_control, + 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 create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + Union[ + serving_config.ServingConfig, + Awaitable[serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + Union[ + serving_config_service.ListServingConfigsResponse, + Awaitable[serving_config_service.ListServingConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ServingConfigServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py new file mode 100644 index 00000000..a40958de --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py @@ -0,0 +1,438 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO + + +class ServingConfigServiceGrpcTransport(ServingConfigServiceTransport): + """gRPC backend transport for ServingConfigService. + + Service for modifying ServingConfig. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the create serving config method over gRPC. + + Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + Returns: + Callable[[~.CreateServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/CreateServingConfig', + request_serializer=serving_config_service.CreateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['create_serving_config'] + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete serving config method over gRPC. + + Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.DeleteServingConfigRequest], + ~.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_serving_config' not in self._stubs: + self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/DeleteServingConfig', + request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_serving_config'] + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the update serving config method over gRPC. + + Updates a ServingConfig. + + Returns: + Callable[[~.UpdateServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/UpdateServingConfig', + request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['update_serving_config'] + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + serving_config.ServingConfig]: + r"""Return a callable for the get serving config method over gRPC. + + Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.GetServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/GetServingConfig', + request_serializer=serving_config_service.GetServingConfigRequest.serialize, + response_deserializer=serving_config.ServingConfig.deserialize, + ) + return self._stubs['get_serving_config'] + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + serving_config_service.ListServingConfigsResponse]: + r"""Return a callable for the list serving configs method over gRPC. + + Lists all ServingConfigs linked to this catalog. + + Returns: + Callable[[~.ListServingConfigsRequest], + ~.ListServingConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: + self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/ListServingConfigs', + request_serializer=serving_config_service.ListServingConfigsRequest.serialize, + response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, + ) + return self._stubs['list_serving_configs'] + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the add control method over gRPC. + + Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + Returns: + Callable[[~.AddControlRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_control' not in self._stubs: + self._stubs['add_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/AddControl', + request_serializer=serving_config_service.AddControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['add_control'] + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the remove control method over gRPC. + + Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + Returns: + Callable[[~.RemoveControlRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_control' not in self._stubs: + self._stubs['remove_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/RemoveControl', + request_serializer=serving_config_service.RemoveControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['remove_control'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ServingConfigServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..ad0a2383 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py @@ -0,0 +1,437 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ServingConfigServiceGrpcTransport + + +class ServingConfigServiceGrpcAsyncIOTransport(ServingConfigServiceTransport): + """gRPC AsyncIO backend transport for ServingConfigService. + + Service for modifying ServingConfig. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the create serving config method over gRPC. + + Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + Returns: + Callable[[~.CreateServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/CreateServingConfig', + request_serializer=serving_config_service.CreateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['create_serving_config'] + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete serving config method over gRPC. + + Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.DeleteServingConfigRequest], + 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_serving_config' not in self._stubs: + self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/DeleteServingConfig', + request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_serving_config'] + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the update serving config method over gRPC. + + Updates a ServingConfig. + + Returns: + Callable[[~.UpdateServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/UpdateServingConfig', + request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['update_serving_config'] + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + Awaitable[serving_config.ServingConfig]]: + r"""Return a callable for the get serving config method over gRPC. + + Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.GetServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/GetServingConfig', + request_serializer=serving_config_service.GetServingConfigRequest.serialize, + response_deserializer=serving_config.ServingConfig.deserialize, + ) + return self._stubs['get_serving_config'] + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + Awaitable[serving_config_service.ListServingConfigsResponse]]: + r"""Return a callable for the list serving configs method over gRPC. + + Lists all ServingConfigs linked to this catalog. + + Returns: + Callable[[~.ListServingConfigsRequest], + Awaitable[~.ListServingConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: + self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/ListServingConfigs', + request_serializer=serving_config_service.ListServingConfigsRequest.serialize, + response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, + ) + return self._stubs['list_serving_configs'] + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the add control method over gRPC. + + Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + Returns: + Callable[[~.AddControlRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_control' not in self._stubs: + self._stubs['add_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/AddControl', + request_serializer=serving_config_service.AddControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['add_control'] + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the remove control method over gRPC. + + Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + Returns: + Callable[[~.RemoveControlRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_control' not in self._stubs: + self._stubs['remove_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/RemoveControl', + request_serializer=serving_config_service.RemoveControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['remove_control'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ServingConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py new file mode 100644 index 00000000..5f5171c1 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py new file mode 100644 index 00000000..24cdc934 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py @@ -0,0 +1,730 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on the customer + website. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(UserEventServiceClient.catalog_path) + parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) + product_path = staticmethod(UserEventServiceClient.product_path) + parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_write_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_collect_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_purge_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_import_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2beta.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_rejoin_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py new file mode 100644 index 00000000..04d1d50e --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py @@ -0,0 +1,929 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[UserEventServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on the customer + website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_write_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_collect_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_purge_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeUserEventsRequest): + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_import_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2beta.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_rejoin_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.RejoinUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.RejoinUserEventsRequest): + request = user_event_service.RejoinUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py new file mode 100644 index 00000000..f53ee5d7 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py new file mode 100644 index 00000000..bfd58c51 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.rejoin_user_events: gapic_v1.method.wrap_method( + self.rejoin_user_events, + 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 write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + user_event.UserEvent, + Awaitable[user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py new file mode 100644 index 00000000..aa8a47d4 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py @@ -0,0 +1,415 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..b4b62767 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,414 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + 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 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py new file mode 100644 index 00000000..62477503 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .catalog import ( + AttributesConfig, + Catalog, + CatalogAttribute, + CompletionConfig, + MerchantCenterLink, + MerchantCenterLinkingConfig, + ProductLevelConfig, +) +from .catalog_service import ( + AddCatalogAttributeRequest, + GetAttributesConfigRequest, + GetCompletionConfigRequest, + GetDefaultBranchRequest, + GetDefaultBranchResponse, + ListCatalogsRequest, + ListCatalogsResponse, + RemoveCatalogAttributeRequest, + ReplaceCatalogAttributeRequest, + SetDefaultBranchRequest, + UpdateAttributesConfigRequest, + UpdateCatalogRequest, + UpdateCompletionConfigRequest, +) +from .common import ( + Audience, + ColorInfo, + Condition, + CustomAttribute, + FulfillmentInfo, + Image, + Interval, + LocalInventory, + PriceInfo, + Rating, + Rule, + UserInfo, + AttributeConfigLevel, + SearchSolutionUseCase, + SolutionType, +) +from .completion_service import ( + CompleteQueryRequest, + CompleteQueryResponse, +) +from .control import ( + Control, +) +from .control_service import ( + CreateControlRequest, + DeleteControlRequest, + GetControlRequest, + ListControlsRequest, + ListControlsResponse, + UpdateControlRequest, +) +from .export_config import ( + ExportErrorsConfig, + ExportMetadata, + ExportProductsResponse, + ExportUserEventsResponse, +) +from .import_config import ( + BigQuerySource, + CompletionDataInputConfig, + GcsSource, + ImportCompletionDataRequest, + ImportCompletionDataResponse, + ImportErrorsConfig, + ImportMetadata, + ImportProductsRequest, + ImportProductsResponse, + ImportUserEventsRequest, + ImportUserEventsResponse, + ProductInlineSource, + ProductInputConfig, + UserEventImportSummary, + UserEventInlineSource, + UserEventInputConfig, +) +from .prediction_service import ( + PredictRequest, + PredictResponse, +) +from .product import ( + Product, +) +from .product_service import ( + AddFulfillmentPlacesMetadata, + AddFulfillmentPlacesRequest, + AddFulfillmentPlacesResponse, + AddLocalInventoriesMetadata, + AddLocalInventoriesRequest, + AddLocalInventoriesResponse, + CreateProductRequest, + DeleteProductRequest, + GetProductRequest, + ListProductsRequest, + ListProductsResponse, + RemoveFulfillmentPlacesMetadata, + RemoveFulfillmentPlacesRequest, + RemoveFulfillmentPlacesResponse, + RemoveLocalInventoriesMetadata, + RemoveLocalInventoriesRequest, + RemoveLocalInventoriesResponse, + SetInventoryMetadata, + SetInventoryRequest, + SetInventoryResponse, + UpdateProductRequest, +) +from .promotion import ( + Promotion, +) +from .purge_config import ( + PurgeMetadata, + PurgeUserEventsRequest, + PurgeUserEventsResponse, +) +from .search_service import ( + SearchRequest, + SearchResponse, +) +from .serving_config import ( + ServingConfig, +) +from .serving_config_service import ( + AddControlRequest, + CreateServingConfigRequest, + DeleteServingConfigRequest, + GetServingConfigRequest, + ListServingConfigsRequest, + ListServingConfigsResponse, + RemoveControlRequest, + UpdateServingConfigRequest, +) +from .user_event import ( + CompletionDetail, + ProductDetail, + PurchaseTransaction, + UserEvent, +) +from .user_event_service import ( + CollectUserEventRequest, + RejoinUserEventsMetadata, + RejoinUserEventsRequest, + RejoinUserEventsResponse, + WriteUserEventRequest, +) + +__all__ = ( + 'AttributesConfig', + 'Catalog', + 'CatalogAttribute', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'ProductLevelConfig', + 'AddCatalogAttributeRequest', + 'GetAttributesConfigRequest', + 'GetCompletionConfigRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + 'SetDefaultBranchRequest', + 'UpdateAttributesConfigRequest', + 'UpdateCatalogRequest', + 'UpdateCompletionConfigRequest', + 'Audience', + 'ColorInfo', + 'Condition', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'Rule', + 'UserInfo', + 'AttributeConfigLevel', + 'SearchSolutionUseCase', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Control', + 'CreateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + 'UpdateControlRequest', + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'ServingConfig', + 'AddControlRequest', + 'CreateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'RemoveControlRequest', + 'UpdateServingConfigRequest', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py new file mode 100644 index 00000000..8398213f --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py @@ -0,0 +1,528 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'ProductLevelConfig', + 'CatalogAttribute', + 'AttributesConfig', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'Catalog', + }, +) + + +class ProductLevelConfig(proto.Message): + r"""Configures what level the product should be uploaded with + regards to how users will be send events and how predictions + will be made. + + Attributes: + ingestion_product_type (str): + The type of [Product][google.cloud.retail.v2beta.Product]s + allowed to be ingested into the catalog. Acceptable values + are: + + - ``primary`` (default): You can ingest + [Product][google.cloud.retail.v2beta.Product]s of all + types. When ingesting a + [Product][google.cloud.retail.v2beta.Product], its type + will default to + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + if unset. + - ``variant``: You can only ingest + [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s. This + means + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] + cannot be empty. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``variant`` and + [merchant_center_product_id_field][google.cloud.retail.v2beta.ProductLevelConfig.merchant_center_product_id_field] + is ``itemGroupId``, an INVALID_ARGUMENT error is returned. + + See `Using product + levels `__ + for more details. + merchant_center_product_id_field (str): + Which field of `Merchant Center + Product `__ + should be imported as + [Product.id][google.cloud.retail.v2beta.Product.id]. + Acceptable values are: + + - ``offerId`` (default): Import ``offerId`` as the product + ID. + - ``itemGroupId``: Import ``itemGroupId`` as the product + ID. Notice that Retail API will choose one item from the + ones with the same ``itemGroupId``, and use it to + represent the item group. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``itemGroupId`` and + [ingestion_product_type][google.cloud.retail.v2beta.ProductLevelConfig.ingestion_product_type] + is ``variant``, an INVALID_ARGUMENT error is returned. + + See `Using product + levels `__ + for more details. + """ + + ingestion_product_type = proto.Field( + proto.STRING, + number=1, + ) + merchant_center_product_id_field = proto.Field( + proto.STRING, + number=2, + ) + + +class CatalogAttribute(proto.Message): + r"""Catalog level attribute config for an attribute. For example, + if customers want to enable/disable facet for a specific + attribute. + + Attributes: + key (str): + Required. Attribute name. For example: ``color``, + ``brands``, ``attributes.custom_attribute``, such as + ``attributes.xyz``. + in_use (bool): + Output only. Indicates whether this attribute has been used + by any products. ``True`` if at least one + [Product][google.cloud.retail.v2beta.Product] is using this + attribute in + [Product.attributes][google.cloud.retail.v2beta.Product.attributes]. + Otherwise, this field is ``False``. + + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + can be pre-loaded by using [AddCatalogAttribute][], + [ImportCatalogAttributes][], or [UpdateAttributesConfig][] + APIs. This field is ``False`` for pre-loaded + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s. + + Only + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s + that are not in use by products can be deleted. + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s + that are in use by products cannot be deleted; however, + their configuration properties will reset to default values + upon removal request. + + After catalog changes, it takes about 10 minutes for this + field to update. + type_ (google.cloud.retail_v2beta.types.CatalogAttribute.AttributeType): + Output only. The type of this attribute. This is derived + from the attribute in + [Product.attributes][google.cloud.retail.v2beta.Product.attributes]. + indexable_option (google.cloud.retail_v2beta.types.CatalogAttribute.IndexableOption): + When + [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] + is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if INDEXABLE_ENABLED + attribute values are indexed so that it can be filtered, + faceted, or boosted in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + dynamic_facetable_option (google.cloud.retail_v2beta.types.CatalogAttribute.DynamicFacetableOption): + If DYNAMIC_FACETABLE_ENABLED, attribute values are available + for dynamic facet. Could only be DYNAMIC_FACETABLE_DISABLED + if + [CatalogAttribute.indexable_option][google.cloud.retail.v2beta.CatalogAttribute.indexable_option] + is INDEXABLE_DISABLED. Otherwise, an INVALID_ARGUMENT error + is returned. + searchable_option (google.cloud.retail_v2beta.types.CatalogAttribute.SearchableOption): + When + [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] + is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if SEARCHABLE_ENABLED, + attribute values are searchable by text queries in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + If SEARCHABLE_ENABLED but attribute type is numerical, + attribute values will not be searchable by text queries in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + as there are no text values associated to numerical + attributes. + """ + class AttributeType(proto.Enum): + r"""The type of an attribute.""" + UNKNOWN = 0 + TEXTUAL = 1 + NUMERICAL = 2 + + class IndexableOption(proto.Enum): + r"""The status of the indexable option of a catalog attribute.""" + INDEXABLE_OPTION_UNSPECIFIED = 0 + INDEXABLE_ENABLED = 1 + INDEXABLE_DISABLED = 2 + + class DynamicFacetableOption(proto.Enum): + r"""The status of the dynamic facetable option of a catalog + attribute. + """ + DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 + DYNAMIC_FACETABLE_ENABLED = 1 + DYNAMIC_FACETABLE_DISABLED = 2 + + class SearchableOption(proto.Enum): + r"""The status of the searchable option of a catalog attribute.""" + SEARCHABLE_OPTION_UNSPECIFIED = 0 + SEARCHABLE_ENABLED = 1 + SEARCHABLE_DISABLED = 2 + + key = proto.Field( + proto.STRING, + number=1, + ) + in_use = proto.Field( + proto.BOOL, + number=9, + ) + type_ = proto.Field( + proto.ENUM, + number=10, + enum=AttributeType, + ) + indexable_option = proto.Field( + proto.ENUM, + number=5, + enum=IndexableOption, + ) + dynamic_facetable_option = proto.Field( + proto.ENUM, + number=6, + enum=DynamicFacetableOption, + ) + searchable_option = proto.Field( + proto.ENUM, + number=7, + enum=SearchableOption, + ) + + +class AttributesConfig(proto.Message): + r"""Catalog level attribute config. + + Attributes: + name (str): + Required. Immutable. The fully qualified resource name of + the attribute config. Format: + ``projects/*/locations/*/catalogs/*/attributesConfig`` + catalog_attributes (Mapping[str, google.cloud.retail_v2beta.types.CatalogAttribute]): + Enable attribute(s) config at catalog level. For example, + indexable, dynamic_facetable, or searchable for each + attribute. + + The key is catalog attribute's name. For example: ``color``, + ``brands``, ``attributes.custom_attribute``, such as + ``attributes.xyz``. + + The maximum number of catalog attributes allowed in a + request is 1000. + attribute_config_level (google.cloud.retail_v2beta.types.AttributeConfigLevel): + Output only. The + [AttributeConfigLevel][google.cloud.retail.v2beta.AttributeConfigLevel] + used for this catalog. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + catalog_attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='CatalogAttribute', + ) + attribute_config_level = proto.Field( + proto.ENUM, + number=3, + enum=common.AttributeConfigLevel, + ) + + +class CompletionConfig(proto.Message): + r"""Catalog level autocomplete config for customers to customize + autocomplete feature's settings. + + Attributes: + name (str): + Required. Immutable. Fully qualified name + ``projects/*/locations/*/catalogs/*/completionConfig`` + matching_order (str): + Specifies the matching order for autocomplete suggestions, + e.g., a query consisting of 'sh' with 'out-of-order' + specified would suggest "women's shoes", whereas a query of + 'red s' with 'exact-prefix' specified would suggest "red + shoes". Currently supported values: + + - 'out-of-order' + - 'exact-prefix' + + Default value: 'exact-prefix'. + max_suggestions (int): + The maximum number of autocomplete + suggestions returned per term. The maximum + allowed max suggestions is 20. Default value is + 20. If left unset or set to 0, then will + fallback to default value. + min_prefix_length (int): + The minimum number of characters needed to be + typed in order to get suggestions. Default value + is 2. If left unset or set to 0, then will + fallback to default value. + auto_learning (bool): + If set to true, the auto learning function is enabled. Auto + learning uses user data to generate suggestions using ML + techniques. Default value is false. Only after enabling auto + learning can users use ``cloud-retail`` data in + [CompleteQueryRequest][google.cloud.retail.v2beta.CompleteQueryRequest]. + suggestions_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the + autocomplete phrases uploaded by the customer. + last_suggestions_import_operation (str): + Output only. Name of the LRO corresponding to the latest + suggestion terms list import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + denylist_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the / + autocomplete denylist phrases uploaded by the + customer. + last_denylist_import_operation (str): + Output only. LRO corresponding to the latest denylist + import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + allowlist_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the + autocomplete allowlist phrases uploaded by the + customer. + last_allowlist_import_operation (str): + Output only. LRO corresponding to the latest allowlist + import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + matching_order = proto.Field( + proto.STRING, + number=2, + ) + max_suggestions = proto.Field( + proto.INT32, + number=3, + ) + min_prefix_length = proto.Field( + proto.INT32, + number=4, + ) + auto_learning = proto.Field( + proto.BOOL, + number=11, + ) + suggestions_input_config = proto.Field( + proto.MESSAGE, + number=5, + message=import_config.CompletionDataInputConfig, + ) + last_suggestions_import_operation = proto.Field( + proto.STRING, + number=6, + ) + denylist_input_config = proto.Field( + proto.MESSAGE, + number=7, + message=import_config.CompletionDataInputConfig, + ) + last_denylist_import_operation = proto.Field( + proto.STRING, + number=8, + ) + allowlist_input_config = proto.Field( + proto.MESSAGE, + number=9, + message=import_config.CompletionDataInputConfig, + ) + last_allowlist_import_operation = proto.Field( + proto.STRING, + number=10, + ) + + +class MerchantCenterLink(proto.Message): + r"""Represents a link between a Merchant Center account and a + branch. Once a link is established, products from the linked + merchant center account will be streamed to the linked branch. + + Attributes: + merchant_center_account_id (int): + Required. The linked `Merchant center account + id `__. + The account must be a standalone account or a sub-account of + a MCA. + branch_id (str): + The branch id (e.g. 0/1/2) within this catalog that products + from merchant_center_account_id are streamed to. When + updating this field, an empty value will use the currently + configured default branch. However, changing the default + branch later on won't change the linked branch here. + + A single branch id can only have one linked merchant center + account id. + destinations (Sequence[str]): + String representing the destination to import for, all if + left empty. List of possible values can be found here. + [https://support.google.com/merchants/answer/7501026] List + of allowed string values: "Shopping_ads", + "Buy_on_google_listings", "Display_ads", "Local_inventory + \_ads", "Free_listings", "Free_local_listings" NOTE: The + string values are case sensitive. + region_code (str): + Region code of offers to accept. 2-letter Uppercase ISO + 3166-1 alpha-2 code. List of values can be found + `here `__ + under the ``region`` tag. If left blank no region filtering + will be performed. + + Example value: ``US``. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. ISO + 639-1. + + This specifies the language of offers in Merchant Center + that will be accepted. If empty no language filtering will + be performed. + + Example value: ``en``. + """ + + merchant_center_account_id = proto.Field( + proto.INT64, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + destinations = proto.RepeatedField( + proto.STRING, + number=3, + ) + region_code = proto.Field( + proto.STRING, + number=4, + ) + language_code = proto.Field( + proto.STRING, + number=5, + ) + + +class MerchantCenterLinkingConfig(proto.Message): + r"""Configures Merchant Center linking. + Links contained in the config will be used to sync data from a + Merchant Center account to a Cloud Retail branch. + + Attributes: + links (Sequence[google.cloud.retail_v2beta.types.MerchantCenterLink]): + Links between Merchant Center accounts and + branches. + """ + + links = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MerchantCenterLink', + ) + + +class Catalog(proto.Message): + r"""The catalog configuration. + + Attributes: + name (str): + Required. Immutable. The fully qualified + resource name of the catalog. + display_name (str): + Required. Immutable. The catalog display name. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + product_level_config (google.cloud.retail_v2beta.types.ProductLevelConfig): + Required. The product level configuration. + merchant_center_linking_config (google.cloud.retail_v2beta.types.MerchantCenterLinkingConfig): + The Merchant Center linking configuration. + Once a link is added, the data stream from + Merchant Center to Cloud Retail will be enabled + automatically. The requester must have access to + the merchant center account in order to make + changes to this field. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + product_level_config = proto.Field( + proto.MESSAGE, + number=4, + message='ProductLevelConfig', + ) + merchant_center_linking_config = proto.Field( + proto.MESSAGE, + number=6, + message='MerchantCenterLinkingConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py new file mode 100644 index 00000000..c49ba005 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py @@ -0,0 +1,453 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'UpdateCatalogRequest', + 'SetDefaultBranchRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'GetCompletionConfigRequest', + 'UpdateCompletionConfigRequest', + 'GetAttributesConfigRequest', + 'UpdateAttributesConfigRequest', + 'AddCatalogAttributeRequest', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + }, +) + + +class ListCatalogsRequest(proto.Message): + r"""Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + + Attributes: + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2beta.Catalog]s under this + location, regardless of whether or not this location exists, + a PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [Catalog][google.cloud.retail.v2beta.Catalog]s to return. If + unspecified, defaults to 50. The maximum allowed value is + 1000. Values above 1000 will be coerced to 1000. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [ListCatalogsResponse.next_page_token][google.cloud.retail.v2beta.ListCatalogsResponse.next_page_token], + received from a previous + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCatalogsResponse(proto.Message): + r"""Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + + Attributes: + catalogs (Sequence[google.cloud.retail_v2beta.types.Catalog]): + All the customer's + [Catalog][google.cloud.retail.v2beta.Catalog]s. + next_page_token (str): + A token that can be sent as + [ListCatalogsRequest.page_token][google.cloud.retail.v2beta.ListCatalogsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + catalogs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateCatalogRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] + method. + + Attributes: + catalog (google.cloud.retail_v2beta.types.Catalog): + Required. The [Catalog][google.cloud.retail.v2beta.Catalog] + to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2beta.Catalog], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2beta.Catalog] 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 + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + catalog = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class SetDefaultBranchRequest(proto.Message): + r"""Request message to set a specified branch as new default_branch. + + Attributes: + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + branch_id (str): + The final component of the resource name of a branch. + + This field must be one of "0", "1" or "2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If there are no sufficient active products in the targeted + branch and + [force][google.cloud.retail.v2beta.SetDefaultBranchRequest.force] + is not set, a FAILED_PRECONDITION error is returned. + note (str): + Some note on this request, this can be retrieved by + [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch] + before next valid default branch set occurs. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + force (bool): + If set to true, it permits switching to a branch with + [branch_id][google.cloud.retail.v2beta.SetDefaultBranchRequest.branch_id] + even if it has no sufficient active products. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + force = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetDefaultBranchRequest(proto.Message): + r"""Request message to show which branch is currently the default + branch. + + Attributes: + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDefaultBranchResponse(proto.Message): + r"""Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. + + Attributes: + branch (str): + Full resource name of the branch id currently + set as default branch. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when this branch is set to default. + note (str): + This corresponds to + [SetDefaultBranchRequest.note][google.cloud.retail.v2beta.SetDefaultBranchRequest.note] + field, when this branch was set as default. + """ + + branch = proto.Field( + proto.STRING, + number=1, + ) + set_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + + +class GetCompletionConfigRequest(proto.Message): + r"""Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] + method. + + Attributes: + name (str): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateCompletionConfigRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] + method. + + Attributes: + completion_config (google.cloud.retail_v2beta.types.CompletionConfig): + Required. The + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + 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 + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + """ + + completion_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.CompletionConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetAttributesConfigRequest(proto.Message): + r"""Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] + method. + + Attributes: + name (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAttributesConfigRequest(proto.Message): + r"""Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] + method. + + Attributes: + attributes_config (google.cloud.retail_v2beta.types.AttributesConfig): + Required. The + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + """ + + attributes_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.AttributesConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class AddCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + catalog_attribute (google.cloud.retail_v2beta.types.CatalogAttribute): + Required. The + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + catalog_attribute = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_catalog.CatalogAttribute, + ) + + +class RemoveCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + key (str): + Required. The attribute name key of the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + key = proto.Field( + proto.STRING, + number=2, + ) + + +class ReplaceCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + catalog_attribute (google.cloud.retail_v2beta.types.CatalogAttribute): + Required. The updated + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to update. The following are NOT supported: + + - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key] + + If not set, all supported fields are updated. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + catalog_attribute = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_catalog.CatalogAttribute, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py new file mode 100644 index 00000000..c40843c0 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py @@ -0,0 +1,1178 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'AttributeConfigLevel', + 'SolutionType', + 'SearchSolutionUseCase', + 'Condition', + 'Rule', + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'LocalInventory', + }, +) + + +class AttributeConfigLevel(proto.Enum): + r"""At which level we offer configuration for attributes.""" + ATTRIBUTE_CONFIG_LEVEL_UNSPECIFIED = 0 + PRODUCT_LEVEL_ATTRIBUTE_CONFIG = 1 + CATALOG_LEVEL_ATTRIBUTE_CONFIG = 2 + + +class SolutionType(proto.Enum): + r"""The type of solution.""" + SOLUTION_TYPE_UNSPECIFIED = 0 + SOLUTION_TYPE_RECOMMENDATION = 1 + SOLUTION_TYPE_SEARCH = 2 + + +class SearchSolutionUseCase(proto.Enum): + r"""The use case of Cloud Retail Search.""" + SEARCH_SOLUTION_USE_CASE_UNSPECIFIED = 0 + SEARCH_SOLUTION_USE_CASE_SEARCH = 1 + SEARCH_SOLUTION_USE_CASE_BROWSE = 2 + + +class Condition(proto.Message): + r"""Metadata that is used to define a condition that triggers an action. + A valid condition must specify at least one of 'query_terms' or + 'products_filter'. If multiple fields are specified, the condition + is met if all the fields are satisfied e.g. if a set of query terms + and product_filter are set, then only items matching the + product_filter for requests with a query matching the query terms + wil get boosted. + + Attributes: + query_terms (Sequence[google.cloud.retail_v2beta.types.Condition.QueryTerm]): + A list (up to 10 entries) of terms to match + the query on. If not specified, match all + queries. If many query terms are specified, the + condition is matched if any of the terms is a + match (i.e. using the OR operator). + active_time_range (Sequence[google.cloud.retail_v2beta.types.Condition.TimeRange]): + Range of time(s) specifying when Condition is + active. Condition true if any time range + matches. + """ + + class QueryTerm(proto.Message): + r"""Query terms that we want to match on. + + Attributes: + value (str): + The value of the term to match on. + Value cannot be empty. + Value can have at most 3 terms if specified as a + partial match. Each space separated string is + considered as one term. Example) "a b c" is 3 + terms and allowed, " a b c d" is 4 terms and not + allowed for partial match. + full_match (bool): + Whether this is supposed to be a full or + partial match. + """ + + value = proto.Field( + proto.STRING, + number=1, + ) + full_match = proto.Field( + proto.BOOL, + number=2, + ) + + class TimeRange(proto.Message): + r"""Used for time-dependent conditions. + Example: Want to have rule applied for week long sale. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start of time range. Range is inclusive. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End of time range. Range is inclusive. + """ + + start_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + query_terms = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=QueryTerm, + ) + active_time_range = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TimeRange, + ) + + +class Rule(proto.Message): + r"""A rule is a condition-action pair + + - A condition defines when a rule is to be triggered. + - An action specifies what occurs on that trigger. Currently only + boost rules are supported. Currently only supported by the search + endpoint. + + 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: + boost_action (google.cloud.retail_v2beta.types.Rule.BoostAction): + A boost action. + + This field is a member of `oneof`_ ``action``. + redirect_action (google.cloud.retail_v2beta.types.Rule.RedirectAction): + Redirects a shopper to a specific page. + + This field is a member of `oneof`_ ``action``. + oneway_synonyms_action (google.cloud.retail_v2beta.types.Rule.OnewaySynonymsAction): + Treats specific term as a synonym with a + group of terms. Group of terms will not be + treated as synonyms with the specific term. + + This field is a member of `oneof`_ ``action``. + do_not_associate_action (google.cloud.retail_v2beta.types.Rule.DoNotAssociateAction): + Prevents term from being associated with + other terms. + + This field is a member of `oneof`_ ``action``. + replacement_action (google.cloud.retail_v2beta.types.Rule.ReplacementAction): + Replaces specific terms in the query. + + This field is a member of `oneof`_ ``action``. + ignore_action (google.cloud.retail_v2beta.types.Rule.IgnoreAction): + Ignores specific terms from query during + search. + + This field is a member of `oneof`_ ``action``. + filter_action (google.cloud.retail_v2beta.types.Rule.FilterAction): + Filters results. + + This field is a member of `oneof`_ ``action``. + twoway_synonyms_action (google.cloud.retail_v2beta.types.Rule.TwowaySynonymsAction): + Treats a set of terms as synonyms of one + another. + + This field is a member of `oneof`_ ``action``. + condition (google.cloud.retail_v2beta.types.Condition): + Required. The condition that triggers the + rule. If the condition is empty, the rule will + always apply. + """ + + class BoostAction(proto.Message): + r"""A boost action to apply to results matching condition + specified above. + + Attributes: + boost (float): + Strength of the condition boost, which must be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + products_filter (str): + The filter can have a max size of 5000 characters. An + expression which specifies which products to apply an action + to. The syntax and supported fields are the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": *(id: + ANY("product_1", "product_2"))* *AND* *(colorFamilies: + ANY("Red", "Blue"))* + """ + + boost = proto.Field( + proto.FLOAT, + number=1, + ) + products_filter = proto.Field( + proto.STRING, + number=2, + ) + + class FilterAction(proto.Message): + r"""- Rule Condition: + + - No [Condition][query_terms] provided is a global match. + - 1 or more [Condition][query_terms] provided is combined with + OR operator. + + - Action Input: The request query and filter that will be applied + to the retrieved products, in addition to any filters already + provided with the SearchRequest. The AND operator is used to + combine the query's existing filters with the filter rule(s). + NOTE: May result in 0 results when filters conflict. + - Action Result: Filters the returned objects to be ONLY those that + passed the filter. + + Attributes: + filter (str): + A filter to apply on the matching condition results. + Supported features: + + - [filter][google.cloud.retail.v2beta.Rule.FilterAction.filter] + must be set. + - Filter syntax is identical to + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter]. + See more details at the Retail Search `user + guide `__. + - To filter products with product ID "product_1" or + "product_2", and color "Red" or "Blue": *(id: + ANY("product_1", "product_2"))* *AND* *(colorFamilies: + ANY("Red", "Blue"))* + """ + + filter = proto.Field( + proto.STRING, + number=1, + ) + + class RedirectAction(proto.Message): + r"""Redirects a shopper to a specific page. + + - Rule Condition: + + - Must specify [Condition][query_terms]. + + - Action Input: Request Query + - Action Result: Redirects shopper to provided uri. + + Attributes: + redirect_uri (str): + URL must have length equal or less than 2000 + characters. + """ + + redirect_uri = proto.Field( + proto.STRING, + number=1, + ) + + class TwowaySynonymsAction(proto.Message): + r"""Creates a set of terms that will be treated as synonyms of each + other. Example: synonyms of "sneakers" and "shoes". + + - "sneakers" will use a synonym of "shoes". + - "shoes" will use a synonym of "sneakers". + + Attributes: + synonyms (Sequence[str]): + Defines a set of synonyms. + Can specify up to 100 synonyms. + Must specify at least 2 synonyms. + """ + + synonyms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class OnewaySynonymsAction(proto.Message): + r"""Maps a set of terms to a set of synonyms. Set of synonyms will be + treated as synonyms of each query term only. ``query_terms`` will + not be treated as synonyms of each other. Example: "sneakers" will + use a synonym of "shoes". "shoes" will not use a synonym of + "sneakers". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. + Will treat synonyms as their synonyms. + Not themselves synonyms of the synonyms. + Can specify up to 100 terms. + synonyms (Sequence[str]): + Defines a set of synonyms. + Cannot contain duplicates. + Can specify up to 100 synonyms. + oneway_terms (Sequence[str]): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=3, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=4, + ) + oneway_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class DoNotAssociateAction(proto.Message): + r"""Prevents ``query_term`` from being associated with specified terms + during search. Example: Don't associate "gShoe" and "cheap". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. Will not consider + do_not_associate_terms for search if in search query. Can + specify up to 100 terms. + do_not_associate_terms (Sequence[str]): + Cannot contain duplicates or the query term. + Can specify up to 100 terms. + terms (Sequence[str]): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + do_not_associate_terms = proto.RepeatedField( + proto.STRING, + number=3, + ) + terms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class ReplacementAction(proto.Message): + r"""Replaces a term in the query. Multiple replacement candidates can be + specified. All ``query_terms`` will be replaced with the replacement + term. Example: Replace "gShoe" with "google shoe". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. + Will be replaced by replacement term. + Can specify up to 100 terms. + replacement_term (str): + Term that will be used for replacement. + term (str): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + replacement_term = proto.Field( + proto.STRING, + number=3, + ) + term = proto.Field( + proto.STRING, + number=1, + ) + + class IgnoreAction(proto.Message): + r"""Prevents a term in the query from being used in search. + Example: Don't search for "shoddy". + + Attributes: + ignore_terms (Sequence[str]): + Terms to ignore in the search query. + """ + + ignore_terms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + boost_action = proto.Field( + proto.MESSAGE, + number=2, + oneof='action', + message=BoostAction, + ) + redirect_action = proto.Field( + proto.MESSAGE, + number=3, + oneof='action', + message=RedirectAction, + ) + oneway_synonyms_action = proto.Field( + proto.MESSAGE, + number=6, + oneof='action', + message=OnewaySynonymsAction, + ) + do_not_associate_action = proto.Field( + proto.MESSAGE, + number=7, + oneof='action', + message=DoNotAssociateAction, + ) + replacement_action = proto.Field( + proto.MESSAGE, + number=8, + oneof='action', + message=ReplacementAction, + ) + ignore_action = proto.Field( + proto.MESSAGE, + number=9, + oneof='action', + message=IgnoreAction, + ) + filter_action = proto.Field( + proto.MESSAGE, + number=10, + oneof='action', + message=FilterAction, + ) + twoway_synonyms_action = proto.Field( + proto.MESSAGE, + number=11, + oneof='action', + message=TwowaySynonymsAction, + ) + condition = proto.Field( + proto.MESSAGE, + number=1, + message='Condition', + ) + + +class Audience(proto.Message): + r"""An intended audience of the + [Product][google.cloud.retail.v2beta.Product] for whom it's sold. + + Attributes: + genders (Sequence[str]): + The genders of the audience. Strongly encouraged to use the + standard values: "male", "female", "unisex". + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `gender `__. + Schema.org property + `Product.audience.suggestedGender `__. + age_groups (Sequence[str]): + The age groups of the audience. Strongly encouraged to use + the standard values: "newborn" (up to 3 months old), + "infant" (3–12 months old), "toddler" (1–5 years old), + "kids" (5–13 years old), "adult" (typically teens or older). + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `age_group `__. + Schema.org property + `Product.audience.suggestedMinAge `__ + and + `Product.audience.suggestedMaxAge `__. + """ + + genders = proto.RepeatedField( + proto.STRING, + number=1, + ) + age_groups = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class ColorInfo(proto.Message): + r"""The color information of a + [Product][google.cloud.retail.v2beta.Product]. + + Attributes: + color_families (Sequence[str]): + The standard color families. Strongly recommended to use the + following standard color groups: "Red", "Pink", "Orange", + "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", + "White", "Gray", "Black" and "Mixed". Normally it is + expected to have only 1 color family. May consider using + single "Mixed" instead of multiple values. + + A maximum of 5 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + colors (Sequence[str]): + The color display names, which may be different from + standard color family names, such as the color aliases used + in the website frontend. Normally it is expected to have + only 1 color. May consider using single "Mixed" instead of + multiple values. + + A maximum of 25 colors are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + """ + + color_families = proto.RepeatedField( + proto.STRING, + number=1, + ) + colors = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in + [Product][google.cloud.retail.v2beta.Product]. + + Attributes: + text (Sequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an INVALID_ARGUMENT + error is returned. + + Exactly one of + [text][google.cloud.retail.v2beta.CustomAttribute.text] or + [numbers][google.cloud.retail.v2beta.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + numbers (Sequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [text][google.cloud.retail.v2beta.CustomAttribute.text] or + [numbers][google.cloud.retail.v2beta.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + searchable (bool): + This field will only be used when + [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] + of the [Catalog][google.cloud.retail.v2beta.Catalog] is + 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute + values are searchable by text queries in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2beta.UserEvent]. + + Only set if type + [text][google.cloud.retail.v2beta.CustomAttribute.text] is + set. Otherwise, a INVALID_ARGUMENT error is returned. + + This field is a member of `oneof`_ ``_searchable``. + indexable (bool): + This field will only be used when + [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] + of the [Catalog][google.cloud.retail.v2beta.Catalog] is + 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute + values are indexed, so that it can be filtered, faceted or + boosted in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2beta.UserEvent]. + + See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter], + [SearchRequest.facet_specs][google.cloud.retail.v2beta.SearchRequest.facet_specs] + and + [SearchRequest.boost_spec][google.cloud.retail.v2beta.SearchRequest.boost_spec] + for more details. + + This field is a member of `oneof`_ ``_indexable``. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + searchable = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + indexable = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + +class FulfillmentInfo(proto.Message): + r"""Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + Attributes: + type_ (str): + The fulfillment type, including commonly used types (such as + pickup in store and same day delivery), and custom types. + Customers have to map custom types to their display names + before rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + place_ids (Sequence[str]): + The IDs for this + [type][google.cloud.retail.v2beta.FulfillmentInfo.type], + such as the store IDs for + [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2beta.FulfillmentInfo.type] + or the region IDs for + [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2beta.FulfillmentInfo.type]. + + A maximum of 3000 values are allowed. Each value must be a + string with a length limit of 30 characters, matching the + pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". + Otherwise, an INVALID_ARGUMENT error is returned. + """ + + type_ = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class Image(proto.Message): + r"""[Product][google.cloud.retail.v2beta.Product] image. Recommendations + AI and Retail Search do not use product images to improve prediction + and search results. However, product images can be returned in + results, and are shown in prediction or search previews in the + console. + + Attributes: + uri (str): + Required. URI of the image. + + This field must be a valid UTF-8 encoded URI with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + height (int): + Height of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + width (int): + Width of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + height = proto.Field( + proto.INT32, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + + +class Interval(proto.Message): + r"""A floating point interval. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum = proto.Field( + proto.DOUBLE, + number=1, + oneof='min', + ) + exclusive_minimum = proto.Field( + proto.DOUBLE, + number=2, + oneof='min', + ) + maximum = proto.Field( + proto.DOUBLE, + number=3, + oneof='max', + ) + exclusive_maximum = proto.Field( + proto.DOUBLE, + number=4, + oneof='max', + ) + + +class PriceInfo(proto.Message): + r"""The price information of a + [Product][google.cloud.retail.v2beta.Product]. + + Attributes: + currency_code (str): + The 3-letter currency code defined in `ISO + 4217 `__. + + If this field is an unrecognizable currency code, an + INVALID_ARGUMENT error is returned. + + The + [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s with the same + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] + must share the same + [currency_code][google.cloud.retail.v2beta.PriceInfo.currency_code]. + Otherwise, a FAILED_PRECONDITION error is returned. + price (float): + Price of the product. + + Google Merchant Center property + `price `__. + Schema.org property + `Offer.price `__. + original_price (float): + Price of the product without any discount. If zero, by + default set to be the + [price][google.cloud.retail.v2beta.PriceInfo.price]. + cost (float): + The costs associated with the sale of a particular product. + Used for gross profit reporting. + + - Profit = + [price][google.cloud.retail.v2beta.PriceInfo.price] - + [cost][google.cloud.retail.v2beta.PriceInfo.cost] + + Google Merchant Center property + `cost_of_goods_sold `__. + price_effective_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2beta.PriceInfo.price] starts + to be effective. This can be set as a future timestamp, and + the [price][google.cloud.retail.v2beta.PriceInfo.price] is + only used for search after + [price_effective_time][google.cloud.retail.v2beta.PriceInfo.price_effective_time]. + If so, the + [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + is used before + [price_effective_time][google.cloud.retail.v2beta.PriceInfo.price_effective_time]. + + Do not set if + [price][google.cloud.retail.v2beta.PriceInfo.price] is + always effective because it will cause additional latency + during search. + price_expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2beta.PriceInfo.price] stops to + be effective. The + [price][google.cloud.retail.v2beta.PriceInfo.price] is used + for search before + [price_expire_time][google.cloud.retail.v2beta.PriceInfo.price_expire_time]. + If this field is set, the + [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + is used after + [price_expire_time][google.cloud.retail.v2beta.PriceInfo.price_expire_time]. + + Do not set if + [price][google.cloud.retail.v2beta.PriceInfo.price] is + always effective because it will cause additional latency + during search. + price_range (google.cloud.retail_v2beta.types.PriceInfo.PriceRange): + Output only. The price range of all the child + [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s grouped + together on the + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]. Only + populated for + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct]. + Do not set this field in API requests. + """ + + class PriceRange(proto.Message): + r"""The price range of all + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. + + Attributes: + price (google.cloud.retail_v2beta.types.Interval): + The inclusive + [Product.pricing_info.price][google.cloud.retail.v2beta.PriceInfo.price] + interval of all + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] having the + same + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. + original_price (google.cloud.retail_v2beta.types.Interval): + The inclusive + [Product.pricing_info.original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + internal of all + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] having the + same + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. + """ + + price = proto.Field( + proto.MESSAGE, + number=1, + message='Interval', + ) + original_price = proto.Field( + proto.MESSAGE, + number=2, + message='Interval', + ) + + currency_code = proto.Field( + proto.STRING, + number=1, + ) + price = proto.Field( + proto.FLOAT, + number=2, + ) + original_price = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + price_effective_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + price_expire_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + price_range = proto.Field( + proto.MESSAGE, + number=7, + message=PriceRange, + ) + + +class Rating(proto.Message): + r"""The rating of a [Product][google.cloud.retail.v2beta.Product]. + + Attributes: + rating_count (int): + The total number of ratings. This value is independent of + the value of + [rating_histogram][google.cloud.retail.v2beta.Rating.rating_histogram]. + + This value must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + average_rating (float): + The average rating of the + [Product][google.cloud.retail.v2beta.Product]. + + The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT + error is returned. + rating_histogram (Sequence[int]): + List of rating counts per rating value (index = rating - 1). + The list is empty if there is no rating. If the list is + non-empty, its size is always 5. Otherwise, an + INVALID_ARGUMENT error is returned. + + For example, [41, 14, 13, 47, 303]. It means that the + [Product][google.cloud.retail.v2beta.Product] got 41 ratings + with 1 star, 14 ratings with 2 star, and so on. + """ + + rating_count = proto.Field( + proto.INT32, + number=1, + ) + average_rating = proto.Field( + proto.FLOAT, + number=2, + ) + rating_histogram = proto.RepeatedField( + proto.INT32, + number=3, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. + + Always use a hashed value for this ID. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + ip_address (str): + The end user's IP address. This field is used to extract + location information for personalization. + + This field must be either an IPv4 address (e.g. + "104.133.9.80") or an IPv6 address (e.g. + "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an + INVALID_ARGUMENT error is returned. + + This should not be set when: + + - setting + [SearchRequest.user_info][google.cloud.retail.v2beta.SearchRequest.user_info]. + - using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2beta.UserInfo.direct_user_request] + is set. + user_agent (str): + User agent as included in the HTTP header. Required for + getting + [SearchResponse.sponsored_results][google.cloud.retail.v2beta.SearchResponse.sponsored_results]. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2beta.UserInfo.direct_user_request] + is set. + direct_user_request (bool): + True if the request is made directly from the end user, in + which case the + [ip_address][google.cloud.retail.v2beta.UserInfo.ip_address] + and + [user_agent][google.cloud.retail.v2beta.UserInfo.user_agent] + can be populated from the HTTP request. This flag should be + set only if the API request is made directly from the end + user such as a mobile app (and not if a gateway or a server + is processing and pushing the user events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent]. + """ + + user_id = proto.Field( + proto.STRING, + number=1, + ) + ip_address = proto.Field( + proto.STRING, + number=2, + ) + user_agent = proto.Field( + proto.STRING, + number=3, + ) + direct_user_request = proto.Field( + proto.BOOL, + number=4, + ) + + +class LocalInventory(proto.Message): + r"""The inventory information at a place (e.g. a store) + identified by a place ID. + + Attributes: + place_id (str): + The place ID for the current set of inventory + information. + price_info (google.cloud.retail_v2beta.types.PriceInfo): + Product price and cost information. + + Google Merchant Center property + `price `__. + attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): + Additional local inventory attributes, for example, store + name, promotion tags, etc. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - At most 30 attributes are allowed. + - The key must be a UTF-8 encoded string with a length + limit of 32 characters. + - The key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis + or KEY_1_LIKE_THIS. + - The attribute values must be of the same type (text or + number). + - Only 1 value is allowed for each attribute. + - For text values, the length limit is 256 UTF-8 + characters. + - The attribute does not support search. The ``searchable`` + field should be unset or set to false. + - The max summed total bytes of custom attribute keys and + values per product is 5MiB. + fulfillment_types (Sequence[str]): + Input only. Supported fulfillment types. Valid fulfillment + type values include commonly used types (such as pickup in + store and same day delivery), and custom types. Customers + have to map custom types to their display names before + rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + All the elements must be distinct. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + place_id = proto.Field( + proto.STRING, + number=1, + ) + price_info = proto.Field( + proto.MESSAGE, + number=2, + message='PriceInfo', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='CustomAttribute', + ) + fulfillment_types = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py new file mode 100644 index 00000000..47e39772 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'CompleteQueryRequest', + 'CompleteQueryResponse', + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Auto-complete parameters. + + Attributes: + catalog (str): + Required. Catalog for which the completion is performed. + + Full resource name of catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + query (str): + Required. The query used to generate + suggestions. + The maximum number of allowed characters is 255. + visitor_id (str): + Required field. A unique identifier for tracking visitors. + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + language_codes (Sequence[str]): + The language filters applied to the output suggestions. If + set, it should contain the language of the query. If not + set, suggestions are returned without considering language + restrictions. This is the BCP-47 language code, such as + "en-US" or "sr-Latn". For more information, see `Tags for + Identifying + Languages `__. The + maximum number of language codes is 3. + device_type (str): + The device type context for completion suggestions. It is + useful to apply different suggestions on different device + types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the + suggestions are across all device types. + + Supported formats: + + - ``UNKNOWN_DEVICE_TYPE`` + + - ``DESKTOP`` + + - ``MOBILE`` + + - A customized string starts with ``OTHER_``, e.g. + ``OTHER_IPHONE``. + dataset (str): + Determines which dataset to use for fetching completion. + "user-data" will use the imported dataset through + [CompletionService.ImportCompletionData][google.cloud.retail.v2beta.CompletionService.ImportCompletionData]. + "cloud-retail" will use the dataset generated by cloud + retail based on user events. If leave empty, it will use the + "user-data". + + Current supported values: + + - user-data + + - cloud-retail This option requires additional + allowlisting. Before using cloud-retail, contact Cloud + Retail support team first. + max_suggestions (int): + Completion max suggestions. If left unset or set to 0, then + will fallback to the configured value + [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions]. + + The maximum allowed max suggestions is 20. If it is set + higher, it will be capped by 20. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + visitor_id = proto.Field( + proto.STRING, + number=7, + ) + language_codes = proto.RepeatedField( + proto.STRING, + number=3, + ) + device_type = proto.Field( + proto.STRING, + number=4, + ) + dataset = proto.Field( + proto.STRING, + number=6, + ) + max_suggestions = proto.Field( + proto.INT32, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response of the auto-complete query. + + Attributes: + completion_results (Sequence[google.cloud.retail_v2beta.types.CompleteQueryResponse.CompletionResult]): + Results of the matching suggestions. The + result list is ordered and the first result is + top suggestion. + attribution_token (str): + A unique complete token. This should be included in the + [UserEvent.completion_detail][google.cloud.retail.v2beta.UserEvent.completion_detail] + for search events resulting from this completion, which + enables accurate attribution of complete model performance. + recent_search_results (Sequence[google.cloud.retail_v2beta.types.CompleteQueryResponse.RecentSearchResult]): + Matched recent searches of this user. The maximum number of + recent searches is 10. This field is a restricted feature. + Contact Retail Search support team if you are interested in + enabling it. + + This feature is only available when + [CompleteQueryRequest.visitor_id][google.cloud.retail.v2beta.CompleteQueryRequest.visitor_id] + field is set and + [UserEvent][google.cloud.retail.v2beta.UserEvent] is + imported. The recent searches satisfy the follow rules: + + - They are ordered from latest to oldest. + - They are matched with + [CompleteQueryRequest.query][google.cloud.retail.v2beta.CompleteQueryRequest.query] + case insensitively. + - They are transformed to lower cases. + - They are UTF-8 safe. + + Recent searches are deduplicated. More recent searches will + be reserved when duplication happens. + """ + + class CompletionResult(proto.Message): + r"""Resource that represents completion results. + + Attributes: + suggestion (str): + The suggestion for the query. + attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): + Custom attributes for the suggestion term. + + - For "user-data", the attributes are additional custom + attributes ingested through BigQuery. + - For "cloud-retail", the attributes are product attributes + generated by Cloud Retail. + """ + + suggestion = proto.Field( + proto.STRING, + number=1, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=common.CustomAttribute, + ) + + class RecentSearchResult(proto.Message): + r"""Recent search of this user. + + Attributes: + recent_search (str): + The recent search query. + """ + + recent_search = proto.Field( + proto.STRING, + number=1, + ) + + completion_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=CompletionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + recent_search_results = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=RecentSearchResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py new file mode 100644 index 00000000..0c7cdc3d --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'Control', + }, +) + + +class Control(proto.Message): + r"""Configures dynamic serving time metadata that is used to pre + and post process search/recommendation model results. + + 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: + facet_spec (google.cloud.retail_v2beta.types.SearchRequest.FacetSpec): + A facet specification to perform faceted + search. + + This field is a member of `oneof`_ ``control``. + rule (google.cloud.retail_v2beta.types.Rule): + A rule control - a condition-action pair. + Enacts a set action when the condition is + triggered. For example: Boost "gShoe" when query + full matches "Running Shoes". + + This field is a member of `oneof`_ ``control``. + name (str): + Immutable. Fully qualified name + projects/\ */locations/global/catalogs/*/controls/\* + display_name (str): + Required. The human readable control display name. Used in + Retail UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is thrown. + associated_serving_config_ids (Sequence[str]): + Output only. List of serving configuration + ids that that are associated with this control. + Note the association is managed via the + ServingConfig, this is an output only + denormalizeed view. Assumed to be in the same + catalog. + solution_types (Sequence[google.cloud.retail_v2beta.types.SolutionType]): + Required. Immutable. The solution types that the serving + config is used for. Currently we support setting only one + type of solution at creation time. + + Only ``SOLUTION_TYPE_SEARCH`` value is supported at the + moment. If no solution type is provided at creation time, + will default to SOLUTION_TYPE_SEARCH. + """ + + facet_spec = proto.Field( + proto.MESSAGE, + number=3, + oneof='control', + message=search_service.SearchRequest.FacetSpec, + ) + rule = proto.Field( + proto.MESSAGE, + number=4, + oneof='control', + message=common.Rule, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + associated_serving_config_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + solution_types = proto.RepeatedField( + proto.ENUM, + number=6, + enum=common.SolutionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py new file mode 100644 index 00000000..17120bb5 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import control as gcr_control +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'CreateControlRequest', + 'UpdateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + }, +) + + +class CreateControlRequest(proto.Message): + r"""Request for CreateControl method. + + Attributes: + parent (str): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + control (google.cloud.retail_v2beta.types.Control): + Required. The Control to create. + control_id (str): + Required. The ID to use for the Control, which will become + the final component of the Control's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-_/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + control = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_control.Control, + ) + control_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateControlRequest(proto.Message): + r"""Request for UpdateControl method. + + Attributes: + control (google.cloud.retail_v2beta.types.Control): + Required. The Control to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Control][google.cloud.retail.v2beta.Control] to update. The + following are NOT supported: + + - [Control.name][google.cloud.retail.v2beta.Control.name] + + If not set or empty, all supported fields are updated. + """ + + control = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_control.Control, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteControlRequest(proto.Message): + r"""Request for DeleteControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetControlRequest(proto.Message): + r"""Request for GetControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListControlsRequest(proto.Message): + r"""Request for ListControls method. + + Attributes: + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 50. Max + allowed value is 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListControls`` call. Provide this to retrieve the + subsequent page. + filter (str): + Optional. A filter to apply on the list results. Supported + features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2beta.ListControlsRequest.filter] + is unset. + - List controls that are used in a single ServingConfig: + 'serving_config = "boosted_home_page_cvr"' + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListControlsResponse(proto.Message): + r"""Response for ListControls method. + + Attributes: + controls (Sequence[google.cloud.retail_v2beta.types.Control]): + All the Controls for a given catalog. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + controls = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_control.Control, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py new file mode 100644 index 00000000..b020964a --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + }, +) + + +class ExportErrorsConfig(proto.Message): + r"""Configuration of destination for Export related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage path for import errors. This must be an + empty, existing Cloud Storage bucket. Export errors will be + written to a file in this bucket, one per line, as a + JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ExportMetadata(proto.Message): + r"""Metadata related to the progress of the Export operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ExportProductsResponse(proto.Message): + r"""Response of the ExportProductsRequest. If the long running + operation is done, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2beta.types.ExportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExportErrorsConfig', + ) + + +class ExportUserEventsResponse(proto.Message): + r"""Response of the ExportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2beta.types.ExportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExportErrorsConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py new file mode 100644 index 00000000..a32de943 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py @@ -0,0 +1,691 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import user_event +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'GcsSource', + 'BigQuerySource', + 'ProductInlineSource', + 'UserEventInlineSource', + 'ImportErrorsConfig', + 'ImportProductsRequest', + 'ImportUserEventsRequest', + 'ImportCompletionDataRequest', + 'ProductInputConfig', + 'UserEventInputConfig', + 'CompletionDataInputConfig', + 'ImportMetadata', + 'ImportProductsResponse', + 'ImportUserEventsResponse', + 'UserEventImportSummary', + 'ImportCompletionDataResponse', + }, +) + + +class GcsSource(proto.Message): + r"""Google Cloud Storage location for input content. + format. + + Attributes: + input_uris (Sequence[str]): + Required. Google Cloud Storage URIs to input files. URI can + be up to 2000 characters long. URIs can match the full + object path (for example, + ``gs://bucket/directory/object.json``) or a pattern matching + one or more files, such as ``gs://bucket/directory/*.json``. + A request can contain at most 100 files, and each file can + be up to 2 GB. See `Importing product + information `__ + for the expected file format and setup instructions. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2beta.Product] per line. + Each product must have a valid + [Product.id][google.cloud.retail.v2beta.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2beta.UserEvent] per + line. + - ``user_event_ga360``: Using + https://support.google.com/analytics/answer/3437719. + + Supported values for control imports: + + - 'control' (default): One JSON + [Control][google.cloud.retail.v2beta.Control] per line. + + Supported values for catalog attribute imports: + + - 'catalog_attribute' (default): One CSV + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + per line. + """ + + input_uris = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2beta.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID (can be project # or ID) that + the BigQuery source is in with a length limit of + 128 characters. If not specified, inherits the + project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2beta.Product] per line. + Each product must have a valid + [Product.id][google.cloud.retail.v2beta.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2beta.UserEvent] per + line. + - ``user_event_ga360``: The schema is available here: + https://support.google.com/analytics/answer/3437719. + - ``user_event_ga4``: This feature is in private preview. + Please contact the support team for importing Google + Analytics 4 events. The schema is available here: + https://support.google.com/analytics/answer/7029846. + + Supported values for auto-completion imports: + + - ``suggestions`` (default): One JSON completion suggestion + per line. + - ``denylist``: One JSON deny suggestion per line. + - ``allowlist``: One JSON allow suggestion per line. + """ + + partition_date = proto.Field( + proto.MESSAGE, + number=6, + oneof='partition', + message=date_pb2.Date, + ) + project_id = proto.Field( + proto.STRING, + number=5, + ) + dataset_id = proto.Field( + proto.STRING, + number=1, + ) + table_id = proto.Field( + proto.STRING, + number=2, + ) + gcs_staging_dir = proto.Field( + proto.STRING, + number=3, + ) + data_schema = proto.Field( + proto.STRING, + number=4, + ) + + +class ProductInlineSource(proto.Message): + r"""The inline source for the input config for ImportProducts + method. + + Attributes: + products (Sequence[google.cloud.retail_v2beta.types.Product]): + Required. A list of products to update/create. Each product + must have a valid + [Product.id][google.cloud.retail.v2beta.Product.id]. + Recommended max of 100 items. + """ + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=product.Product, + ) + + +class UserEventInlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (Sequence[google.cloud.retail_v2beta.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + +class ImportErrorsConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage prefix for import errors. This must be + an empty, existing Cloud Storage directory. Import errors + will be written to sharded files in this directory, one per + line, as a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportProductsRequest(proto.Message): + r"""Request message for Import methods. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` + + If no updateMask is specified, requires products.create + permission. If updateMask is specified, requires + products.update permission. + request_id (str): + Deprecated. This field has no effect. + input_config (google.cloud.retail_v2beta.types.ProductInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported 'products' to update. If not set, will + by default update all fields. + reconciliation_mode (google.cloud.retail_v2beta.types.ImportProductsRequest.ReconciliationMode): + The mode of reconciliation between existing products and the + products to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2beta.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2beta.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + """ + class ReconciliationMode(proto.Enum): + r"""Indicates how imported products are reconciled with the + existing products created or imported before. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + request_id = proto.Field( + proto.STRING, + number=6, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='ProductInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + reconciliation_mode = proto.Field( + proto.ENUM, + number=5, + enum=ReconciliationMode, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=7, + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + input_config (google.cloud.retail_v2beta.types.UserEventInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='UserEventInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + + +class ImportCompletionDataRequest(proto.Message): + r"""Request message for ImportCompletionData methods. + + Attributes: + parent (str): + Required. The catalog which the suggestions dataset belongs + to. + + Format: + ``projects/1234/locations/global/catalogs/default_catalog``. + input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): + Required. The desired input location of the + data. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='CompletionDataInputConfig', + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=3, + ) + + +class ProductInputConfig(proto.Message): + r"""The input config source for products. + + 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: + product_inline_source (google.cloud.retail_v2beta.types.ProductInlineSource): + The Inline source for the input content for + products. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2beta.types.GcsSource): + Google Cloud Storage location for the input + content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + product_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='ProductInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class UserEventInputConfig(proto.Message): + r"""The input config source for user events. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user_event_inline_source (google.cloud.retail_v2beta.types.UserEventInlineSource): + Required. The Inline source for the input + content for UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2beta.types.GcsSource): + Required. Google Cloud Storage location for + the input content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): + Required. BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + user_event_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='UserEventInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class CompletionDataInputConfig(proto.Message): + r"""The input config source for completion data. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): + Required. BigQuery input source. + Add the IAM permission "BigQuery Data Viewer" + for + cloud-retail-customer-data-access@system.gserviceaccount.com + before using this feature otherwise an error is + thrown. + + This field is a member of `oneof`_ ``source``. + """ + + big_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='BigQuerySource', + ) + + +class ImportMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + request_id (str): + Deprecated. This field is never set. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=3, + ) + failure_count = proto.Field( + proto.INT64, + number=4, + ) + request_id = proto.Field( + proto.STRING, + number=5, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=6, + ) + + +class ImportProductsResponse(proto.Message): + r"""Response of the + [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + import_summary (google.cloud.retail_v2beta.types.UserEventImportSummary): + Aggregated statistics of user event import + status. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + import_summary = proto.Field( + proto.MESSAGE, + number=3, + message='UserEventImportSummary', + ) + + +class UserEventImportSummary(proto.Message): + r"""A summary of import result. The UserEventImportSummary + summarizes the import status for user events. + + Attributes: + joined_events_count (int): + Count of user events imported with complete + existing catalog information. + unjoined_events_count (int): + Count of user events imported, but with + catalog information not found in the imported + catalog. + """ + + joined_events_count = proto.Field( + proto.INT64, + number=1, + ) + unjoined_events_count = proto.Field( + proto.INT64, + number=2, + ) + + +class ImportCompletionDataResponse(proto.Message): + r"""Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. + 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 (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py new file mode 100644 index 00000000..f31ba819 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import user_event as gcr_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'PredictRequest', + 'PredictResponse', + }, +) + + +class PredictRequest(proto.Message): + r"""Request message for Predict method. + + Attributes: + placement (str): + Required. Full resource name of the format: + {name=projects/*/locations/global/catalogs/default_catalog/placements/*} + The ID of the Recommendations AI placement. Before you can + request predictions from your model, you must create at + least one placement for it. For more information, see + `Managing + placements `__. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements + user_event (google.cloud.retail_v2beta.types.UserEvent): + Required. Context about the user, what they + are looking at and what action they took to + trigger the predict request. Note that this user + event detail won't be ingested to userEvent + logs. Thus, a separate userEvent write request + is required for event logging. + page_size (int): + Maximum number of results to return per page. + Set this property to the number of prediction + results needed. If zero, the service will choose + a reasonable default. The maximum allowed value + is 100. Values above 100 will be coerced to 100. + page_token (str): + The previous PredictResponse.next_page_token. + filter (str): + Filter for restricting prediction results with a length + limit of 5,000 characters. Accepts values for tags and the + ``filterOutOfStockItems`` flag. + + - Tag expressions. Restricts predictions to products that + match all of the specified tags. Boolean operators ``OR`` + and ``NOT`` are supported if the expression is enclosed + in parentheses, and must be separated from the tag values + by a space. ``-"tagA"`` is also supported and is + equivalent to ``NOT "tagA"``. Tag values must be double + quoted UTF-8 encoded strings with a size limit of 1,000 + characters. + + Note: "Recently viewed" models don't support tag + filtering at the moment. + + - filterOutOfStockItems. Restricts predictions to products + that do not have a stockState value of OUT_OF_STOCK. + + Examples: + + - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT + "promotional") + - filterOutOfStockItems tag=(-"promotional") + - filterOutOfStockItems + + If your filter blocks all prediction results, the API will + return generic (unfiltered) popular products. If you only + want results strictly matching the filters, set + ``strictFiltering`` to True in ``PredictRequest.params`` to + receive empty results instead. Note that the API will never + return items with storageStatus of "EXPIRED" or "DELETED" + regardless of filter choices. + validate_only (bool): + Use validate only mode for this prediction + query. If set to true, a dummy model will be + used that returns arbitrary products. Note that + the validate only mode should only be used for + testing the API, or if the model is not ready. + params (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific parameters for the predictions. + + Allowed values: + + - ``returnProduct``: Boolean. If set to true, the + associated product object will be returned in the + ``results.metadata`` field in the prediction response. + - ``returnScore``: Boolean. If set to true, the prediction + 'score' corresponding to each returned product will be + set in the ``results.metadata`` field in the prediction + response. The given 'score' indicates the probability of + an product being clicked/purchased given the user's + context and history. + - ``strictFiltering``: Boolean. True by default. If set to + false, the service will return generic (unfiltered) + popular products instead of empty if your filter blocks + all prediction results. + - ``priceRerankLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of + {'no-price-reranking', 'low-price-reranking', + 'medium-price-reranking', 'high-price-reranking'}. This + gives request-level control and adjusts prediction + results based on product price. + - ``diversityLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of {'no-diversity', + 'low-diversity', 'medium-diversity', 'high-diversity', + 'auto-diversity'}. This gives request-level control and + adjusts prediction results based on product category. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters, and cannot be empty. Values can + be empty, and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + placement = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + filter = proto.Field( + proto.STRING, + number=5, + ) + validate_only = proto.Field( + proto.BOOL, + number=6, + ) + params = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class PredictResponse(proto.Message): + r"""Response message for predict method. + + Attributes: + results (Sequence[google.cloud.retail_v2beta.types.PredictResponse.PredictionResult]): + A list of recommended products. The order + represents the ranking (from the most relevant + product to the least). + attribution_token (str): + A unique attribution token. This should be included in the + [UserEvent][google.cloud.retail.v2beta.UserEvent] logs + resulting from this recommendation, which enables accurate + attribution of recommendation model performance. + missing_ids (Sequence[str]): + IDs of products in the request that were + missing from the inventory. + validate_only (bool): + True if the validateOnly property was set in + the request. + """ + + class PredictionResult(proto.Message): + r"""PredictionResult represents the recommendation prediction + results. + + Attributes: + id (str): + ID of the recommended product + metadata (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional product metadata / annotations. + + Possible values: + + - ``product``: JSON representation of the product. Will be + set if ``returnProduct`` is set to true in + ``PredictRequest.params``. + - ``score``: Prediction score in double value. Will be set + if ``returnScore`` is set to true in + ``PredictRequest.params``. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + metadata = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=PredictionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + missing_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py new file mode 100644 index 00000000..bd0de773 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py @@ -0,0 +1,705 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'Product', + }, +) + + +class Product(proto.Message): + r"""Product captures all metadata information of items to be + recommended or searched. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this product becomes unavailable for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + If it is set, the + [Product][google.cloud.retail.v2beta.Product] is not + available for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + after + [expire_time][google.cloud.retail.v2beta.Product.expire_time]. + However, the product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + [expire_time][google.cloud.retail.v2beta.Product.expire_time] + must be later than + [available_time][google.cloud.retail.v2beta.Product.available_time] + and + [publish_time][google.cloud.retail.v2beta.Product.publish_time], + otherwise an INVALID_ARGUMENT error is thrown. + + Corresponding properties: Google Merchant Center property + `expiration_date `__. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Input only. The TTL (time to live) of the product. + + If it is set, it must be a non-negative value, and + [expire_time][google.cloud.retail.v2beta.Product.expire_time] + is set as current timestamp plus + [ttl][google.cloud.retail.v2beta.Product.ttl]. The derived + [expire_time][google.cloud.retail.v2beta.Product.expire_time] + is returned in the output and + [ttl][google.cloud.retail.v2beta.Product.ttl] is left blank + when retrieving the + [Product][google.cloud.retail.v2beta.Product]. + + If it is set, the product is not available for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + after current timestamp plus + [ttl][google.cloud.retail.v2beta.Product.ttl]. However, the + product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This field is a member of `oneof`_ ``expiration``. + name (str): + Immutable. Full resource name of the product, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. + id (str): + Immutable. [Product][google.cloud.retail.v2beta.Product] + identifier, which is the final component of + [name][google.cloud.retail.v2beta.Product.name]. For + example, this field is "id_1", if + [name][google.cloud.retail.v2beta.Product.name] is + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `id `__. + Schema.org property + `Product.sku `__. + type_ (google.cloud.retail_v2beta.types.Product.Type): + Immutable. The type of the product. Default to + [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2beta.ProductLevelConfig.ingestion_product_type] + if unset. + primary_product_id (str): + Variant group identifier. Must be an + [id][google.cloud.retail.v2beta.Product.id], with the same + parent branch with this product. Otherwise, an error is + thrown. + + For + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]s, this field + can only be empty or set to the same value as + [id][google.cloud.retail.v2beta.Product.id]. + + For VARIANT [Product][google.cloud.retail.v2beta.Product]s, + this field cannot be empty. A maximum of 2,000 products are + allowed to share the same + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `item_group_id `__. + Schema.org property + `Product.inProductGroupWithID `__. + collection_member_ids (Sequence[str]): + The [id][google.cloud.retail.v2beta.Product.id] of the + collection members when + [type][google.cloud.retail.v2beta.Product.type] is + [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION]. + + Non-existent product ids are allowed. The + [type][google.cloud.retail.v2beta.Product.type] of the + members must be either + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + or + [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + otherwise and INVALID_ARGUMENT error is thrown. Should not + set it for other types. A maximum of 1000 values are + allowed. Otherwise, an INVALID_ARGUMENT error is return. + gtin (str): + The Global Trade Item Number (GTIN) of the product. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This field must be a Unigram. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `gtin `__. + Schema.org property + `Product.isbn `__, + `Product.gtin8 `__, + `Product.gtin12 `__, + `Product.gtin13 `__, or + `Product.gtin14 `__. + + If the value is not a valid GTIN, an INVALID_ARGUMENT error + is returned. + categories (Sequence[str]): + Product categories. This field is repeated for supporting + one product belonging to several parallel categories. + Strongly recommended using the full path for better search / + recommendation quality. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + For example, if a shoes product belongs to both ["Shoes & + Accessories" -> "Shoes"] and ["Sports & Fitness" -> + "Athletic Clothing" -> "Shoes"], it could be represented as: + + :: + + "categories": [ + "Shoes & Accessories > Shoes", + "Sports & Fitness > Athletic Clothing > Shoes" + ] + + Must be set for + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] otherwise an + INVALID_ARGUMENT error is returned. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2beta.Product]. Empty values + are not allowed. Each value must be a UTF-8 encoded string + with a length limit of 5,000 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `google_product_category `__. + Schema.org property [Product.category] + (https://schema.org/category). + title (str): + Required. Product title. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `title `__. + Schema.org property + `Product.name `__. + brands (Sequence[str]): + The brands of the product. + + A maximum of 30 brands are allowed. Each brand must be a + UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `brand `__. + Schema.org property + `Product.brand `__. + description (str): + Product description. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `description `__. + Schema.org property + `Product.description `__. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. + + For product prediction, this field is ignored and the model + automatically detects the text language. The + [Product][google.cloud.retail.v2beta.Product] can include + text in different languages, but duplicating + [Product][google.cloud.retail.v2beta.Product]s to provide + text in multiple languages can result in degraded model + performance. + + For product search this field is in use. It defaults to + "en-US" if unset. + attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): + Highly encouraged. Extra product attributes to be included. + For example, for products, this could include the store + name, vendor, style, color, etc. These are very strong + signals for recommendation model, thus we highly recommend + providing the attributes here. + + Features that can take on one of a limited number of + possible values. Two types of features can be set are: + + Textual features. some examples would be the brand/maker of + a product, or country of a customer. Numerical features. + Some examples would be the height/weight of a product, or + age of a customer. + + For example: + ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - Max entries count: 200. + - The key must be a UTF-8 encoded string with a length + limit of 128 characters. + - For indexable attribute, the key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, + ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a + non-empty UTF-8 encoded string with a length limit of 256 + characters. + - For number attributes, at most 400 values are allowed. + tags (Sequence[str]): + Custom tags associated with the product. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2beta.Product]. This value + must be a UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This tag can be used for filtering recommendation results by + passing the tag as part of the + [PredictRequest.filter][google.cloud.retail.v2beta.PredictRequest.filter]. + + Corresponding properties: Google Merchant Center property + `custom_label_0–4 `__. + price_info (google.cloud.retail_v2beta.types.PriceInfo): + Product price and cost information. + + Corresponding properties: Google Merchant Center property + `price `__. + rating (google.cloud.retail_v2beta.types.Rating): + The rating of this product. + available_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this + [Product][google.cloud.retail.v2beta.Product] becomes + available for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + availability (google.cloud.retail_v2beta.types.Product.Availability): + The online availability of the + [Product][google.cloud.retail.v2beta.Product]. Default to + [Availability.IN_STOCK][google.cloud.retail.v2beta.Product.Availability.IN_STOCK]. + + Corresponding properties: Google Merchant Center property + `availability `__. + Schema.org property + `Offer.availability `__. + available_quantity (google.protobuf.wrappers_pb2.Int32Value): + The available quantity of the item. + fulfillment_info (Sequence[google.cloud.retail_v2beta.types.FulfillmentInfo]): + Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + All the elements must have distinct + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type]. + Otherwise, an INVALID_ARGUMENT error is returned. + uri (str): + Canonical URL directly linking to the product detail page. + + It is strongly recommended to provide a valid uri for the + product, otherwise the service performance could be + significantly degraded. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `link `__. + Schema.org property `Offer.url `__. + images (Sequence[google.cloud.retail_v2beta.types.Image]): + Product images for the product. We highly recommend putting + the main image first. + + A maximum of 300 images are allowed. + + Corresponding properties: Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + audience (google.cloud.retail_v2beta.types.Audience): + The target group associated with a given + audience (e.g. male, veterans, car owners, + musicians, etc.) of the product. + color_info (google.cloud.retail_v2beta.types.ColorInfo): + The color of the product. + + Corresponding properties: Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + sizes (Sequence[str]): + The size of the product. To represent different size systems + or size types, consider using this format: + [[[size_system:]size_type:]size_value]. + + For example, in "US:MENS:M", "US" represents size system; + "MENS" represents size type; "M" represents size value. In + "GIRLS:27", size system is empty; "GIRLS" represents size + type; "27" represents size value. In "32 inches", both size + system and size type are empty, while size value is "32 + inches". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2beta.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `size `__, + `size_type `__, + and + `size_system `__. + Schema.org property + `Product.size `__. + materials (Sequence[str]): + The material of the product. For example, "leather", + "wooden". + + A maximum of 20 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 200 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `material `__. + Schema.org property + `Product.material `__. + patterns (Sequence[str]): + The pattern or graphic print of the product. For example, + "striped", "polka dot", "paisley". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2beta.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `pattern `__. + Schema.org property + `Product.pattern `__. + conditions (Sequence[str]): + The condition of the product. Strongly encouraged to use the + standard values: "new", "refurbished", "used". + + A maximum of 1 value is allowed per + [Product][google.cloud.retail.v2beta.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `condition `__. + Schema.org property + `Offer.itemCondition `__. + promotions (Sequence[google.cloud.retail_v2beta.types.Promotion]): + The promotions applied to the product. A maximum of 10 + values are allowed per + [Product][google.cloud.retail.v2beta.Product]. Only + [Promotion.promotion_id][google.cloud.retail.v2beta.Promotion.promotion_id] + will be used, other fields will be ignored if set. + publish_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the product is published by the retailer + for the first time, which indicates the freshness of the + products. Note that this field is different from + [available_time][google.cloud.retail.v2beta.Product.available_time], + given it purely describes product freshness regardless of + when it is available on search and recommendation. + retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the + [Product][google.cloud.retail.v2beta.Product]s are returned + in + [SearchResponse][google.cloud.retail.v2beta.SearchResponse]. + + Supported fields for all + [type][google.cloud.retail.v2beta.Product.type]s: + + - [audience][google.cloud.retail.v2beta.Product.audience] + - [availability][google.cloud.retail.v2beta.Product.availability] + - [brands][google.cloud.retail.v2beta.Product.brands] + - [color_info][google.cloud.retail.v2beta.Product.color_info] + - [conditions][google.cloud.retail.v2beta.Product.conditions] + - [gtin][google.cloud.retail.v2beta.Product.gtin] + - [materials][google.cloud.retail.v2beta.Product.materials] + - [name][google.cloud.retail.v2beta.Product.name] + - [patterns][google.cloud.retail.v2beta.Product.patterns] + - [price_info][google.cloud.retail.v2beta.Product.price_info] + - [rating][google.cloud.retail.v2beta.Product.rating] + - [sizes][google.cloud.retail.v2beta.Product.sizes] + - [title][google.cloud.retail.v2beta.Product.title] + - [uri][google.cloud.retail.v2beta.Product.uri] + + Supported fields only for + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION]: + + - [categories][google.cloud.retail.v2beta.Product.categories] + - [description][google.cloud.retail.v2beta.Product.description] + - [images][google.cloud.retail.v2beta.Product.images] + + Supported fields only for + [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT]: + + - Only the first image in + [images][google.cloud.retail.v2beta.Product.images] + + To mark + [attributes][google.cloud.retail.v2beta.Product.attributes] + as retrievable, include paths of the form "attributes.key" + where "key" is the key of a custom attribute, as specified + in + [attributes][google.cloud.retail.v2beta.Product.attributes]. + + For + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION], + the following fields are always returned in + [SearchResponse][google.cloud.retail.v2beta.SearchResponse] + by default: + + - [name][google.cloud.retail.v2beta.Product.name] + + For + [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT], + the following fields are always returned in by default: + + - [name][google.cloud.retail.v2beta.Product.name] + - [color_info][google.cloud.retail.v2beta.Product.color_info] + + Maximum number of paths is 30. Otherwise, an + INVALID_ARGUMENT error is returned. + + Note: Returning more fields in + [SearchResponse][google.cloud.retail.v2beta.SearchResponse] + may increase response payload size and serving latency. + variants (Sequence[google.cloud.retail_v2beta.types.Product]): + Output only. Product variants grouped together on primary + product which share similar product attributes. It's + automatically grouped by + [primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] + for all the product variants. Only populated for + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct]. + Do not set this field in API requests. + """ + class Type(proto.Enum): + r"""The type of this product.""" + TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + VARIANT = 2 + COLLECTION = 3 + + class Availability(proto.Enum): + r"""Product availability. If this field is unspecified, the + product is assumed to be in stock. + """ + AVAILABILITY_UNSPECIFIED = 0 + IN_STOCK = 1 + OUT_OF_STOCK = 2 + PREORDER = 3 + BACKORDER = 4 + + expire_time = proto.Field( + proto.MESSAGE, + number=16, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl = proto.Field( + proto.MESSAGE, + number=17, + oneof='expiration', + message=duration_pb2.Duration, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + type_ = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + primary_product_id = proto.Field( + proto.STRING, + number=4, + ) + collection_member_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + gtin = proto.Field( + proto.STRING, + number=6, + ) + categories = proto.RepeatedField( + proto.STRING, + number=7, + ) + title = proto.Field( + proto.STRING, + number=8, + ) + brands = proto.RepeatedField( + proto.STRING, + number=9, + ) + description = proto.Field( + proto.STRING, + number=10, + ) + language_code = proto.Field( + proto.STRING, + number=11, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message=common.CustomAttribute, + ) + tags = proto.RepeatedField( + proto.STRING, + number=13, + ) + price_info = proto.Field( + proto.MESSAGE, + number=14, + message=common.PriceInfo, + ) + rating = proto.Field( + proto.MESSAGE, + number=15, + message=common.Rating, + ) + available_time = proto.Field( + proto.MESSAGE, + number=18, + message=timestamp_pb2.Timestamp, + ) + availability = proto.Field( + proto.ENUM, + number=19, + enum=Availability, + ) + available_quantity = proto.Field( + proto.MESSAGE, + number=20, + message=wrappers_pb2.Int32Value, + ) + fulfillment_info = proto.RepeatedField( + proto.MESSAGE, + number=21, + message=common.FulfillmentInfo, + ) + uri = proto.Field( + proto.STRING, + number=22, + ) + images = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=common.Image, + ) + audience = proto.Field( + proto.MESSAGE, + number=24, + message=common.Audience, + ) + color_info = proto.Field( + proto.MESSAGE, + number=25, + message=common.ColorInfo, + ) + sizes = proto.RepeatedField( + proto.STRING, + number=26, + ) + materials = proto.RepeatedField( + proto.STRING, + number=27, + ) + patterns = proto.RepeatedField( + proto.STRING, + number=28, + ) + conditions = proto.RepeatedField( + proto.STRING, + number=29, + ) + promotions = proto.RepeatedField( + proto.MESSAGE, + number=34, + message=promotion.Promotion, + ) + publish_time = proto.Field( + proto.MESSAGE, + number=33, + message=timestamp_pb2.Timestamp, + ) + retrievable_fields = proto.Field( + proto.MESSAGE, + number=30, + message=field_mask_pb2.FieldMask, + ) + variants = proto.RepeatedField( + proto.MESSAGE, + number=31, + message='Product', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py new file mode 100644 index 00000000..06a23d13 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py @@ -0,0 +1,844 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'CreateProductRequest', + 'GetProductRequest', + 'UpdateProductRequest', + 'DeleteProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'SetInventoryRequest', + 'SetInventoryMetadata', + 'SetInventoryResponse', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesResponse', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesResponse', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesResponse', + }, +) + + +class CreateProductRequest(proto.Message): + r"""Request message for [CreateProduct][] method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + product (google.cloud.retail_v2beta.types.Product): + Required. The [Product][google.cloud.retail.v2beta.Product] + to create. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2beta.Product], which will + become the final component of the + [Product.name][google.cloud.retail.v2beta.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2beta.Product]s with the same + [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + product_id = proto.Field( + proto.STRING, + number=3, + ) + + +class GetProductRequest(proto.Message): + r"""Request message for [GetProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested + [Product][google.cloud.retail.v2beta.Product] does not + exist, a NOT_FOUND error is returned. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateProductRequest(proto.Message): + r"""Request message for [UpdateProduct][] method. + + Attributes: + product (google.cloud.retail_v2beta.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Product][google.cloud.retail.v2beta.Product] to update. The + immutable and output only fields are NOT supported. If not + set, all supported fields (the fields that are neither + immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + a new [Product][google.cloud.retail.v2beta.Product] will be + created. In this situation, ``update_mask`` is ignored. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteProductRequest(proto.Message): + r"""Request message for [DeleteProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2beta.Product] to delete + can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] with more than + one + [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2beta.Product] will be + deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProductsRequest(proto.Message): + r"""Request message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list products + under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2beta.Product]s under this + branch, regardless of whether or not this branch exists, a + PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [Product][google.cloud.retail.v2beta.Product]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 + [ListProductsResponse.next_page_token][google.cloud.retail.v2beta.ListProductsResponse.next_page_token], + received from a previous + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + filter (str): + A filter to apply on the list results. Supported features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2beta.ListProductsRequest.filter] + is unset. + - List + [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s sharing + the same + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]. For + example: ``primary_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2beta.Product]s + bundled in a + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product]. For + example: ``collection_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2beta.Product]s with + a partibular type. For example: ``type = "PRIMARY"`` + ``type = "VARIANT"`` ``type = "COLLECTION"`` + + If the field is unrecognizable, an INVALID_ARGUMENT error is + returned. + + If the specified + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] or + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product] does not + exist, a NOT_FOUND error is returned. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields of [Product][google.cloud.retail.v2beta.Product] + to return in the responses. If not set or empty, the + following fields are returned: + + - [Product.name][google.cloud.retail.v2beta.Product.name] + - [Product.id][google.cloud.retail.v2beta.Product.id] + - [Product.title][google.cloud.retail.v2beta.Product.title] + - [Product.uri][google.cloud.retail.v2beta.Product.uri] + - [Product.images][google.cloud.retail.v2beta.Product.images] + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.brands][google.cloud.retail.v2beta.Product.brands] + + If "*" is provided, all fields are returned. + [Product.name][google.cloud.retail.v2beta.Product.name] is + always returned no matter what mask is set. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class ListProductsResponse(proto.Message): + r"""Response message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + + Attributes: + products (Sequence[google.cloud.retail_v2beta.types.Product]): + The [Product][google.cloud.retail.v2beta.Product]s. + next_page_token (str): + A token that can be sent as + [ListProductsRequest.page_token][google.cloud.retail.v2beta.ListProductsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class SetInventoryRequest(proto.Message): + r"""Request message for [SetInventory][] method. + + Attributes: + inventory (google.cloud.retail_v2beta.types.Product): + Required. The inventory information to update. The allowable + fields to update are: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product] named in + [Product.name][google.cloud.retail.v2beta.Product.name], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2beta.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting the + last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of fulfillment + types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear in + [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types have + empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following inventory + fields: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + + If a full overwrite of inventory information while ignoring + timestamps is needed, [UpdateProduct][] should be invoked + instead. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2beta.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the request is issued, used to + prevent out-of-order updates on inventory fields + with the last update time recorded. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] with name + [Product.name][google.cloud.retail.v2beta.Product.name] is + not found, the inventory update will still be processed and + retained for at most 1 day until the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + inventory = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + set_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + set_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=4, + ) + + +class SetInventoryMetadata(proto.Message): + r"""Metadata related to the progress of the SetInventory operation. + Currently empty because there is no meaningful metadata populated + from the [SetInventory][] method. + + """ + + +class SetInventoryResponse(proto.Message): + r"""Response of the SetInventoryRequest. Currently empty because there + is no meaningful response populated from the [SetInventory][] + method. + + """ + + +class AddFulfillmentPlacesRequest(proto.Message): + r"""Request message for [AddFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery" to be added for this + [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type]. + Duplicate IDs will be automatically ignored. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If the total number of place IDs exceeds 2000 for this + [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type] + after adding, then the update will be rejected. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + the fulfillment information will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + add_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class AddFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the AddFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [AddFulfillmentPlaces][] method. + + """ + + +class AddFulfillmentPlacesResponse(proto.Message): + r"""Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + + +class AddLocalInventoriesRequest(proto.Message): + r"""Request message for [AddLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + local_inventories (Sequence[google.cloud.retail_v2beta.types.LocalInventory]): + Required. A list of inventory information at + difference places. Each place is identified by + its place ID. At most 3000 inventories are + allowed per request. + add_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided list of + [LocalInventory][google.cloud.retail.v2beta.LocalInventory] + to update. The field is updated to the provided value. + + If a field is set while the place does not have a previous + local inventory, the local inventory at that store is + created. + + If a field is set while the value of that field is not + provided, the original field value, if it exists, is + deleted. + + If the mask is not set or set with empty paths, all + inventory fields will be updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory updates are + issued. Used to prevent out-of-order updates on + local inventory fields. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + the local inventory will still be processed and retained for + at most 1 day and processed once the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + local_inventories = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.LocalInventory, + ) + add_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + add_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=6, + ) + + +class AddLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the AddLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [AddLocalInventories][] method. + + """ + + +class AddLocalInventoriesResponse(proto.Message): + r"""Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesRequest(proto.Message): + r"""Request message for [RemoveLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + place_ids (Sequence[str]): + Required. A list of place IDs to have their + inventory deleted. At most 3000 place IDs are + allowed per request. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory deletions are + issued. Used to prevent out-of-order updates and + deletions on local inventory fields. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + the local inventory removal request will still be processed + and retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class RemoveLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesResponse(proto.Message): + r"""Response of the [RemoveLocalInventories][] API. Currently empty + because there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + + +class RemoveFulfillmentPlacesRequest(proto.Message): + r"""Request message for [RemoveFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2beta.RemoveFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery", to be removed for this + [type][google.cloud.retail.v2beta.RemoveFulfillmentPlacesRequest.type]. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + the fulfillment information will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class RemoveFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveFulfillmentPlaces][] method. + + """ + + +class RemoveFulfillmentPlacesResponse(proto.Message): + r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty + because there is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py new file mode 100644 index 00000000..be192a70 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'Promotion', + }, +) + + +class Promotion(proto.Message): + r"""Promotion information. + + Attributes: + promotion_id (str): + ID of the promotion. For example, "free gift". + + The value must be a UTF-8 encoded string with a length limit + of 128 characters, and match the pattern: + ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or + ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is + returned. + + Google Merchant Center property + `promotion `__. + """ + + promotion_id = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py new file mode 100644 index 00000000..95c99126 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + }, +) + + +class PurgeMetadata(proto.Message): + r"""Metadata related to the progress of the Purge operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + """ + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + + Attributes: + parent (str): + Required. The resource name of the catalog under which the + events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}`` + filter (str): + Required. The filter string to specify the events to be + deleted with a length limit of 5,000 characters. Empty + string filter is not allowed. The eligible fields for + filtering are: + + - ``eventType``: Double quoted + [UserEvent.event_type][google.cloud.retail.v2beta.UserEvent.event_type] + string. + - ``eventTime``: in ISO 8601 "zulu" format. + - ``visitorId``: Double quoted string. Specifying this will + delete all events associated with a visitor. + - ``userId``: Double quoted string. Specifying this will + delete all events associated with a user. + + Examples: + + - Deleting all events in a time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + - Deleting specific eventType in time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + - Deleting all events for a specific visitor: + ``visitorId = "visitor1024"`` + + The filtering fields are assumed to have an implicit AND. + force (bool): + Actually perform the purge. If ``force`` is set to false, + the method will return the expected purge count without + deleting any user events. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsResponse(proto.Message): + r"""Response of the PurgeUserEventsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purged_events_count (int): + The total count of events purged as a result + of the operation. + """ + + purged_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py new file mode 100644 index 00000000..21447a27 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py @@ -0,0 +1,1074 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'SearchRequest', + 'SearchResponse', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + + Attributes: + placement (str): + Required. The resource name of the search engine placement, + such as + ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` + This field is used to identify the serving configuration + name and the set of models that will be used to make the + search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + + Use "default_branch" as the branch ID or leave this field + empty, to search products under the default branch. + query (str): + Raw search query. + visitor_id (str): + Required. A unique identifier for tracking visitors. For + example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + This should be the same identifier as + [UserEvent.visitor_id][google.cloud.retail.v2beta.UserEvent.visitor_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2beta.types.UserInfo): + User information. + page_size (int): + Maximum number of + [Product][google.cloud.retail.v2beta.Product]s to return. If + unspecified, defaults to a reasonable value. The maximum + allowed value is 120. Values above 120 will be coerced to + 120. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [SearchResponse.next_page_token][google.cloud.retail.v2beta.SearchResponse.next_page_token], + received from a previous + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Product][google.cloud.retail.v2beta.Product]s deemed by the + API as relevant) in search results. This field is only + considered if + [page_token][google.cloud.retail.v2beta.SearchRequest.page_token] + is unset. + + If this field is negative, an INVALID_ARGUMENT is returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. Filter expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + canonical_filter (str): + The default filter that is applied when a user performs a + search without checking any filters on the search page. + + The filter applied to every search request when quality + improvement such as query expansion is needed. For example, + if a query does not have enough results, an expanded query + with + [SearchRequest.canonical_filter][google.cloud.retail.v2beta.SearchRequest.canonical_filter] + will be returned as a supplement of the original query. This + field is strongly recommended to achieve high search + quality. + + See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for more details about filter syntax. + order_by (str): + The order in which products are returned. Products can be + ordered by a field in an + [Product][google.cloud.retail.v2beta.Product] object. Leave + it unset if ordered by relevance. OrderBy expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + facet_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + dynamic_facet_spec (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec): + Deprecated. Refer to + https://cloud.google.com/retail/docs/configs#dynamic + to enable dynamic facets. Do not set this field. + The specification for dynamically generated + facets. Notice that only textual facets can be + dynamically generated. + boost_spec (google.cloud.retail_v2beta.types.SearchRequest.BoostSpec): + Boost specification to boost certain products. See more + details at this `user + guide `__. + + Notice that if both + [ServingConfig.boost_control_ids][google.cloud.retail.v2beta.ServingConfig.boost_control_ids] + and [SearchRequest.boost_spec] are set, the boost conditions + from both places are evaluated. If a search request matches + multiple boost conditions, the final boost score is equal to + the sum of the boost scores from all matched boost + conditions. + query_expansion_spec (google.cloud.retail_v2beta.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that specifies the + conditions under which query expansion will occur. See more + details at this `user + guide `__. + variant_rollup_keys (Sequence[str]): + The keys to fetch and rollup the matching + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s attributes, + [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo] + or + [LocalInventory][google.cloud.retail.v2beta.LocalInventory]s + attributes. The attributes from all the matching + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s or + [LocalInventory][google.cloud.retail.v2beta.LocalInventory]s + are merged and de-duplicated. Notice that rollup attributes + will lead to extra query latency. Maximum number of keys is + 30. + + For + [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], + a fulfillment type and a fulfillment ID must be provided in + the format of "fulfillmentType.fulfillmentId". E.g., in + "pickupInStore.store123", "pickupInStore" is fulfillment + type and "store123" is the store ID. + + Supported keys are: + + - colorFamilies + - price + - originalPrice + - discount + - variantId + - inventory(place_id,price) + - inventory(place_id,original_price) + - inventory(place_id,attributes.key), where key is any key + in the [Product.inventories.attributes][] map. + - attributes.key, where key is any key in the + [Product.attributes][google.cloud.retail.v2beta.Product.attributes] + map. + - pickupInStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "pickup-in-store". + - shipToStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "ship-to-store". + - sameDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "same-day-delivery". + - nextDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "next-day-delivery". + - customFulfillment1.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-1". + - customFulfillment2.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-2". + - customFulfillment3.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-3". + - customFulfillment4.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-4". + - customFulfillment5.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-5". + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. Required for + category navigation queries to achieve good search quality. + The format should be the same as + [UserEvent.page_categories][google.cloud.retail.v2beta.UserEvent.page_categories]; + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + search_mode (google.cloud.retail_v2beta.types.SearchRequest.SearchMode): + The search mode of the search request. If not + specified, a single search request triggers both + product search and faceted search. + personalization_spec (google.cloud.retail_v2beta.types.SearchRequest.PersonalizationSpec): + The specification for personalization. + """ + class SearchMode(proto.Enum): + r"""The search mode of each search request.""" + SEARCH_MODE_UNSPECIFIED = 0 + PRODUCT_SEARCH_ONLY = 1 + FACETED_SEARCH_ONLY = 2 + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.retail_v2beta.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum of facet values that should be returned for this + facet. If unspecified, defaults to 20. The maximum allowed + value is 300. Values above 300 will be coerced to 300. + + If this field is negative, an INVALID_ARGUMENT is returned. + excluded_filter_keys (Sequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + For example, suppose there are 100 products with color facet + "Red" and 200 products with color facet "Blue". A query + containing the filter "colorFamilies:ANY("Red")" and have + "colorFamilies" as + [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] + will by default return the "Red" with count 100. + + If this field contains "colorFamilies", then the query + returns both the "Red" with count 100 and "Blue" with count + 200, because the "colorFamilies" key is now excluded from + the filter. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined by Google Retail Search. It will be ordered + together with dynamic facets if dynamic facets is enabled. + If set to false, the position of this facet in the response + will be the same as in the request, and it will be ranked + before the facets with dynamic position enable and all + dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response will be determined by Google Retail + Search. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enable, which will + generate a facet 'gender'. Then the final order of the + facets in the response can be ("price", "brands", "rating", + "gender") or ("price", "brands", "gender", "rating") depends + on how Google Retail Search orders "gender" and "rating" + facets. However, notice that "price" and "brands" will + always be ranked at 1st and 2nd position since their + enable_dynamic_position are false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Product][google.cloud.retail.v2beta.Product] object, over + which the facet values are computed. Facet key is + case-sensitive. + + Allowed facet keys when + [FacetKey.query][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.query] + is not specified: + + - textual_field = + + - "brands" + - "categories" + - "genders" + - "ageGroups" + - "availability" + - "colorFamilies" + - "colors" + - "sizes" + - "materials" + - "patterns" + - "conditions" + - "attributes.key" + - "pickupInStore" + - "shipToStore" + - "sameDayDelivery" + - "nextDayDelivery" + - "customFulfillment1" + - "customFulfillment2" + - "customFulfillment3" + - "customFulfillment4" + - "customFulfillment5" + - "inventory(place_id,attributes.key)" + + - numerical_field = + + - "price" + - "discount" + - "rating" + - "ratingCount" + - "attributes.key" + - "inventory(place_id,price)" + - "inventory(place_id,original_price)" + - "inventory(place_id,attributes.key)". + intervals (Sequence[google.cloud.retail_v2beta.types.Interval]): + Set only if values should be bucketized into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (Sequence[str]): + Only get facet for the given restricted values. For example, + when using "pickupInStore" as key and set restricted values + to ["store123", "store456"], only facets for "store123" and + "store456" are returned. Only supported on textual fields + and fulfillments. Maximum is 20. + + Must be set for the fulfillment facet keys: + + - pickupInStore + + - shipToStore + + - sameDayDelivery + + - nextDayDelivery + + - customFulfillment1 + + - customFulfillment2 + + - customFulfillment3 + + - customFulfillment4 + + - customFulfillment5 + prefixes (Sequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "categories" has three values "Women > Shoe", + "Women > Dress" and "Men > Shoe". If set + "prefixes" to "Women", the "categories" facet + will give only "Women > Shoe" and "Women > + Dress". Only supported on textual fields. + Maximum is 10. + contains (Sequence[str]): + Only get facet values that contains the given + strings. For example, suppose "categories" has + three values "Women > Shoe", "Women > Dress" and + "Men > Shoe". If set "contains" to "Shoe", the + "categories" facet will give only "Women > Shoe" + and "Men > Shoe". Only supported on textual + fields. Maximum is 10. + order_by (str): + The order in which [Facet.values][] are returned. + + Allowed values are: + + - "count desc", which means order by + [Facet.FacetValue.count][] descending. + + - "value desc", which means order by + [Facet.FacetValue.value][] descending. Only applies to + textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.intervals]; + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + are sorted in the order given by + [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.restricted_values]. + query (str): + The query that is used to compute facet for the given facet + key. When provided, it will override the default behavior of + facet computation. The query syntax is the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for detail syntax and limitations. Notice that there is no + limitation on + [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] + when query is specified. + + In the response, [FacetValue.value][] will be always "1" and + [FacetValue.count][] will be the number of results that + matches the query. + + For example, you can set a customized facet for + "shipToStore", where + [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] + is "customizedShipToStore", and + [FacetKey.query][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.query] + is "availability: ANY("IN_STOCK") AND shipToStore: + ANY("123")". Then the facet will count the products that are + both in stock and ship to store "123". + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + intervals = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes = proto.RepeatedField( + proto.STRING, + number=8, + ) + contains = proto.RepeatedField( + proto.STRING, + number=9, + ) + order_by = proto.Field( + proto.STRING, + number=4, + ) + query = proto.Field( + proto.STRING, + number=5, + ) + + facet_key = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.FacetSpec.FacetKey', + ) + limit = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position = proto.Field( + proto.BOOL, + number=4, + ) + + class DynamicFacetSpec(proto.Message): + r"""The specifications of dynamically generated facets. + + Attributes: + mode (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec.Mode): + Mode of the DynamicFacet feature. Defaults to + [Mode.DISABLED][google.cloud.retail.v2beta.SearchRequest.DynamicFacetSpec.Mode.DISABLED] + if it's unset. + """ + class Mode(proto.Enum): + r"""Enum to control DynamicFacet mode""" + MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.DynamicFacetSpec.Mode', + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain items. + + Attributes: + condition_boost_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a product + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 10. + skip_boost_spec_validation (bool): + Whether to skip boostspec validation. If this field is set + to true, invalid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] + will be ignored and valid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] + will still be applied. + + This field is a member of `oneof`_ ``_skip_boost_spec_validation``. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to products which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": + + - (id: ANY("product_1", "product_2")) AND + (colorFamilies: ANY("Red","Blue")) + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition = proto.Field( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + skip_boost_spec_validation = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.retail_v2beta.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.retail.v2beta.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 3 + + condition = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.QueryExpansionSpec.Condition', + ) + pin_unexpanded_results = proto.Field( + proto.BOOL, + number=2, + ) + + class PersonalizationSpec(proto.Message): + r"""The specification for personalization. + + Attributes: + mode (google.cloud.retail_v2beta.types.SearchRequest.PersonalizationSpec.Mode): + Defaults to + [Mode.AUTO][google.cloud.retail.v2beta.SearchRequest.PersonalizationSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""The personalization mode of each search request.""" + MODE_UNSPECIFIED = 0 + AUTO = 1 + DISABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.PersonalizationSpec.Mode', + ) + + placement = proto.Field( + proto.STRING, + number=1, + ) + branch = proto.Field( + proto.STRING, + number=2, + ) + query = proto.Field( + proto.STRING, + number=3, + ) + visitor_id = proto.Field( + proto.STRING, + number=4, + ) + user_info = proto.Field( + proto.MESSAGE, + number=5, + message=common.UserInfo, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + offset = proto.Field( + proto.INT32, + number=9, + ) + filter = proto.Field( + proto.STRING, + number=10, + ) + canonical_filter = proto.Field( + proto.STRING, + number=28, + ) + order_by = proto.Field( + proto.STRING, + number=11, + ) + facet_specs = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=FacetSpec, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=21, + message=DynamicFacetSpec, + ) + boost_spec = proto.Field( + proto.MESSAGE, + number=13, + message=BoostSpec, + ) + query_expansion_spec = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionSpec, + ) + variant_rollup_keys = proto.RepeatedField( + proto.STRING, + number=17, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=23, + ) + search_mode = proto.Field( + proto.ENUM, + number=31, + enum=SearchMode, + ) + personalization_spec = proto.Field( + proto.MESSAGE, + number=32, + message=PersonalizationSpec, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + + Attributes: + results (Sequence[google.cloud.retail_v2beta.types.SearchResponse.SearchResult]): + A list of matched items. The order represents + the ranking. + facets (Sequence[google.cloud.retail_v2beta.types.SearchResponse.Facet]): + Results of facets requested by user. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.retail.v2beta.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.retail.v2beta.SearchResponse.total_size] + that matches. + corrected_query (str): + If spell correction applies, the corrected + query. Otherwise, empty. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.retail.v2beta.UserEvent] logs + resulting from this search, which enables accurate + attribution of search model performance. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.retail.v2beta.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + query_expansion_info (google.cloud.retail_v2beta.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search will be performed, and only + [redirect_uri][google.cloud.retail.v2beta.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.retail.v2beta.SearchResponse.attribution_token] + will be set in the response. + applied_controls (Sequence[str]): + The fully qualified resource name of applied + `controls `__. + invalid_condition_boost_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + The invalid + [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] + that are not applied during serving. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Product.id][google.cloud.retail.v2beta.Product.id] of the + searched [Product][google.cloud.retail.v2beta.Product]. + product (google.cloud.retail_v2beta.types.Product): + The product data snippet in the search response. Only + [Product.name][google.cloud.retail.v2beta.Product.name] is + guaranteed to be populated. + + [Product.variants][google.cloud.retail.v2beta.Product.variants] + contains the product variants that match the search query. + If there are multiple product variants matching the query, + top 5 most relevant product variants are returned and + ordered by relevancy. + + If relevancy can be deternmined, use + [matching_variant_fields][google.cloud.retail.v2beta.SearchResponse.SearchResult.matching_variant_fields] + to look up matched product variants fields. If relevancy + cannot be determined, e.g. when searching "shoe" all + products in a shoe product can be a match, 5 product + variants are returned but order is meaningless. + matching_variant_count (int): + The count of matched + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s. + matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): + If a + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] matches the + search query, this map indicates which + [Product][google.cloud.retail.v2beta.Product] fields are + matched. The key is the + [Product.name][google.cloud.retail.v2beta.Product.name], the + value is a field mask of the matched + [Product][google.cloud.retail.v2beta.Product] fields. If + matched attributes cannot be determined, this map will be + empty. + + For example, a key "sku1" with field mask + "products.color_info" indicates there is a match between + "sku1" [ColorInfo][google.cloud.retail.v2beta.ColorInfo] and + the query. + variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): + The rollup matching + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] attributes. + The key is one of the + [SearchRequest.variant_rollup_keys][google.cloud.retail.v2beta.SearchRequest.variant_rollup_keys]. + The values are the merged and de-duplicated + [Product][google.cloud.retail.v2beta.Product] attributes. + Notice that the rollup values are respect filter. For + example, when filtering by "colorFamilies:ANY("red")" and + rollup "colorFamilies", only "red" is returned. + + For textual and numerical attributes, the rollup values is a + list of string or double values with type + [google.protobuf.ListValue][google.protobuf.ListValue]. For + example, if there are two variants with colors "red" and + "blue", the rollup values are + + :: + + { key: "colorFamilies" + value { + list_value { + values { string_value: "red" } + values { string_value: "blue" } + } + } + } + + For + [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], + the rollup values is a double value with type + [google.protobuf.Value][google.protobuf.Value]. For example, + ``{key: "pickupInStore.store1" value { number_value: 10 }}`` + means a there are 10 variants in this product are available + in the store "store1". + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + matching_variant_count = proto.Field( + proto.INT32, + number=3, + ) + matching_variant_fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + variant_rollup_values = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. E.g., "colorFamilies" + or "price" or "attributes.attr1". + values (Sequence[google.cloud.retail_v2beta.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Text value of a facet, such as "Black" for + facet "colorFamilies". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.retail_v2beta.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value = proto.Field( + proto.STRING, + number=1, + oneof='facet_value', + ) + interval = proto.Field( + proto.MESSAGE, + number=2, + oneof='facet_value', + message=common.Interval, + ) + count = proto.Field( + proto.INT64, + number=3, + ) + + key = proto.Field( + proto.STRING, + number=1, + ) + values = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SearchResponse.Facet.FacetValue', + ) + dynamic_facet = proto.Field( + proto.BOOL, + number=3, + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2beta.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count = proto.Field( + proto.INT64, + number=2, + ) + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + corrected_query = proto.Field( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + next_page_token = proto.Field( + proto.STRING, + number=6, + ) + query_expansion_info = proto.Field( + proto.MESSAGE, + number=7, + message=QueryExpansionInfo, + ) + redirect_uri = proto.Field( + proto.STRING, + number=10, + ) + applied_controls = proto.RepeatedField( + proto.STRING, + number=12, + ) + invalid_condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py new file mode 100644 index 00000000..f8b78591 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py @@ -0,0 +1,309 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'ServingConfig', + }, +) + + +class ServingConfig(proto.Message): + r"""Configures metadata that is used to generate serving time results + (e.g. search results or recommendation predictions). The + ServingConfig is passed in the search and predict request and + together with the Catalog.default_branch, generates results. + + Attributes: + name (str): + Immutable. Fully qualified name + projects/\ */locations/global/catalogs/*/servingConfig/\* + display_name (str): + Required. The human readable serving config display name. + Used in Retail UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + model_id (str): + The id of the model to use at serving time. Currently only + RecommendationModels are supported: + https://cloud.google.com/retail/recommendations-ai/docs/create-models + Can be changed but only to a compatible model (e.g. + others-you-may-like CTR to others-you-may-like CVR). + + Required when + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + price_reranking_level (str): + How much price ranking we want in serving results. Price + reranking causes product items with a similar recommendation + probability to be ordered by price, with the highest-priced + items first. This setting could result in a decrease in + click-through and conversion rates. Allowed values are: + + - 'no-price-reranking' + - 'low-price-raranking' + - 'medium-price-reranking' + - 'high-price-reranking' + + If not specified, we choose default based on model type. + Default value: 'no-price-reranking'. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + facet_control_ids (Sequence[str]): + Facet specifications for faceted search. If empty, no facets + are returned. The ids refer to the ids of + [Control][google.cloud.retail.v2beta.Control] resources with + only the Facet control set. These controls are assumed to be + in the same [Catalog][google.cloud.retail.v2beta.Catalog] as + the + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]. A + maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + dynamic_facet_spec (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec): + The specification for dynamically generated facets. Notice + that only textual facets can be dynamically generated. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + boost_control_ids (Sequence[str]): + Condition boost specifications. If a product matches + multiple conditions in the specifications, boost scores from + these specifications are all applied and combined in a + non-linear way. Maximum number of specifications is 100. + + Notice that if both + [ServingConfig.boost_control_ids][google.cloud.retail.v2beta.ServingConfig.boost_control_ids] + and [SearchRequest.boost_spec] are set, the boost conditions + from both places are evaluated. If a search request matches + multiple boost conditions, the final boost score is equal to + the sum of the boost scores from all matched boost + conditions. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + filter_control_ids (Sequence[str]): + Condition filter specifications. If a product matches + multiple conditions in the specifications, filters from + these specifications are all applied and combined via the + AND operator. Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + redirect_control_ids (Sequence[str]): + Condition redirect specifications. Only the first triggered + redirect action is applied, even if multiple apply. Maximum + number of specifications is 1000. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + twoway_synonyms_control_ids (Sequence[str]): + Condition synonyms specifications. If multiple syonyms + conditions match, all matching synonyms control in the list + will execute. Order of controls in the list will not matter. + Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + oneway_synonyms_control_ids (Sequence[str]): + Condition oneway synonyms specifications. If multiple oneway + synonyms conditions match, all matching oneway synonyms + controls in the list will execute. Order of controls in the + list will not matter. Maximum number of specifications is + 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + do_not_associate_control_ids (Sequence[str]): + Condition do not associate specifications. If multiple do + not associate conditions match, all matching do not + associate controls in the list will execute. + + - Order does not matter. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + replacement_control_ids (Sequence[str]): + Condition replacement specifications. + + - Applied according to the order in the list. + - A previously replaced term can not be re-replaced. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + ignore_control_ids (Sequence[str]): + Condition ignore specifications. If multiple ignore + conditions match, all matching ignore controls in the list + will execute. + + - Order does not matter. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + diversity_level (str): + How much diversity to use in recommendation model results + e.g. 'medium-diversity' or 'high-diversity'. Currently + supported values: + + - 'no-diversity' + - 'low-diversity' + - 'medium-diversity' + - 'high-diversity' + - 'auto-diversity' + + If not specified, we choose default based on recommendation + model type. Default value: 'no-diversity'. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + enable_category_filter_level (str): + Whether to add additional category filters on the + 'similar-items' model. If not specified, we enable it by + default. Allowed values are: + + - 'no-category-match': No additional filtering of original + results from the model and the customer's filters. + - 'relaxed-category-match': Only keep results with + categories that match at least one item categories in the + PredictRequests's context item. + + - If customer also sends filters in the PredictRequest, + then the results will satisfy both conditions (user + given and category match). + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + solution_types (Sequence[google.cloud.retail_v2beta.types.SolutionType]): + Required. Immutable. Specifies the solution + types that a serving config can be associated + with. Currently we support setting only one type + of solution. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + model_id = proto.Field( + proto.STRING, + number=3, + ) + price_reranking_level = proto.Field( + proto.STRING, + number=4, + ) + facet_control_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=6, + message=search_service.SearchRequest.DynamicFacetSpec, + ) + boost_control_ids = proto.RepeatedField( + proto.STRING, + number=7, + ) + filter_control_ids = proto.RepeatedField( + proto.STRING, + number=9, + ) + redirect_control_ids = proto.RepeatedField( + proto.STRING, + number=10, + ) + twoway_synonyms_control_ids = proto.RepeatedField( + proto.STRING, + number=18, + ) + oneway_synonyms_control_ids = proto.RepeatedField( + proto.STRING, + number=12, + ) + do_not_associate_control_ids = proto.RepeatedField( + proto.STRING, + number=13, + ) + replacement_control_ids = proto.RepeatedField( + proto.STRING, + number=14, + ) + ignore_control_ids = proto.RepeatedField( + proto.STRING, + number=15, + ) + diversity_level = proto.Field( + proto.STRING, + number=8, + ) + enable_category_filter_level = proto.Field( + proto.STRING, + number=16, + ) + solution_types = proto.RepeatedField( + proto.ENUM, + number=19, + enum=common.SolutionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py new file mode 100644 index 00000000..20edced0 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py @@ -0,0 +1,234 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'CreateServingConfigRequest', + 'UpdateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'AddControlRequest', + 'RemoveControlRequest', + }, +) + + +class CreateServingConfigRequest(proto.Message): + r"""Request for CreateServingConfig method. + + Attributes: + parent (str): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + serving_config (google.cloud.retail_v2beta.types.ServingConfig): + Required. The ServingConfig to create. + serving_config_id (str): + Required. The ID to use for the ServingConfig, which will + become the final component of the ServingConfig's resource + name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-_/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + serving_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_serving_config.ServingConfig, + ) + serving_config_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateServingConfigRequest(proto.Message): + r"""Request for UpdateServingConfig method. + + Attributes: + serving_config (google.cloud.retail_v2beta.types.ServingConfig): + Required. The ServingConfig to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [ServingConfig][google.cloud.retail.v2beta.ServingConfig] to + update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] + + If not set, all supported fields are updated. + """ + + serving_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_serving_config.ServingConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteServingConfigRequest(proto.Message): + r"""Request for DeleteServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetServingConfigRequest(proto.Message): + r"""Request for GetServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListServingConfigsRequest(proto.Message): + r"""Request for ListServingConfigs method. + + Attributes: + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 100. If a + value greater than 100 is provided, at most 100 + results are returned. + page_token (str): + Optional. A page token, received from a previous + ``ListServingConfigs`` call. Provide this to retrieve the + subsequent page. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServingConfigsResponse(proto.Message): + r"""Response for ListServingConfigs method. + + Attributes: + serving_configs (Sequence[google.cloud.retail_v2beta.types.ServingConfig]): + All the ServingConfigs for a given catalog. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + serving_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_serving_config.ServingConfig, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class AddControlRequest(proto.Message): + r"""Request for AddControl method. + + Attributes: + serving_config (str): + Required. The source ServingConfig resource name . Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + control_id (str): + Required. The id of the control to apply. Assumed to be in + the same catalog as the serving config - if id is not found + a NOT_FOUND error is returned. + """ + + serving_config = proto.Field( + proto.STRING, + number=1, + ) + control_id = proto.Field( + proto.STRING, + number=2, + ) + + +class RemoveControlRequest(proto.Message): + r"""Request for RemoveControl method. + + Attributes: + serving_config (str): + Required. The source ServingConfig resource name . Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + control_id (str): + Required. The id of the control to apply. + Assumed to be in the same catalog as the serving + config. + """ + + serving_config = proto.Field( + proto.STRING, + number=1, + ) + control_id = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py new file mode 100644 index 00000000..bf1b1aee --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py @@ -0,0 +1,507 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import product as gcr_product +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'UserEvent', + 'ProductDetail', + 'CompletionDetail', + 'PurchaseTransaction', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Retail API needs + to know about how end users interact with customers' website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + - ``add-to-cart``: Products being added to cart. + - ``category-page-view``: Special pages such as sale or + promotion pages viewed. + - ``detail-page-view``: Products detail page viewed. + - ``home-page-view``: Homepage viewed. + - ``promotion-offered``: Promotion is offered to a user. + - ``promotion-not-offered``: Promotion is not offered to a + user. + - ``purchase-complete``: User finishing a purchase. + - ``search``: Product search. + - ``shopping-cart-page-view``: User viewing a shopping + cart. + visitor_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + The field should not contain PII or user-data. We recommend + to use Google Analystics `Client + ID `__ + for this field. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the sesion_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add visitor_id as prefix. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.retail.v2beta.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + experiment_ids (Sequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups + (e.g. using Retail API, using different + recommendation models). + attribution_token (str): + Highly recommended for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2beta.PredictionService.Predict]. + This field enables accurate attribution of recommendation + model performance. + + The value must be a valid + [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] + for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2beta.PredictionService.Predict]. + The value must be a valid + [SearchResponse.attribution_token][google.cloud.retail.v2beta.SearchResponse.attribution_token] + for user events that are the result of + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + This token enables us to accurately attribute page view or + purchase back to the event and the particular predict + response containing this clicked/purchased product. If user + clicks on product K in the recommendation results, pass + [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] + as a URL parameter to product K's page. When recording + events on product K's page, log the + [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] + to this field. + product_details (Sequence[google.cloud.retail_v2beta.types.ProductDetail]): + The main product details related to the event. + + This field is required for the following event types: + + - ``add-to-cart`` + - ``detail-page-view`` + - ``purchase-complete`` + - ``search`` + + In a ``search`` event, this field represents the products + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [product_details][google.cloud.retail.v2beta.UserEvent.product_details] + is desired. The end user may have not finished browsing the + whole page yet. + completion_detail (google.cloud.retail_v2beta.types.CompletionDetail): + The main auto-completion details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Retail API use those + custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - The key must be a UTF-8 encoded string with a length + limit of 5,000 characters. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a UTF-8 + encoded string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is traffic_channel, which is how a user arrives + at the site. Users can arrive at the site by coming to the + site directly, coming through Google search, or in other + ways. + cart_id (str): + The ID or name of the associated shopping cart. This ID is + used to associate multiple items added or present in the + cart before purchase. + + This can only be set for ``add-to-cart``, + ``purchase-complete``, or ``shopping-cart-page-view`` + events. + purchase_transaction (google.cloud.retail_v2beta.types.PurchaseTransaction): + A transaction represents the entire purchase transaction. + + Required for ``purchase-complete`` events. Other event types + should not set this field. Otherwise, an INVALID_ARGUMENT + error is returned. + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.retail.v2beta.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + At least one of + [search_query][google.cloud.retail.v2beta.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2beta.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. + + See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + order_by (str): + The order in which products are returned. + + See + [SearchRequest.order_by][google.cloud.retail.v2beta.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.retail.v2beta.SearchRequest.offset] + for definition. + + If this field is negative, an INVALID_ARGUMENT is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + + Required for ``category-page-view`` events. At least one of + [search_query][google.cloud.retail.v2beta.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2beta.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2beta.types.UserInfo): + User information. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. + page_view_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageViewId`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + """ + + event_type = proto.Field( + proto.STRING, + number=1, + ) + visitor_id = proto.Field( + proto.STRING, + number=2, + ) + session_id = proto.Field( + proto.STRING, + number=21, + ) + event_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + experiment_ids = proto.RepeatedField( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + product_details = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ProductDetail', + ) + completion_detail = proto.Field( + proto.MESSAGE, + number=22, + message='CompletionDetail', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=common.CustomAttribute, + ) + cart_id = proto.Field( + proto.STRING, + number=8, + ) + purchase_transaction = proto.Field( + proto.MESSAGE, + number=9, + message='PurchaseTransaction', + ) + search_query = proto.Field( + proto.STRING, + number=10, + ) + filter = proto.Field( + proto.STRING, + number=16, + ) + order_by = proto.Field( + proto.STRING, + number=17, + ) + offset = proto.Field( + proto.INT32, + number=18, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=11, + ) + user_info = proto.Field( + proto.MESSAGE, + number=12, + message=common.UserInfo, + ) + uri = proto.Field( + proto.STRING, + number=13, + ) + referrer_uri = proto.Field( + proto.STRING, + number=14, + ) + page_view_id = proto.Field( + proto.STRING, + number=15, + ) + + +class ProductDetail(proto.Message): + r"""Detailed product information associated with a user event. + + Attributes: + product (google.cloud.retail_v2beta.types.Product): + Required. [Product][google.cloud.retail.v2beta.Product] + information. + + Required field(s): + + - [Product.id][google.cloud.retail.v2beta.Product.id] + + Optional override field(s): + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + + If any supported optional fields are provided, we will treat + them as a full override when looking up product information + from the catalog. Thus, it is important to ensure that the + overriding fields are accurate and complete. + + All other product fields are ignored and instead populated + via catalog lookup after event ingestion. + quantity (google.protobuf.wrappers_pb2.Int32Value): + Quantity of the product associated with the user event. + + For example, this field will be 2 if two products are added + to the shopping cart for ``purchase-complete`` event. + Required for ``add-to-cart`` and ``purchase-complete`` event + types. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + quantity = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +class CompletionDetail(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + completion_attribution_token (str): + Completion attribution token in + [CompleteQueryResponse.attribution_token][google.cloud.retail.v2beta.CompleteQueryResponse.attribution_token]. + selected_suggestion (str): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2beta.CompleteQueryResponse.CompletionResult.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2beta.CompleteQueryResponse.CompletionResult.suggestion] + position, starting from 0. + """ + + completion_attribution_token = proto.Field( + proto.STRING, + number=1, + ) + selected_suggestion = proto.Field( + proto.STRING, + number=2, + ) + selected_position = proto.Field( + proto.INT32, + number=3, + ) + + +class PurchaseTransaction(proto.Message): + r"""A transaction represents the entire purchase transaction. + + Attributes: + id (str): + The transaction ID with a length limit of 128 + characters. + revenue (float): + Required. Total non-zero revenue or grand + total associated with the transaction. This + value include shipping, tax, or other + adjustments to total revenue that you want to + include as part of your revenue calculations. + tax (float): + All the taxes associated with the + transaction. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [revenue][google.cloud.retail.v2beta.PurchaseTransaction.revenue] + - + [tax][google.cloud.retail.v2beta.PurchaseTransaction.tax] + - + [cost][google.cloud.retail.v2beta.PurchaseTransaction.cost] + currency_code (str): + Required. Currency code. Use three-character + ISO-4217 code. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + revenue = proto.Field( + proto.FLOAT, + number=2, + ) + tax = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + currency_code = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py new file mode 100644 index 00000000..990180c4 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import user_event as gcr_user_event + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'WriteUserEventRequest', + 'CollectUserEventRequest', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'RejoinUserEventsMetadata', + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (google.cloud.retail_v2beta.types.UserEvent): + Required. User event to write. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for 3rd party requests. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.STRING, + number=2, + ) + uri = proto.Field( + proto.STRING, + number=3, + ) + ets = proto.Field( + proto.INT64, + number=4, + ) + + +class RejoinUserEventsRequest(proto.Message): + r"""Request message for RejoinUserEvents method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event_rejoin_scope (google.cloud.retail_v2beta.types.RejoinUserEventsRequest.UserEventRejoinScope): + The type of the user event rejoin to define the scope and + range of the user events to be rejoined with the latest + product catalog. Defaults to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not + set, or set to an invalid integer value. + """ + class UserEventRejoinScope(proto.Enum): + r"""The scope of user events to be rejoined with the latest product + catalog. If the rejoining aims at reducing number of unjoined + events, set UserEventRejoinScope to UNJOINED_EVENTS. If the + rejoining aims at correcting product catalog information in joined + events, set UserEventRejoinScope to JOINED_EVENTS. If all events + needs to be rejoined, set UserEventRejoinScope to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. + """ + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 + JOINED_EVENTS = 1 + UNJOINED_EVENTS = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event_rejoin_scope = proto.Field( + proto.ENUM, + number=2, + enum=UserEventRejoinScope, + ) + + +class RejoinUserEventsResponse(proto.Message): + r"""Response message for RejoinUserEvents method. + + Attributes: + rejoined_user_events_count (int): + Number of user events that were joined with + latest product catalog. + """ + + rejoined_user_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +class RejoinUserEventsMetadata(proto.Message): + r"""Metadata for RejoinUserEvents method. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/mypy.ini b/owl-bot-staging/v2beta/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v2beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2beta/noxfile.py b/owl-bot-staging/v2beta/noxfile.py new file mode 100644 index 00000000..5abd48a4 --- /dev/null +++ b/owl-bot-staging/v2beta/noxfile.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.6", + "3.7", + "3.8", + "3.9", + "3.10", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==19.10b0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.9" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/retail_v2beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py new file mode 100644 index 00000000..09847366 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_AddCatalogAttribute_async] +from google.cloud import retail_v2beta + + +async def sample_add_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_AddCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py new file mode 100644 index 00000000..4f05ae26 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync] +from google.cloud import retail_v2beta + + +def sample_add_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py new file mode 100644 index 00000000..637bfe3a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetAttributesConfig_async] +from google.cloud import retail_v2beta + + +async def sample_get_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetAttributesConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py new file mode 100644 index 00000000..c347bee2 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetAttributesConfig_sync] +from google.cloud import retail_v2beta + + +def sample_get_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetAttributesConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py new file mode 100644 index 00000000..2133e940 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetCompletionConfig_async] +from google.cloud import retail_v2beta + + +async def sample_get_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetCompletionConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py new file mode 100644 index 00000000..bb9bf00d --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetCompletionConfig_sync] +from google.cloud import retail_v2beta + + +def sample_get_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetCompletionConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py new file mode 100644 index 00000000..e598ec09 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetDefaultBranch_async] +from google.cloud import retail_v2beta + + +async def sample_get_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py new file mode 100644 index 00000000..6adcb072 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetDefaultBranch_sync] +from google.cloud import retail_v2beta + + +def sample_get_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py new file mode 100644 index 00000000..b4e3df0e --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_ListCatalogs_async] +from google.cloud import retail_v2beta + + +async def sample_list_catalogs(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py new file mode 100644 index 00000000..d938f3ae --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_ListCatalogs_sync] +from google.cloud import retail_v2beta + + +def sample_list_catalogs(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py new file mode 100644 index 00000000..032fb3c6 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async] +from google.cloud import retail_v2beta + + +async def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = await client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py new file mode 100644 index 00000000..f1ecc22b --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync] +from google.cloud import retail_v2beta + + +def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py new file mode 100644 index 00000000..8a87262f --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReplaceCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async] +from google.cloud import retail_v2beta + + +async def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py new file mode 100644 index 00000000..24b38d05 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReplaceCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync] +from google.cloud import retail_v2beta + + +def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py new file mode 100644 index 00000000..6eec0779 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_SetDefaultBranch_async] +from google.cloud import retail_v2beta + + +async def sample_set_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + +# [END retail_v2beta_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py new file mode 100644 index 00000000..a3deb8fd --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_SetDefaultBranch_sync] +from google.cloud import retail_v2beta + + +def sample_set_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + +# [END retail_v2beta_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py new file mode 100644 index 00000000..b4a235ec --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async] +from google.cloud import retail_v2beta + + +async def sample_update_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + attributes_config = retail_v2beta.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2beta.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = await client.update_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py new file mode 100644 index 00000000..8f82ee5d --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync] +from google.cloud import retail_v2beta + + +def sample_update_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + attributes_config = retail_v2beta.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2beta.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = client.update_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py new file mode 100644 index 00000000..772504ff --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateCatalog_async] +from google.cloud import retail_v2beta + + +async def sample_update_catalog(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2beta.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2beta.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py new file mode 100644 index 00000000..ed59d356 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateCatalog_sync] +from google.cloud import retail_v2beta + + +def sample_update_catalog(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2beta.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2beta.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py new file mode 100644 index 00000000..377166a7 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async] +from google.cloud import retail_v2beta + + +async def sample_update_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + completion_config = retail_v2beta.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2beta.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = await client.update_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py new file mode 100644 index 00000000..f641f121 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync] +from google.cloud import retail_v2beta + + +def sample_update_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + completion_config = retail_v2beta.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2beta.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = client.update_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py new file mode 100644 index 00000000..96fdc6a6 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CompletionService_CompleteQuery_async] +from google.cloud import retail_v2beta + + +async def sample_complete_query(): + # Create a client + client = retail_v2beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py new file mode 100644 index 00000000..afb0ba7d --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CompletionService_CompleteQuery_sync] +from google.cloud import retail_v2beta + + +def sample_complete_query(): + # Create a client + client = retail_v2beta.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py new file mode 100644 index 00000000..912753e9 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CompletionService_ImportCompletionData_async] +from google.cloud import retail_v2beta + + +async def sample_import_completion_data(): + # Create a client + client = retail_v2beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2beta.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py new file mode 100644 index 00000000..2cbd277d --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CompletionService_ImportCompletionData_sync] +from google.cloud import retail_v2beta + + +def sample_import_completion_data(): + # Create a client + client = retail_v2beta.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2beta.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py new file mode 100644 index 00000000..51e0cb4f --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_CreateControl_async] +from google.cloud import retail_v2beta + + +async def sample_create_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = await client.create_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_CreateControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py new file mode 100644 index 00000000..8d16b152 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_CreateControl_sync] +from google.cloud import retail_v2beta + + +def sample_create_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = client.create_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_CreateControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py new file mode 100644 index 00000000..cb18f6ba --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_DeleteControl_async] +from google.cloud import retail_v2beta + + +async def sample_delete_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteControlRequest( + name="name_value", + ) + + # Make the request + await client.delete_control(request=request) + + +# [END retail_v2beta_generated_ControlService_DeleteControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py new file mode 100644 index 00000000..8a0d4f56 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_DeleteControl_sync] +from google.cloud import retail_v2beta + + +def sample_delete_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteControlRequest( + name="name_value", + ) + + # Make the request + client.delete_control(request=request) + + +# [END retail_v2beta_generated_ControlService_DeleteControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py new file mode 100644 index 00000000..f9eeb9fd --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_GetControl_async] +from google.cloud import retail_v2beta + + +async def sample_get_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetControlRequest( + name="name_value", + ) + + # Make the request + response = await client.get_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_GetControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py new file mode 100644 index 00000000..ee0de08a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_GetControl_sync] +from google.cloud import retail_v2beta + + +def sample_get_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetControlRequest( + name="name_value", + ) + + # Make the request + response = client.get_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_GetControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py new file mode 100644 index 00000000..9a645706 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListControls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_ListControls_async] +from google.cloud import retail_v2beta + + +async def sample_list_controls(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_ControlService_ListControls_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py new file mode 100644 index 00000000..97c8ba62 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListControls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_ListControls_sync] +from google.cloud import retail_v2beta + + +def sample_list_controls(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_ControlService_ListControls_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py new file mode 100644 index 00000000..9a42018c --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_UpdateControl_async] +from google.cloud import retail_v2beta + + +async def sample_update_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateControlRequest( + control=control, + ) + + # Make the request + response = await client.update_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_UpdateControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py new file mode 100644 index 00000000..2a306202 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_UpdateControl_sync] +from google.cloud import retail_v2beta + + +def sample_update_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateControlRequest( + control=control, + ) + + # Make the request + response = client.update_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_UpdateControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py new file mode 100644 index 00000000..fd37548f --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_PredictionService_Predict_async] +from google.cloud import retail_v2beta + + +async def sample_predict(): + # Create a client + client = retail_v2beta.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py new file mode 100644 index 00000000..6975056e --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_PredictionService_Predict_sync] +from google.cloud import retail_v2beta + + +def sample_predict(): + # Create a client + client = retail_v2beta.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py new file mode 100644 index 00000000..92a7a7e1 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async] +from google.cloud import retail_v2beta + + +async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py new file mode 100644 index 00000000..d828edde --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync] +from google.cloud import retail_v2beta + + +def sample_add_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py new file mode 100644 index 00000000..ebcf5c80 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_AddLocalInventories_async] +from google.cloud import retail_v2beta + + +async def sample_add_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py new file mode 100644 index 00000000..9d3d9ab0 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_AddLocalInventories_sync] +from google.cloud import retail_v2beta + + +def sample_add_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py new file mode 100644 index 00000000..2bba20c0 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_CreateProduct_async] +from google.cloud import retail_v2beta + + +async def sample_create_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py new file mode 100644 index 00000000..32bd03e2 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_CreateProduct_sync] +from google.cloud import retail_v2beta + + +def sample_create_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py new file mode 100644 index 00000000..8f9591fa --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_DeleteProduct_async] +from google.cloud import retail_v2beta + + +async def sample_delete_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + +# [END retail_v2beta_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py new file mode 100644 index 00000000..56630734 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_DeleteProduct_sync] +from google.cloud import retail_v2beta + + +def sample_delete_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + +# [END retail_v2beta_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py new file mode 100644 index 00000000..f8dcfc01 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_GetProduct_async] +from google.cloud import retail_v2beta + + +async def sample_get_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py new file mode 100644 index 00000000..ab5cd918 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_GetProduct_sync] +from google.cloud import retail_v2beta + + +def sample_get_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py new file mode 100644 index 00000000..aa4256cc --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_ImportProducts_async] +from google.cloud import retail_v2beta + + +async def sample_import_products(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2beta.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py new file mode 100644 index 00000000..b4bc8314 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_ImportProducts_sync] +from google.cloud import retail_v2beta + + +def sample_import_products(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2beta.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py new file mode 100644 index 00000000..e259ecd6 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_ListProducts_async] +from google.cloud import retail_v2beta + + +async def sample_list_products(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py new file mode 100644 index 00000000..5cb40315 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_ListProducts_sync] +from google.cloud import retail_v2beta + + +def sample_list_products(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py new file mode 100644 index 00000000..1b18eb50 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async] +from google.cloud import retail_v2beta + + +async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py new file mode 100644 index 00000000..f430e360 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync] +from google.cloud import retail_v2beta + + +def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py new file mode 100644 index 00000000..55fba819 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_RemoveLocalInventories_async] +from google.cloud import retail_v2beta + + +async def sample_remove_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py new file mode 100644 index 00000000..31d1e58e --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_RemoveLocalInventories_sync] +from google.cloud import retail_v2beta + + +def sample_remove_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py new file mode 100644 index 00000000..9b467025 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_SetInventory_async] +from google.cloud import retail_v2beta + + +async def sample_set_inventory(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2beta.Product() + inventory.title = "title_value" + + request = retail_v2beta.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py new file mode 100644 index 00000000..d1061827 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_SetInventory_sync] +from google.cloud import retail_v2beta + + +def sample_set_inventory(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2beta.Product() + inventory.title = "title_value" + + request = retail_v2beta.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py new file mode 100644 index 00000000..8d9590cd --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_UpdateProduct_async] +from google.cloud import retail_v2beta + + +async def sample_update_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py new file mode 100644 index 00000000..fc614e58 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_UpdateProduct_sync] +from google.cloud import retail_v2beta + + +def sample_update_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py new file mode 100644 index 00000000..967c9102 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_SearchService_Search_async] +from google.cloud import retail_v2beta + + +async def sample_search(): + # Create a client + client = retail_v2beta.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py new file mode 100644 index 00000000..1e6a5045 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_SearchService_Search_sync] +from google.cloud import retail_v2beta + + +def sample_search(): + # Create a client + client = retail_v2beta.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py new file mode 100644 index 00000000..d6554386 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_AddControl_async] +from google.cloud import retail_v2beta + + +async def sample_add_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.add_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_AddControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py new file mode 100644 index 00000000..e61e4e2a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_AddControl_sync] +from google.cloud import retail_v2beta + + +def sample_add_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.add_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_AddControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py new file mode 100644 index 00000000..b09fadf2 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_CreateServingConfig_async] +from google.cloud import retail_v2beta + + +async def sample_create_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = await client.create_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_CreateServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py new file mode 100644 index 00000000..5d4c0993 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync] +from google.cloud import retail_v2beta + + +def sample_create_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = client.create_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py new file mode 100644 index 00000000..c0b03659 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async] +from google.cloud import retail_v2beta + + +async def sample_delete_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_serving_config(request=request) + + +# [END retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py new file mode 100644 index 00000000..1db19c0a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync] +from google.cloud import retail_v2beta + + +def sample_delete_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_serving_config(request=request) + + +# [END retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py new file mode 100644 index 00000000..64f6aeef --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_GetServingConfig_async] +from google.cloud import retail_v2beta + + +async def sample_get_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_GetServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py new file mode 100644 index 00000000..1cfab934 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_GetServingConfig_sync] +from google.cloud import retail_v2beta + + +def sample_get_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_GetServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py new file mode 100644 index 00000000..7ad0a3aa --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServingConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_ListServingConfigs_async] +from google.cloud import retail_v2beta + + +async def sample_list_serving_configs(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_ServingConfigService_ListServingConfigs_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py new file mode 100644 index 00000000..6a3e7e2a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServingConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync] +from google.cloud import retail_v2beta + + +def sample_list_serving_configs(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py new file mode 100644 index 00000000..c9994a00 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_RemoveControl_async] +from google.cloud import retail_v2beta + + +async def sample_remove_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.remove_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_RemoveControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py new file mode 100644 index 00000000..db6dfa93 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_RemoveControl_sync] +from google.cloud import retail_v2beta + + +def sample_remove_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.remove_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_RemoveControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py new file mode 100644 index 00000000..2a6bd3a0 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async] +from google.cloud import retail_v2beta + + +async def sample_update_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = await client.update_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py new file mode 100644 index 00000000..f6441e46 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync] +from google.cloud import retail_v2beta + + +def sample_update_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = client.update_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 00000000..ce80fabf --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_CollectUserEvent_async] +from google.cloud import retail_v2beta + + +async def sample_collect_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 00000000..ff7df192 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_CollectUserEvent_sync] +from google.cloud import retail_v2beta + + +def sample_collect_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py new file mode 100644 index 00000000..259c3424 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_ImportUserEvents_async] +from google.cloud import retail_v2beta + + +async def sample_import_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2beta.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 00000000..89e0ec02 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_ImportUserEvents_sync] +from google.cloud import retail_v2beta + + +def sample_import_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2beta.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py new file mode 100644 index 00000000..6f97cab1 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_PurgeUserEvents_async] +from google.cloud import retail_v2beta + + +async def sample_purge_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py new file mode 100644 index 00000000..212d2693 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_PurgeUserEvents_sync] +from google.cloud import retail_v2beta + + +def sample_purge_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py new file mode 100644 index 00000000..8a95e668 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_RejoinUserEvents_async] +from google.cloud import retail_v2beta + + +async def sample_rejoin_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py new file mode 100644 index 00000000..ebd635b8 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_RejoinUserEvents_sync] +from google.cloud import retail_v2beta + + +def sample_rejoin_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py new file mode 100644 index 00000000..71317cac --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_WriteUserEvent_async] +from google.cloud import retail_v2beta + + +async def sample_write_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 00000000..e93e4df4 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_WriteUserEvent_sync] +from google.cloud import retail_v2beta + + +def sample_write_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json b/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json new file mode 100644 index 00000000..591f20ca --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json @@ -0,0 +1,6913 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.retail.v2beta", + "version": "v2beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-retail" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.add_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "AddCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "add_catalog_attribute" + }, + "description": "Sample for AddCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_AddCatalogAttribute_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.add_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "AddCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "add_catalog_attribute" + }, + "description": "Sample for AddCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetAttributesConfigRequest" + }, + { + "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.retail_v2beta.types.AttributesConfig", + "shortName": "get_attributes_config" + }, + "description": "Sample for GetAttributesConfig", + "file": "retail_v2beta_generated_catalog_service_get_attributes_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetAttributesConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_attributes_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetAttributesConfigRequest" + }, + { + "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.retail_v2beta.types.AttributesConfig", + "shortName": "get_attributes_config" + }, + "description": "Sample for GetAttributesConfig", + "file": "retail_v2beta_generated_catalog_service_get_attributes_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetAttributesConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_attributes_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_completion_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetCompletionConfigRequest" + }, + { + "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.retail_v2beta.types.CompletionConfig", + "shortName": "get_completion_config" + }, + "description": "Sample for GetCompletionConfig", + "file": "retail_v2beta_generated_catalog_service_get_completion_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetCompletionConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_completion_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_completion_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetCompletionConfigRequest" + }, + { + "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.retail_v2beta.types.CompletionConfig", + "shortName": "get_completion_config" + }, + "description": "Sample for GetCompletionConfig", + "file": "retail_v2beta_generated_catalog_service_get_completion_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetCompletionConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_completion_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2beta_generated_catalog_service_get_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetDefaultBranch_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2beta_generated_catalog_service_get_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetDefaultBranch_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListCatalogsRequest" + }, + { + "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.retail_v2beta.services.catalog_service.pagers.ListCatalogsAsyncPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2beta_generated_catalog_service_list_catalogs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_ListCatalogs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_list_catalogs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListCatalogsRequest" + }, + { + "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.retail_v2beta.services.catalog_service.pagers.ListCatalogsPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2beta_generated_catalog_service_list_catalogs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_ListCatalogs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_list_catalogs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.remove_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "RemoveCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "remove_catalog_attribute" + }, + "description": "Sample for RemoveCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.remove_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "RemoveCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "remove_catalog_attribute" + }, + "description": "Sample for RemoveCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.replace_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ReplaceCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "replace_catalog_attribute" + }, + "description": "Sample for ReplaceCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.replace_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ReplaceCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "replace_catalog_attribute" + }, + "description": "Sample for ReplaceCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2beta_generated_catalog_service_set_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_SetDefaultBranch_async", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_set_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2beta_generated_catalog_service_set_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_SetDefaultBranch_sync", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_set_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest" + }, + { + "name": "attributes_config", + "type": "google.cloud.retail_v2beta.types.AttributesConfig" + }, + { + "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.retail_v2beta.types.AttributesConfig", + "shortName": "update_attributes_config" + }, + "description": "Sample for UpdateAttributesConfig", + "file": "retail_v2beta_generated_catalog_service_update_attributes_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_attributes_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest" + }, + { + "name": "attributes_config", + "type": "google.cloud.retail_v2beta.types.AttributesConfig" + }, + { + "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.retail_v2beta.types.AttributesConfig", + "shortName": "update_attributes_config" + }, + "description": "Sample for UpdateAttributesConfig", + "file": "retail_v2beta_generated_catalog_service_update_attributes_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_attributes_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2beta.types.Catalog" + }, + { + "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.retail_v2beta.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2beta_generated_catalog_service_update_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateCatalog_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2beta.types.Catalog" + }, + { + "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.retail_v2beta.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2beta_generated_catalog_service_update_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateCatalog_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_completion_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest" + }, + { + "name": "completion_config", + "type": "google.cloud.retail_v2beta.types.CompletionConfig" + }, + { + "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.retail_v2beta.types.CompletionConfig", + "shortName": "update_completion_config" + }, + "description": "Sample for UpdateCompletionConfig", + "file": "retail_v2beta_generated_catalog_service_update_completion_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_completion_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_completion_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest" + }, + { + "name": "completion_config", + "type": "google.cloud.retail_v2beta.types.CompletionConfig" + }, + { + "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.retail_v2beta.types.CompletionConfig", + "shortName": "update_completion_config" + }, + "description": "Sample for UpdateCompletionConfig", + "file": "retail_v2beta_generated_catalog_service_update_completion_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_completion_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2beta.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2beta_generated_completion_service_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CompletionService_CompleteQuery_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_completion_service_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CompletionServiceClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2beta.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2beta_generated_completion_service_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CompletionService_CompleteQuery_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_completion_service_complete_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2beta.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2beta_generated_completion_service_import_completion_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CompletionService_ImportCompletionData_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_completion_service_import_completion_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CompletionServiceClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2beta.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2beta_generated_completion_service_import_completion_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CompletionService_ImportCompletionData_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_completion_service_import_completion_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.create_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.CreateControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "CreateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateControlRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "control", + "type": "google.cloud.retail_v2beta.types.Control" + }, + { + "name": "control_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.retail_v2beta.types.Control", + "shortName": "create_control" + }, + "description": "Sample for CreateControl", + "file": "retail_v2beta_generated_control_service_create_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_CreateControl_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_create_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.create_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.CreateControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "CreateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateControlRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "control", + "type": "google.cloud.retail_v2beta.types.Control" + }, + { + "name": "control_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.retail_v2beta.types.Control", + "shortName": "create_control" + }, + "description": "Sample for CreateControl", + "file": "retail_v2beta_generated_control_service_create_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_CreateControl_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_create_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.delete_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.DeleteControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "DeleteControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteControlRequest" + }, + { + "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_control" + }, + "description": "Sample for DeleteControl", + "file": "retail_v2beta_generated_control_service_delete_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_DeleteControl_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_delete_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.delete_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.DeleteControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "DeleteControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteControlRequest" + }, + { + "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_control" + }, + "description": "Sample for DeleteControl", + "file": "retail_v2beta_generated_control_service_delete_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_DeleteControl_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_delete_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.get_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.GetControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "GetControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetControlRequest" + }, + { + "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.retail_v2beta.types.Control", + "shortName": "get_control" + }, + "description": "Sample for GetControl", + "file": "retail_v2beta_generated_control_service_get_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_GetControl_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_get_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.get_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.GetControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "GetControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetControlRequest" + }, + { + "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.retail_v2beta.types.Control", + "shortName": "get_control" + }, + "description": "Sample for GetControl", + "file": "retail_v2beta_generated_control_service_get_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_GetControl_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_get_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.list_controls", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.ListControls", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListControlsRequest" + }, + { + "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.retail_v2beta.services.control_service.pagers.ListControlsAsyncPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "retail_v2beta_generated_control_service_list_controls_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_ListControls_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_list_controls_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.list_controls", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.ListControls", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListControlsRequest" + }, + { + "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.retail_v2beta.services.control_service.pagers.ListControlsPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "retail_v2beta_generated_control_service_list_controls_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_ListControls_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_list_controls_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.update_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.UpdateControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "UpdateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateControlRequest" + }, + { + "name": "control", + "type": "google.cloud.retail_v2beta.types.Control" + }, + { + "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.retail_v2beta.types.Control", + "shortName": "update_control" + }, + "description": "Sample for UpdateControl", + "file": "retail_v2beta_generated_control_service_update_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_UpdateControl_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_update_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.update_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.UpdateControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "UpdateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateControlRequest" + }, + { + "name": "control", + "type": "google.cloud.retail_v2beta.types.Control" + }, + { + "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.retail_v2beta.types.Control", + "shortName": "update_control" + }, + "description": "Sample for UpdateControl", + "file": "retail_v2beta_generated_control_service_update_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_UpdateControl_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_update_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.PredictionServiceAsyncClient", + "shortName": "PredictionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.PredictionServiceAsyncClient.predict", + "method": { + "fullName": "google.cloud.retail.v2beta.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2beta.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2beta_generated_prediction_service_predict_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_PredictionService_Predict_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_prediction_service_predict_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.PredictionServiceClient", + "shortName": "PredictionServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.PredictionServiceClient.predict", + "method": { + "fullName": "google.cloud.retail.v2beta.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2beta.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2beta_generated_prediction_service_predict_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_PredictionService_Predict_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_prediction_service_predict_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2beta_generated_product_service_add_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_add_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2beta_generated_product_service_add_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_add_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2beta_generated_product_service_add_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_AddLocalInventories_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_add_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2beta_generated_product_service_add_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_AddLocalInventories_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_add_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "name": "product_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.retail_v2beta.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2beta_generated_product_service_create_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_CreateProduct_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_create_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "name": "product_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.retail_v2beta.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2beta_generated_product_service_create_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_CreateProduct_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_create_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2beta_generated_product_service_delete_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_DeleteProduct_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_delete_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2beta_generated_product_service_delete_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_DeleteProduct_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_delete_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetProductRequest" + }, + { + "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.retail_v2beta.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2beta_generated_product_service_get_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_GetProduct_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_get_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetProductRequest" + }, + { + "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.retail_v2beta.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2beta_generated_product_service_get_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_GetProduct_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_get_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2beta_generated_product_service_import_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_ImportProducts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_import_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2beta_generated_product_service_import_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_ImportProducts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_import_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListProductsRequest" + }, + { + "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.retail_v2beta.services.product_service.pagers.ListProductsAsyncPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2beta_generated_product_service_list_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_ListProducts_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_list_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListProductsRequest" + }, + { + "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.retail_v2beta.services.product_service.pagers.ListProductsPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2beta_generated_product_service_list_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_ListProducts_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_list_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2beta_generated_product_service_remove_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_remove_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2beta_generated_product_service_remove_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_RemoveLocalInventories_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_remove_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2beta_generated_product_service_remove_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_RemoveLocalInventories_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_remove_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2beta_generated_product_service_set_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_SetInventory_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_set_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2beta_generated_product_service_set_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_SetInventory_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_set_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "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.retail_v2beta.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2beta_generated_product_service_update_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_UpdateProduct_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_update_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "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.retail_v2beta.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2beta_generated_product_service_update_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_UpdateProduct_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_update_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.SearchServiceAsyncClient.search", + "method": { + "fullName": "google.cloud.retail.v2beta.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2beta.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2beta_generated_search_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_SearchService_Search_async", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_search_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.SearchServiceClient", + "shortName": "SearchServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.SearchServiceClient.search", + "method": { + "fullName": "google.cloud.retail.v2beta.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2beta.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.services.search_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2beta_generated_search_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_SearchService_Search_sync", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_search_service_search_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.add_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.AddControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "AddControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "add_control" + }, + "description": "Sample for AddControl", + "file": "retail_v2beta_generated_serving_config_service_add_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_AddControl_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_add_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.add_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.AddControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "AddControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "add_control" + }, + "description": "Sample for AddControl", + "file": "retail_v2beta_generated_serving_config_service_add_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_AddControl_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_add_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.create_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.CreateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "CreateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateServingConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2beta.types.ServingConfig" + }, + { + "name": "serving_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "create_serving_config" + }, + "description": "Sample for CreateServingConfig", + "file": "retail_v2beta_generated_serving_config_service_create_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_CreateServingConfig_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_create_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.create_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.CreateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "CreateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateServingConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2beta.types.ServingConfig" + }, + { + "name": "serving_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "create_serving_config" + }, + "description": "Sample for CreateServingConfig", + "file": "retail_v2beta_generated_serving_config_service_create_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_create_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.delete_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.DeleteServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "DeleteServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteServingConfigRequest" + }, + { + "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_serving_config" + }, + "description": "Sample for DeleteServingConfig", + "file": "retail_v2beta_generated_serving_config_service_delete_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_delete_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.delete_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.DeleteServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "DeleteServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteServingConfigRequest" + }, + { + "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_serving_config" + }, + "description": "Sample for DeleteServingConfig", + "file": "retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.get_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.GetServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "GetServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetServingConfigRequest" + }, + { + "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.retail_v2beta.types.ServingConfig", + "shortName": "get_serving_config" + }, + "description": "Sample for GetServingConfig", + "file": "retail_v2beta_generated_serving_config_service_get_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_GetServingConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_get_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.get_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.GetServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "GetServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetServingConfigRequest" + }, + { + "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.retail_v2beta.types.ServingConfig", + "shortName": "get_serving_config" + }, + "description": "Sample for GetServingConfig", + "file": "retail_v2beta_generated_serving_config_service_get_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_GetServingConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_get_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.list_serving_configs", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.ListServingConfigs", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "ListServingConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListServingConfigsRequest" + }, + { + "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.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager", + "shortName": "list_serving_configs" + }, + "description": "Sample for ListServingConfigs", + "file": "retail_v2beta_generated_serving_config_service_list_serving_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_ListServingConfigs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_list_serving_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.list_serving_configs", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.ListServingConfigs", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "ListServingConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListServingConfigsRequest" + }, + { + "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.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsPager", + "shortName": "list_serving_configs" + }, + "description": "Sample for ListServingConfigs", + "file": "retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.remove_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.RemoveControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "RemoveControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "remove_control" + }, + "description": "Sample for RemoveControl", + "file": "retail_v2beta_generated_serving_config_service_remove_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_RemoveControl_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_remove_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.remove_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.RemoveControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "RemoveControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "remove_control" + }, + "description": "Sample for RemoveControl", + "file": "retail_v2beta_generated_serving_config_service_remove_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_RemoveControl_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_remove_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.update_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.UpdateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "UpdateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateServingConfigRequest" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2beta.types.ServingConfig" + }, + { + "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.retail_v2beta.types.ServingConfig", + "shortName": "update_serving_config" + }, + "description": "Sample for UpdateServingConfig", + "file": "retail_v2beta_generated_serving_config_service_update_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_update_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.update_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.UpdateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "UpdateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateServingConfigRequest" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2beta.types.ServingConfig" + }, + { + "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.retail_v2beta.types.ServingConfig", + "shortName": "update_serving_config" + }, + "description": "Sample for UpdateServingConfig", + "file": "retail_v2beta_generated_serving_config_service_update_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_update_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2beta_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_CollectUserEvent_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2beta_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_CollectUserEvent_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2beta_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_ImportUserEvents_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2beta_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_ImportUserEvents_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2beta_generated_user_event_service_purge_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_PurgeUserEvents_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_purge_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2beta_generated_user_event_service_purge_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_PurgeUserEvents_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_purge_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2beta_generated_user_event_service_rejoin_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_RejoinUserEvents_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_rejoin_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_RejoinUserEvents_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2beta_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_WriteUserEvent_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2beta_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_WriteUserEvent_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py b/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py new file mode 100644 index 00000000..dbd16de7 --- /dev/null +++ b/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py @@ -0,0 +1,218 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class retailCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_catalog_attribute': ('attributes_config', 'catalog_attribute', ), + 'add_control': ('serving_config', 'control_id', ), + 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), + 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), + 'create_control': ('parent', 'control', 'control_id', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'create_serving_config': ('parent', 'serving_config', 'serving_config_id', ), + 'delete_control': ('name', ), + 'delete_product': ('name', ), + 'delete_serving_config': ('name', ), + 'get_attributes_config': ('name', ), + 'get_completion_config': ('name', ), + 'get_control': ('name', ), + 'get_default_branch': ('catalog', ), + 'get_product': ('name', ), + 'get_serving_config': ('name', ), + 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), + 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), + 'import_user_events': ('parent', 'input_config', 'errors_config', ), + 'list_catalogs': ('parent', 'page_size', 'page_token', ), + 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', ), + 'list_serving_configs': ('parent', 'page_size', 'page_token', ), + 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), + 'purge_user_events': ('parent', 'filter', 'force', ), + 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), + 'remove_catalog_attribute': ('attributes_config', 'key', ), + 'remove_control': ('serving_config', 'control_id', ), + 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), + 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), + 'replace_catalog_attribute': ('attributes_config', 'catalog_attribute', 'update_mask', ), + 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), + 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), + 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), + 'update_attributes_config': ('attributes_config', 'update_mask', ), + 'update_catalog': ('catalog', 'update_mask', ), + 'update_completion_config': ('completion_config', 'update_mask', ), + 'update_control': ('control', 'update_mask', ), + 'update_product': ('product', 'update_mask', 'allow_missing', ), + 'update_serving_config': ('serving_config', 'update_mask', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=retailCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the retail client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2beta/setup.py b/owl-bot-staging/v2beta/setup.py new file mode 100644 index 00000000..3d49d09f --- /dev/null +++ b/owl-bot-staging/v2beta/setup.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-retail', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-retail", + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.31.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'googleapis-common-protos >= 1.55.0, <2.0.0dev', + 'proto-plus >= 1.19.7', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2beta/tests/__init__.py b/owl-bot-staging/v2beta/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/tests/unit/__init__.py b/owl-bot-staging/v2beta/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py b/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py new file mode 100644 index 00000000..ea836f42 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py @@ -0,0 +1,3793 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.catalog_service import CatalogServiceAsyncClient +from google.cloud.retail_v2beta.services.catalog_service import CatalogServiceClient +from google.cloud.retail_v2beta.services.catalog_service import pagers +from google.cloud.retail_v2beta.services.catalog_service import transports +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CatalogServiceClient._get_default_mtls_endpoint(None) is None + assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CatalogServiceGrpcTransport, "grpc"), + (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_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", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_catalog_service_client_get_transport_class(): + transport = CatalogServiceClient.get_transport_class() + available_transports = [ + transports.CatalogServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CatalogServiceClient.get_transport_class("grpc") + assert transport == transports.CatalogServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + CatalogServiceClient, CatalogServiceAsyncClient +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_catalog_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CatalogServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ListCatalogsRequest, + dict, +]) +def test_list_catalogs(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_catalogs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalogs), + '__call__') as call: + client.list_catalogs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + +@pytest.mark.asyncio +async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_catalogs_async_from_dict(): + await test_list_catalogs_async(request_type=dict) + + +def test_list_catalogs_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = catalog_service.ListCatalogsResponse() + client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_catalogs( + 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_catalogs_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_catalogs_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_catalogs( + 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_catalogs_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + + +def test_list_catalogs_pager(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_catalogs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, catalog.Catalog) + for i in results) +def test_list_catalogs_pages(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = list(client.list_catalogs(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_catalogs_async_pager(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_catalogs(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, catalog.Catalog) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_catalogs_async_pages(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCatalogRequest, + dict, +]) +def test_update_catalog(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + ) + response = client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_catalog_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalog), + '__call__') as call: + client.update_catalog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + +@pytest.mark.asyncio +async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_catalog_async_from_dict(): + await test_update_catalog_async(request_type=dict) + + +def test_update_catalog_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = gcr_catalog.Catalog() + client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_catalog_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +def test_update_catalog_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_catalog_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.SetDefaultBranchRequest, + dict, +]) +def test_set_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_set_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + client.set_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_set_default_branch_async_from_dict(): + await test_set_default_branch_async(request_type=dict) + + +def test_set_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = None + client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_set_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_set_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetDefaultBranchRequest, + dict, +]) +def test_get_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + ) + response = client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +def test_get_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_default_branch), + '__call__') as call: + client.get_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + )) + response = await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +@pytest.mark.asyncio +async def test_get_default_branch_async_from_dict(): + await test_get_default_branch_async(request_type=dict) + + +def test_get_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = catalog_service.GetDefaultBranchResponse() + client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_get_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_get_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetCompletionConfigRequest, + dict, +]) +def test_get_completion_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + ) + response = client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +def test_get_completion_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_completion_config), + '__call__') as call: + client.get_completion_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + +@pytest.mark.asyncio +async def test_get_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCompletionConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + )) + response = await client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +@pytest.mark.asyncio +async def test_get_completion_config_async_from_dict(): + await test_get_completion_config_async(request_type=dict) + + +def test_get_completion_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCompletionConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + call.return_value = catalog.CompletionConfig() + client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_completion_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCompletionConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + await client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_completion_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_completion_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_completion_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_completion_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_completion_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_completion_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCompletionConfigRequest, + dict, +]) +def test_update_completion_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + ) + response = client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +def test_update_completion_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_completion_config), + '__call__') as call: + client.update_completion_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + +@pytest.mark.asyncio +async def test_update_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCompletionConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + )) + response = await client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +@pytest.mark.asyncio +async def test_update_completion_config_async_from_dict(): + await test_update_completion_config_async(request_type=dict) + + +def test_update_completion_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCompletionConfigRequest() + + request.completion_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + call.return_value = catalog.CompletionConfig() + client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'completion_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_completion_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCompletionConfigRequest() + + request.completion_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + await client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'completion_config.name=name_value', + ) in kw['metadata'] + + +def test_update_completion_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_completion_config( + completion_config=catalog.CompletionConfig(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].completion_config + mock_val = catalog.CompletionConfig(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_completion_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_completion_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_completion_config( + completion_config=catalog.CompletionConfig(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].completion_config + mock_val = catalog.CompletionConfig(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_completion_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetAttributesConfigRequest, + dict, +]) +def test_get_attributes_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_get_attributes_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_attributes_config), + '__call__') as call: + client.get_attributes_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + +@pytest.mark.asyncio +async def test_get_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetAttributesConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_get_attributes_config_async_from_dict(): + await test_get_attributes_config_async(request_type=dict) + + +def test_get_attributes_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetAttributesConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_attributes_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetAttributesConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_attributes_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_attributes_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_attributes_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_attributes_config( + catalog_service.GetAttributesConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_attributes_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_attributes_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_attributes_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_attributes_config( + catalog_service.GetAttributesConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateAttributesConfigRequest, + dict, +]) +def test_update_attributes_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_update_attributes_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_attributes_config), + '__call__') as call: + client.update_attributes_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + +@pytest.mark.asyncio +async def test_update_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateAttributesConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_update_attributes_config_async_from_dict(): + await test_update_attributes_config_async(request_type=dict) + + +def test_update_attributes_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateAttributesConfigRequest() + + request.attributes_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_attributes_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateAttributesConfigRequest() + + request.attributes_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config.name=name_value', + ) in kw['metadata'] + + +def test_update_attributes_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_attributes_config( + attributes_config=catalog.AttributesConfig(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].attributes_config + mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_attributes_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_attributes_config( + attributes_config=catalog.AttributesConfig(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].attributes_config + mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.AddCatalogAttributeRequest, + dict, +]) +def test_add_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_add_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + client.add_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_add_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.AddCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_add_catalog_attribute_async_from_dict(): + await test_add_catalog_attribute_async(request_type=dict) + + +def test_add_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.AddCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.AddCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + catalog_service.RemoveCatalogAttributeRequest, + dict, +]) +def test_remove_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_remove_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + client.remove_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.RemoveCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_async_from_dict(): + await test_remove_catalog_attribute_async(request_type=dict) + + +def test_remove_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.RemoveCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.RemoveCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ReplaceCatalogAttributeRequest, + dict, +]) +def test_replace_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_replace_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + client.replace_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ReplaceCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_async_from_dict(): + await test_replace_catalog_attribute_async(request_type=dict) + + +def test_replace_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ReplaceCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ReplaceCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CatalogServiceClient.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 = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CatalogServiceGrpcTransport, + ) + +def test_catalog_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_catalog_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_catalogs', + 'update_catalog', + 'set_default_branch', + 'get_default_branch', + 'get_completion_config', + 'update_completion_config', + 'get_attributes_config', + 'update_attributes_config', + 'add_catalog_attribute', + 'remove_catalog_attribute', + 'replace_catalog_attribute', + ) + 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_catalog_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.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport( + 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_catalog_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.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport() + adc.assert_called_once() + + +def test_catalog_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) + CatalogServiceClient() + 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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +def test_catalog_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,grpc_helpers", + [ + (transports.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_catalog_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_no_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_with_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_catalog_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcTransport( + 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_catalog_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcAsyncIOTransport( + 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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_attributes_config_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.attributes_config_path(project, location, catalog) + assert expected == actual + + +def test_parse_attributes_config_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CatalogServiceClient.attributes_config_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_attributes_config_path(path) + assert expected == actual + +def test_branch_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = CatalogServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "branch": "clam", + } + path = CatalogServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_branch_path(path) + assert expected == actual + +def test_catalog_path(): + project = "whelk" + location = "octopus" + catalog = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + } + path = CatalogServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_completion_config_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.completion_config_path(project, location, catalog) + assert expected == actual + + +def test_parse_completion_config_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + } + path = CatalogServiceClient.completion_config_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_completion_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CatalogServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = CatalogServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = CatalogServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CatalogServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CatalogServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CatalogServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = CatalogServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CatalogServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CatalogServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CatalogServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py new file mode 100644 index 00000000..6ba74e1e --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py @@ -0,0 +1,1451 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.completion_service import CompletionServiceAsyncClient +from google.cloud.retail_v2beta.services.completion_service import CompletionServiceClient +from google.cloud.retail_v2beta.services.completion_service import transports +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CompletionServiceClient._get_default_mtls_endpoint(None) is None + assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CompletionServiceGrpcTransport, "grpc"), + (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_completion_service_client_get_transport_class(): + transport = CompletionServiceClient.get_transport_class() + available_transports = [ + transports.CompletionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CompletionServiceClient.get_transport_class("grpc") + assert transport == transports.CompletionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + CompletionServiceClient, CompletionServiceAsyncClient +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_completion_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CompletionServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + ) + response = client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +def test_complete_query_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + client.complete_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + +@pytest.mark.asyncio +async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + )) + response = await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +@pytest.mark.asyncio +async def test_complete_query_async_from_dict(): + await test_complete_query_async(request_type=dict) + + +def test_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) + await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportCompletionDataRequest, + dict, +]) +def test_import_completion_data(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_completion_data_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + client.import_completion_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + +@pytest.mark.asyncio +async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_completion_data_async_from_dict(): + await test_import_completion_data_async(request_type=dict) + + +def test_import_completion_data_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # 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_completion_data_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CompletionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CompletionServiceGrpcTransport, + ) + +def test_completion_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_completion_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'complete_query', + 'import_completion_data', + ) + 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_completion_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_completion_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport() + adc.assert_called_once() + + +def test_completion_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CompletionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionServiceGrpcTransport, grpc_helpers), + (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_completion_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_no_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_with_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_completion_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_completion_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_completion_service_grpc_lro_client(): + client = CompletionServiceClient( + 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_completion_service_grpc_lro_async_client(): + client = CompletionServiceAsyncClient( + 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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CompletionServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CompletionServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CompletionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CompletionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = CompletionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CompletionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CompletionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CompletionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = CompletionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CompletionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CompletionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CompletionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CompletionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py new file mode 100644 index 00000000..0f0f4080 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py @@ -0,0 +1,2554 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.control_service import ControlServiceAsyncClient +from google.cloud.retail_v2beta.services.control_service import ControlServiceClient +from google.cloud.retail_v2beta.services.control_service import pagers +from google.cloud.retail_v2beta.services.control_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.cloud.retail_v2beta.types import search_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ControlServiceClient._get_default_mtls_endpoint(None) is None + assert ControlServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ControlServiceClient, "grpc"), + (ControlServiceAsyncClient, "grpc_asyncio"), +]) +def test_control_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ControlServiceGrpcTransport, "grpc"), + (transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_control_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", [ + (ControlServiceClient, "grpc"), + (ControlServiceAsyncClient, "grpc_asyncio"), +]) +def test_control_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_control_service_client_get_transport_class(): + transport = ControlServiceClient.get_transport_class() + available_transports = [ + transports.ControlServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ControlServiceClient.get_transport_class("grpc") + assert transport == transports.ControlServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +def test_control_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(ControlServiceClient, '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(ControlServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "true"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "false"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_control_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + ControlServiceClient, ControlServiceAsyncClient +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +def test_control_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_control_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_control_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_control_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.control_service.transports.ControlServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ControlServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_control_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.CreateControlRequest, + dict, +]) +def test_create_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_create_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.create_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + +@pytest.mark.asyncio +async def test_create_control_async(transport: str = 'grpc_asyncio', request_type=control_service.CreateControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_create_control_async_from_dict(): + await test_create_control_async(request_type=dict) + + +def test_create_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.CreateControlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + call.return_value = gcr_control.Control() + client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.CreateControlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + await client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_control( + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) + assert arg == mock_val + arg = args[0].control_id + mock_val = 'control_id_value' + assert arg == mock_val + + +def test_create_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.CreateControlRequest(), + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_id_value', + ) + +@pytest.mark.asyncio +async def test_create_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_control( + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) + assert arg == mock_val + arg = args[0].control_id + mock_val = 'control_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.CreateControlRequest(), + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.DeleteControlRequest, + dict, +]) +def test_delete_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.delete_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + +@pytest.mark.asyncio +async def test_delete_control_async(transport: str = 'grpc_asyncio', request_type=control_service.DeleteControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_control_async_from_dict(): + await test_delete_control_async(request_type=dict) + + +def test_delete_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.DeleteControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__call__') as call: + call.return_value = None + client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.DeleteControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__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_control( + 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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.DeleteControlRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__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_control( + 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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.DeleteControlRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.UpdateControlRequest, + dict, +]) +def test_update_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_update_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.update_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + +@pytest.mark.asyncio +async def test_update_control_async(transport: str = 'grpc_asyncio', request_type=control_service.UpdateControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_update_control_async_from_dict(): + await test_update_control_async(request_type=dict) + + +def test_update_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.UpdateControlRequest() + + request.control.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + call.return_value = gcr_control.Control() + client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'control.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.UpdateControlRequest() + + request.control.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + await client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'control.name=name_value', + ) in kw['metadata'] + + +def test_update_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_control( + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_control( + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.GetControlRequest, + dict, +]) +def test_get_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_get_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.get_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + +@pytest.mark.asyncio +async def test_get_control_async(transport: str = 'grpc_asyncio', request_type=control_service.GetControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_get_control_async_from_dict(): + await test_get_control_async(request_type=dict) + + +def test_get_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.GetControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + call.return_value = control.Control() + client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.GetControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) + await client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_control( + 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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.GetControlRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_control( + 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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.GetControlRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.ListControlsRequest, + dict, +]) +def test_list_controls(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_controls_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_controls), + '__call__') as call: + client.list_controls() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + +@pytest.mark.asyncio +async def test_list_controls_async(transport: str = 'grpc_asyncio', request_type=control_service.ListControlsRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_controls_async_from_dict(): + await test_list_controls_async(request_type=dict) + + +def test_list_controls_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.ListControlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + call.return_value = control_service.ListControlsResponse() + client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_controls_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.ListControlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) + await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_controls_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_controls( + 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_controls_flattened_error(): + client = ControlServiceClient( + credentials=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_controls( + control_service.ListControlsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_controls_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_controls( + 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_controls_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_controls( + control_service.ListControlsRequest(), + parent='parent_value', + ) + + +def test_list_controls_pager(transport_name: str = "grpc"): + client = ControlServiceClient( + 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_controls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_controls(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, control.Control) + for i in results) +def test_list_controls_pages(transport_name: str = "grpc"): + client = ControlServiceClient( + 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_controls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + pages = list(client.list_controls(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_controls_async_pager(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_controls(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, control.Control) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_controls_async_pages(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_controls(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ControlServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ControlServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ControlServiceClient.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 = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ControlServiceGrpcTransport, + ) + +def test_control_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ControlServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_control_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.control_service.transports.ControlServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ControlServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_control', + 'delete_control', + 'update_control', + 'get_control', + 'list_controls', + ) + 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_control_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.retail_v2beta.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ControlServiceTransport( + 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_control_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.retail_v2beta.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ControlServiceTransport() + adc.assert_called_once() + + +def test_control_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) + ControlServiceClient() + 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.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + ], +) +def test_control_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,grpc_helpers", + [ + (transports.ControlServiceGrpcTransport, grpc_helpers), + (transports.ControlServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_control_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_control_service_host_no_port(transport_name): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_control_service_host_with_port(transport_name): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_control_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ControlServiceGrpcTransport( + 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_control_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ControlServiceGrpcAsyncIOTransport( + 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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = ControlServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = ControlServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_control_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + control = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) + actual = ControlServiceClient.control_path(project, location, catalog, control) + assert expected == actual + + +def test_parse_control_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "control": "clam", + } + path = ControlServiceClient.control_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_control_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ControlServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ControlServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ControlServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ControlServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ControlServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ControlServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ControlServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ControlServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.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 = ControlServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ControlServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.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.ControlServiceTransport, '_prep_wrapped_messages') as prep: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ControlServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ControlServiceClient.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 = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ControlServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ControlServiceClient( + 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", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py new file mode 100644 index 00000000..3115c5c9 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py @@ -0,0 +1,1279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.prediction_service import PredictionServiceAsyncClient +from google.cloud.retail_v2beta.services.prediction_service import PredictionServiceClient +from google.cloud.retail_v2beta.services.prediction_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import prediction_service +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import promotion +from google.cloud.retail_v2beta.types import user_event +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PredictionServiceClient._get_default_mtls_endpoint(None) is None + assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionServiceGrpcTransport, "grpc"), + (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_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", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_prediction_service_client_get_transport_class(): + transport = PredictionServiceClient.get_transport_class() + available_transports = [ + transports.PredictionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = PredictionServiceClient.get_transport_class("grpc") + assert transport == transports.PredictionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + PredictionServiceClient, PredictionServiceAsyncClient +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_prediction_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PredictionServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_service.PredictRequest, + dict, +]) +def test_predict(request_type, transport: str = 'grpc'): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + response = client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_predict_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + client.predict() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + +@pytest.mark.asyncio +async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + )) + response = await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +@pytest.mark.asyncio +async def test_predict_async_from_dict(): + await test_predict_async(request_type=dict) + + +def test_predict_field_headers(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_predict_field_headers_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) + await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = PredictionServiceClient.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 = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'predict', + ) + 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport( + 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport() + adc.assert_called_once() + + +def test_prediction_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) + PredictionServiceClient() + 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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +def test_prediction_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,grpc_helpers", + [ + (transports.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_prediction_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_no_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_with_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_prediction_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcTransport( + 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_prediction_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcAsyncIOTransport( + 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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_product_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + product = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + "branch": "winkle", + "product": "nautilus", + } + path = PredictionServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PredictionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = PredictionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = PredictionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = PredictionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PredictionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = PredictionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = PredictionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = PredictionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = PredictionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PredictionServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py new file mode 100644 index 00000000..87547c3f --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py @@ -0,0 +1,4085 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.product_service import ProductServiceAsyncClient +from google.cloud.retail_v2beta.services.product_service import ProductServiceClient +from google.cloud.retail_v2beta.services.product_service import pagers +from google.cloud.retail_v2beta.services.product_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.cloud.retail_v2beta.types import promotion +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProductServiceClient._get_default_mtls_endpoint(None) is None + assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProductServiceGrpcTransport, "grpc"), + (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_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", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_product_service_client_get_transport_class(): + transport = ProductServiceClient.get_transport_class() + available_transports = [ + transports.ProductServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ProductServiceClient.get_transport_class("grpc") + assert transport == transports.ProductServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_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(ProductServiceClient, '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(ProductServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + ProductServiceClient, ProductServiceAsyncClient +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_product_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProductServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.CreateProductRequest, + dict, +]) +def test_create_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_create_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.create_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + +@pytest.mark.asyncio +async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_create_product_async_from_dict(): + await test_create_product_async(request_type=dict) + + +def test_create_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + + +def test_create_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + +@pytest.mark.asyncio +async def test_create_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_get_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.get_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + +@pytest.mark.asyncio +async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_get_product_async_from_dict(): + await test_get_product_async(request_type=dict) + + +def test_get_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = product.Product() + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.GetProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.GetProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.list_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + +@pytest.mark.asyncio +async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_products_async_from_dict(): + await test_list_products_async(request_type=dict) + + +def test_list_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = product_service.ListProductsResponse() + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products( + 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_products_flattened_error(): + client = ProductServiceClient( + credentials=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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products( + 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_products_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + + +def test_list_products_pager(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_products(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, product.Product) + for i in results) +def test_list_products_pages(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(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_products_async_pager(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(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, product.Product) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_products(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + product_service.UpdateProductRequest, + dict, +]) +def test_update_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_update_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.update_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + +@pytest.mark.asyncio +async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_update_product_async_from_dict(): + await test_update_product_async(request_type=dict) + + +def test_update_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +def test_update_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.DeleteProductRequest, + dict, +]) +def test_delete_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.delete_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + +@pytest.mark.asyncio +async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_product_async_from_dict(): + await test_delete_product_async(request_type=dict) + + +def test_delete_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = None + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportProductsRequest, + dict, +]) +def test_import_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.import_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + +@pytest.mark.asyncio +async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__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_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_products_async_from_dict(): + await test_import_products_async(request_type=dict) + + +def test_import_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + product_service.SetInventoryRequest, + dict, +]) +def test_set_inventory(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_inventory_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + client.set_inventory() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + +@pytest.mark.asyncio +async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_set_inventory_async_from_dict(): + await test_set_inventory_async(request_type=dict) + + +def test_set_inventory_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_inventory_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +def test_set_inventory_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_set_inventory_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_set_inventory_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_inventory_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddFulfillmentPlacesRequest, + dict, +]) +def test_add_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + client.add_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async_from_dict(): + await test_add_fulfillment_places_async(request_type=dict) + + +def test_add_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveFulfillmentPlacesRequest, + dict, +]) +def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + client.remove_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async_from_dict(): + await test_remove_fulfillment_places_async(request_type=dict) + + +def test_remove_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddLocalInventoriesRequest, + dict, +]) +def test_add_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + client.add_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_local_inventories_async_from_dict(): + await test_add_local_inventories_async(request_type=dict) + + +def test_add_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveLocalInventoriesRequest, + dict, +]) +def test_remove_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + client.remove_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_local_inventories_async_from_dict(): + await test_remove_local_inventories_async(request_type=dict) + + +def test_remove_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ProductServiceClient.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 = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProductServiceGrpcTransport, + ) + +def test_product_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_product_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.product_service.transports.ProductServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_product', + 'get_product', + 'list_products', + 'update_product', + 'delete_product', + 'import_products', + 'set_inventory', + 'add_fulfillment_places', + 'remove_fulfillment_places', + 'add_local_inventories', + 'remove_local_inventories', + ) + 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_product_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.retail_v2beta.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport( + 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_product_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.retail_v2beta.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport() + adc.assert_called_once() + + +def test_product_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) + ProductServiceClient() + 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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + ], +) +def test_product_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,grpc_helpers", + [ + (transports.ProductServiceGrpcTransport, grpc_helpers), + (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_product_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_no_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_with_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_product_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcTransport( + 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_product_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcAsyncIOTransport( + 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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_product_service_grpc_lro_client(): + client = ProductServiceClient( + 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_product_service_grpc_lro_async_client(): + client = ProductServiceAsyncClient( + 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" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = ProductServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = ProductServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = ProductServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = ProductServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProductServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ProductServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProductServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ProductServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProductServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ProductServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ProductServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ProductServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ProductServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ProductServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ProductServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py new file mode 100644 index 00000000..9ee8f756 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py @@ -0,0 +1,1496 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.search_service import SearchServiceAsyncClient +from google.cloud.retail_v2beta.services.search_service import SearchServiceClient +from google.cloud.retail_v2beta.services.search_service import pagers +from google.cloud.retail_v2beta.services.search_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SearchServiceClient._get_default_mtls_endpoint(None) is None + assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SearchServiceGrpcTransport, "grpc"), + (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_search_service_client_get_transport_class(): + transport = SearchServiceClient.get_transport_class() + available_transports = [ + transports.SearchServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SearchServiceClient.get_transport_class("grpc") + assert transport == transports.SearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + SearchServiceClient, SearchServiceAsyncClient +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SearchServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + search_service.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + + +def test_search_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = search_service.SearchResponse() + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_search_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('placement', ''), + )), + ) + pager = client.search(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_async_pager(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = SearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_search_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_search_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport() + adc.assert_called_once() + + +def test_search_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SearchServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SearchServiceGrpcTransport, grpc_helpers), + (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_search_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_no_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_with_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_branch_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = SearchServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = SearchServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = SearchServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = SearchServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py new file mode 100644 index 00000000..071b0b17 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py @@ -0,0 +1,3279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.serving_config_service import ServingConfigServiceAsyncClient +from google.cloud.retail_v2beta.services.serving_config_service import ServingConfigServiceClient +from google.cloud.retail_v2beta.services.serving_config_service import pagers +from google.cloud.retail_v2beta.services.serving_config_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ServingConfigServiceClient._get_default_mtls_endpoint(None) is None + assert ServingConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ServingConfigServiceClient, "grpc"), + (ServingConfigServiceAsyncClient, "grpc_asyncio"), +]) +def test_serving_config_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ServingConfigServiceGrpcTransport, "grpc"), + (transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_serving_config_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", [ + (ServingConfigServiceClient, "grpc"), + (ServingConfigServiceAsyncClient, "grpc_asyncio"), +]) +def test_serving_config_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_serving_config_service_client_get_transport_class(): + transport = ServingConfigServiceClient.get_transport_class() + available_transports = [ + transports.ServingConfigServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ServingConfigServiceClient.get_transport_class("grpc") + assert transport == transports.ServingConfigServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +def test_serving_config_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(ServingConfigServiceClient, '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(ServingConfigServiceClient, '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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "true"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "false"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_serving_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + ServingConfigServiceClient, ServingConfigServiceAsyncClient +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +def test_serving_config_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_serving_config_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_serving_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_serving_config_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ServingConfigServiceClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_serving_config_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.CreateServingConfigRequest, + dict, +]) +def test_create_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_create_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.create_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + +@pytest.mark.asyncio +async def test_create_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.CreateServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_create_serving_config_async_from_dict(): + await test_create_serving_config_async(request_type=dict) + + +def test_create_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.CreateServingConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.CreateServingConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_serving_config( + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].serving_config + mock_val = gcr_serving_config.ServingConfig(name='name_value') + assert arg == mock_val + arg = args[0].serving_config_id + mock_val = 'serving_config_id_value' + assert arg == mock_val + + +def test_create_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.CreateServingConfigRequest(), + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_serving_config( + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].serving_config + mock_val = gcr_serving_config.ServingConfig(name='name_value') + assert arg == mock_val + arg = args[0].serving_config_id + mock_val = 'serving_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.CreateServingConfigRequest(), + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.DeleteServingConfigRequest, + dict, +]) +def test_delete_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.delete_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + +@pytest.mark.asyncio +async def test_delete_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.DeleteServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_serving_config_async_from_dict(): + await test_delete_serving_config_async(request_type=dict) + + +def test_delete_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.DeleteServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__call__') as call: + call.return_value = None + client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.DeleteServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__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_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.DeleteServingConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__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_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.DeleteServingConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.UpdateServingConfigRequest, + dict, +]) +def test_update_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_update_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.update_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + +@pytest.mark.asyncio +async def test_update_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.UpdateServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_update_serving_config_async_from_dict(): + await test_update_serving_config_async(request_type=dict) + + +def test_update_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.UpdateServingConfigRequest() + + request.serving_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.UpdateServingConfigRequest() + + request.serving_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config.name=name_value', + ) in kw['metadata'] + + +def test_update_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_serving_config( + serving_config=gcr_serving_config.ServingConfig(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].serving_config + mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_serving_config( + serving_config=gcr_serving_config.ServingConfig(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].serving_config + mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.GetServingConfigRequest, + dict, +]) +def test_get_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_get_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.get_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + +@pytest.mark.asyncio +async def test_get_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.GetServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_get_serving_config_async_from_dict(): + await test_get_serving_config_async(request_type=dict) + + +def test_get_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.GetServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + call.return_value = serving_config.ServingConfig() + client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.GetServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) + await client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.GetServingConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.GetServingConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.ListServingConfigsRequest, + dict, +]) +def test_list_serving_configs(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_serving_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_configs), + '__call__') as call: + client.list_serving_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + +@pytest.mark.asyncio +async def test_list_serving_configs_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.ListServingConfigsRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_serving_configs_async_from_dict(): + await test_list_serving_configs_async(request_type=dict) + + +def test_list_serving_configs_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.ListServingConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + call.return_value = serving_config_service.ListServingConfigsResponse() + client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_serving_configs_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.ListServingConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) + await client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_serving_configs_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_serving_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_serving_configs_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_serving_configs_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_serving_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_serving_configs_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent='parent_value', + ) + + +def test_list_serving_configs_pager(transport_name: str = "grpc"): + client = ServingConfigServiceClient( + 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_serving_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_serving_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, serving_config.ServingConfig) + for i in results) +def test_list_serving_configs_pages(transport_name: str = "grpc"): + client = ServingConfigServiceClient( + 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_serving_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_serving_configs(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_serving_configs_async_pager(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_serving_configs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, serving_config.ServingConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_serving_configs_async_pages(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_serving_configs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + serving_config_service.AddControlRequest, + dict, +]) +def test_add_control(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_add_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + client.add_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + +@pytest.mark.asyncio +async def test_add_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.AddControlRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_add_control_async_from_dict(): + await test_add_control_async(request_type=dict) + + +def test_add_control_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.AddControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_control_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.AddControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_add_control_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + + +def test_add_control_flattened_error(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_control( + serving_config_service.AddControlRequest(), + serving_config='serving_config_value', + ) + +@pytest.mark.asyncio +async def test_add_control_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_control_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_control( + serving_config_service.AddControlRequest(), + serving_config='serving_config_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.RemoveControlRequest, + dict, +]) +def test_remove_control(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_remove_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + client.remove_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + +@pytest.mark.asyncio +async def test_remove_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.RemoveControlRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_remove_control_async_from_dict(): + await test_remove_control_async(request_type=dict) + + +def test_remove_control_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.RemoveControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_control_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.RemoveControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_remove_control_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + + +def test_remove_control_flattened_error(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config='serving_config_value', + ) + +@pytest.mark.asyncio +async def test_remove_control_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_control_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config='serving_config_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServingConfigServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ServingConfigServiceClient.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 = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ServingConfigServiceGrpcTransport, + ) + +def test_serving_config_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ServingConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_serving_config_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ServingConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_serving_config', + 'delete_serving_config', + 'update_serving_config', + 'get_serving_config', + 'list_serving_configs', + 'add_control', + 'remove_control', + ) + 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_serving_config_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.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServingConfigServiceTransport( + 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_serving_config_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.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServingConfigServiceTransport() + adc.assert_called_once() + + +def test_serving_config_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) + ServingConfigServiceClient() + 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.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + ], +) +def test_serving_config_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,grpc_helpers", + [ + (transports.ServingConfigServiceGrpcTransport, grpc_helpers), + (transports.ServingConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_serving_config_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_serving_config_service_host_no_port(transport_name): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_serving_config_service_host_with_port(transport_name): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_serving_config_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServingConfigServiceGrpcTransport( + 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_serving_config_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + 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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = ServingConfigServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = ServingConfigServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + serving_config = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, serving_config=serving_config, ) + actual = ServingConfigServiceClient.serving_config_path(project, location, catalog, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "serving_config": "clam", + } + path = ServingConfigServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ServingConfigServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ServingConfigServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ServingConfigServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ServingConfigServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ServingConfigServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ServingConfigServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ServingConfigServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ServingConfigServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.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 = ServingConfigServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ServingConfigServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.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.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ServingConfigServiceClient.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 = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ServingConfigServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ServingConfigServiceClient( + 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", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py new file mode 100644 index 00000000..0274310f --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py @@ -0,0 +1,1988 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.retail_v2beta.services.user_event_service import UserEventServiceClient +from google.cloud.retail_v2beta.services.user_event_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import promotion +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + ) + response = client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +def test_write_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) + await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeUserEventsRequest, + dict, +]) +def test_purge_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + client.purge_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + +@pytest.mark.asyncio +async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_user_events_async_from_dict(): + await test_purge_user_events_async(request_type=dict) + + +def test_purge_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_purge_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.RejoinUserEventsRequest, + dict, +]) +def test_rejoin_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_rejoin_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + client.rejoin_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + +@pytest.mark.asyncio +async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_rejoin_user_events_async_from_dict(): + await test_rejoin_user_events_async(request_type=dict) + + +def test_rejoin_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_rejoin_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'purge_user_events', + 'import_user_events', + 'rejoin_user_events', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_user_event_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_user_event_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +def test_user_event_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + UserEventServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = UserEventServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = UserEventServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_product_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + product = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + "branch": "whelk", + "product": "octopus", + } + path = UserEventServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) From a0ddcf64e2f4955111e71b5f0e18c5199ca3f327 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 1 Jun 2022 03:51:46 +0000 Subject: [PATCH 02/11] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../services/product_service/async_client.py | 29 +- .../services/product_service/client.py | 29 +- .../product_service/transports/grpc.py | 6 +- .../transports/grpc_asyncio.py | 6 +- google/cloud/retail_v2/types/catalog.py | 11 +- google/cloud/retail_v2/types/common.py | 38 +- .../retail_v2/types/completion_service.py | 14 +- google/cloud/retail_v2/types/import_config.py | 20 +- .../retail_v2/types/prediction_service.py | 36 +- google/cloud/retail_v2/types/product.py | 4 +- .../cloud/retail_v2/types/product_service.py | 35 +- .../cloud/retail_v2/types/search_service.py | 132 +- google/cloud/retail_v2/types/user_event.py | 9 +- owl-bot-staging/v2/.coveragerc | 17 - owl-bot-staging/v2/.flake8 | 33 - owl-bot-staging/v2/MANIFEST.in | 2 - owl-bot-staging/v2/README.rst | 49 - owl-bot-staging/v2/docs/conf.py | 376 - owl-bot-staging/v2/docs/index.rst | 7 - .../v2/docs/retail_v2/catalog_service.rst | 10 - .../v2/docs/retail_v2/completion_service.rst | 6 - .../v2/docs/retail_v2/prediction_service.rst | 6 - .../v2/docs/retail_v2/product_service.rst | 10 - .../v2/docs/retail_v2/search_service.rst | 10 - .../v2/docs/retail_v2/services.rst | 11 - owl-bot-staging/v2/docs/retail_v2/types.rst | 7 - .../v2/docs/retail_v2/user_event_service.rst | 6 - .../v2/google/cloud/retail/__init__.py | 193 - .../v2/google/cloud/retail/py.typed | 2 - .../v2/google/cloud/retail_v2/__init__.py | 194 - .../cloud/retail_v2/gapic_metadata.json | 333 - .../v2/google/cloud/retail_v2/py.typed | 2 - .../cloud/retail_v2/services/__init__.py | 15 - .../services/catalog_service/__init__.py | 22 - .../services/catalog_service/async_client.py | 653 -- .../services/catalog_service/client.py | 861 -- .../services/catalog_service/pagers.py | 140 - .../catalog_service/transports/__init__.py | 33 - .../catalog_service/transports/base.py | 194 - .../catalog_service/transports/grpc.py | 379 - .../transports/grpc_asyncio.py | 378 - .../services/completion_service/__init__.py | 22 - .../completion_service/async_client.py | 391 - .../services/completion_service/client.py | 592 -- .../completion_service/transports/__init__.py | 33 - .../completion_service/transports/base.py | 172 - .../completion_service/transports/grpc.py | 323 - .../transports/grpc_asyncio.py | 322 - .../services/prediction_service/__init__.py | 22 - .../prediction_service/async_client.py | 279 - .../services/prediction_service/client.py | 479 -- .../prediction_service/transports/__init__.py | 33 - .../prediction_service/transports/base.py | 150 - .../prediction_service/transports/grpc.py | 262 - .../transports/grpc_asyncio.py | 261 - .../services/product_service/__init__.py | 22 - .../services/product_service/async_client.py | 1701 ---- .../services/product_service/client.py | 1903 ----- .../services/product_service/pagers.py | 140 - .../product_service/transports/__init__.py | 33 - .../product_service/transports/base.py | 308 - .../product_service/transports/grpc.py | 678 -- .../transports/grpc_asyncio.py | 677 -- .../services/search_service/__init__.py | 22 - .../services/search_service/async_client.py | 303 - .../services/search_service/client.py | 512 -- .../services/search_service/pagers.py | 139 - .../search_service/transports/__init__.py | 33 - .../search_service/transports/base.py | 150 - .../search_service/transports/grpc.py | 268 - .../search_service/transports/grpc_asyncio.py | 267 - .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 730 -- .../services/user_event_service/client.py | 929 --- .../user_event_service/transports/__init__.py | 33 - .../user_event_service/transports/base.py | 231 - .../user_event_service/transports/grpc.py | 415 - .../transports/grpc_asyncio.py | 414 - .../google/cloud/retail_v2/types/__init__.py | 194 - .../google/cloud/retail_v2/types/catalog.py | 131 - .../cloud/retail_v2/types/catalog_service.py | 248 - .../v2/google/cloud/retail_v2/types/common.py | 736 -- .../retail_v2/types/completion_service.py | 229 - .../cloud/retail_v2/types/import_config.py | 697 -- .../retail_v2/types/prediction_service.py | 275 - .../google/cloud/retail_v2/types/product.py | 701 -- .../cloud/retail_v2/types/product_service.py | 858 -- .../google/cloud/retail_v2/types/promotion.py | 50 - .../cloud/retail_v2/types/purge_config.py | 107 - .../cloud/retail_v2/types/search_service.py | 1150 --- .../cloud/retail_v2/types/user_event.py | 508 -- .../retail_v2/types/user_event_service.py | 154 - owl-bot-staging/v2/mypy.ini | 3 - owl-bot-staging/v2/noxfile.py | 180 - ...atalog_service_get_default_branch_async.py | 44 - ...catalog_service_get_default_branch_sync.py | 44 - ...ted_catalog_service_list_catalogs_async.py | 46 - ...ated_catalog_service_list_catalogs_sync.py | 46 - ...atalog_service_set_default_branch_async.py | 42 - ...catalog_service_set_default_branch_sync.py | 42 - ...ed_catalog_service_update_catalog_async.py | 49 - ...ted_catalog_service_update_catalog_sync.py | 49 - ...completion_service_complete_query_async.py | 46 - ..._completion_service_complete_query_sync.py | 46 - ...on_service_import_completion_data_async.py | 54 - ...ion_service_import_completion_data_sync.py | 54 - ...erated_prediction_service_predict_async.py | 50 - ...nerated_prediction_service_predict_sync.py | 50 - ...ct_service_add_fulfillment_places_async.py | 51 - ...uct_service_add_fulfillment_places_sync.py | 51 - ...uct_service_add_local_inventories_async.py | 49 - ...duct_service_add_local_inventories_sync.py | 49 - ...ed_product_service_create_product_async.py | 50 - ...ted_product_service_create_product_sync.py | 50 - ...ed_product_service_delete_product_async.py | 43 - ...ted_product_service_delete_product_sync.py | 43 - ...rated_product_service_get_product_async.py | 45 - ...erated_product_service_get_product_sync.py | 45 - ...d_product_service_import_products_async.py | 53 - ...ed_product_service_import_products_sync.py | 53 - ...ted_product_service_list_products_async.py | 46 - ...ated_product_service_list_products_sync.py | 46 - ...service_remove_fulfillment_places_async.py | 51 - ..._service_remove_fulfillment_places_sync.py | 51 - ..._service_remove_local_inventories_async.py | 50 - ...t_service_remove_local_inventories_sync.py | 50 - ...ted_product_service_set_inventory_async.py | 52 - ...ated_product_service_set_inventory_sync.py | 52 - ...ed_product_service_update_product_async.py | 48 - ...ted_product_service_update_product_sync.py | 48 - ...2_generated_search_service_search_async.py | 47 - ...v2_generated_search_service_search_sync.py | 47 - ..._event_service_collect_user_event_async.py | 46 - ...r_event_service_collect_user_event_sync.py | 46 - ..._event_service_import_user_events_async.py | 54 - ...r_event_service_import_user_events_sync.py | 54 - ...r_event_service_purge_user_events_async.py | 50 - ...er_event_service_purge_user_events_sync.py | 50 - ..._event_service_rejoin_user_events_async.py | 49 - ...r_event_service_rejoin_user_events_sync.py | 49 - ...er_event_service_write_user_event_async.py | 50 - ...ser_event_service_write_user_event_sync.py | 50 - .../snippet_metadata_retail_v2.json | 3826 --------- .../v2/scripts/fixup_retail_v2_keywords.py | 199 - owl-bot-staging/v2/setup.py | 59 - owl-bot-staging/v2/tests/__init__.py | 16 - owl-bot-staging/v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../v2/tests/unit/gapic/retail_v2/__init__.py | 16 - .../gapic/retail_v2/test_catalog_service.py | 2267 ------ .../retail_v2/test_completion_service.py | 1451 ---- .../retail_v2/test_prediction_service.py | 1279 --- .../gapic/retail_v2/test_product_service.py | 4085 ---------- .../gapic/retail_v2/test_search_service.py | 1496 ---- .../retail_v2/test_user_event_service.py | 1988 ----- owl-bot-staging/v2alpha/.coveragerc | 17 - owl-bot-staging/v2alpha/.flake8 | 33 - owl-bot-staging/v2alpha/MANIFEST.in | 2 - owl-bot-staging/v2alpha/README.rst | 49 - owl-bot-staging/v2alpha/docs/conf.py | 376 - owl-bot-staging/v2alpha/docs/index.rst | 7 - .../docs/retail_v2alpha/catalog_service.rst | 10 - .../retail_v2alpha/completion_service.rst | 6 - .../docs/retail_v2alpha/control_service.rst | 10 - .../retail_v2alpha/prediction_service.rst | 6 - .../docs/retail_v2alpha/product_service.rst | 10 - .../docs/retail_v2alpha/search_service.rst | 10 - .../v2alpha/docs/retail_v2alpha/services.rst | 13 - .../retail_v2alpha/serving_config_service.rst | 10 - .../v2alpha/docs/retail_v2alpha/types.rst | 7 - .../retail_v2alpha/user_event_service.rst | 6 - .../v2alpha/google/cloud/retail/__init__.py | 281 - .../v2alpha/google/cloud/retail/py.typed | 2 - .../google/cloud/retail_v2alpha/__init__.py | 282 - .../cloud/retail_v2alpha/gapic_metadata.json | 561 -- .../google/cloud/retail_v2alpha/py.typed | 2 - .../cloud/retail_v2alpha/services/__init__.py | 15 - .../services/catalog_service/__init__.py | 22 - .../services/catalog_service/async_client.py | 1352 ---- .../services/catalog_service/client.py | 1581 ---- .../services/catalog_service/pagers.py | 140 - .../catalog_service/transports/__init__.py | 33 - .../catalog_service/transports/base.py | 293 - .../catalog_service/transports/grpc.py | 598 -- .../transports/grpc_asyncio.py | 597 -- .../services/completion_service/__init__.py | 22 - .../completion_service/async_client.py | 391 - .../services/completion_service/client.py | 592 -- .../completion_service/transports/__init__.py | 33 - .../completion_service/transports/base.py | 172 - .../completion_service/transports/grpc.py | 323 - .../transports/grpc_asyncio.py | 322 - .../services/control_service/__init__.py | 22 - .../services/control_service/async_client.py | 744 -- .../services/control_service/client.py | 952 --- .../services/control_service/pagers.py | 140 - .../control_service/transports/__init__.py | 33 - .../control_service/transports/base.py | 209 - .../control_service/transports/grpc.py | 380 - .../transports/grpc_asyncio.py | 379 - .../services/prediction_service/__init__.py | 22 - .../prediction_service/async_client.py | 279 - .../services/prediction_service/client.py | 479 -- .../prediction_service/transports/__init__.py | 33 - .../prediction_service/transports/base.py | 150 - .../prediction_service/transports/grpc.py | 262 - .../transports/grpc_asyncio.py | 261 - .../services/product_service/__init__.py | 22 - .../services/product_service/async_client.py | 1804 ----- .../services/product_service/client.py | 2007 ----- .../services/product_service/pagers.py | 140 - .../product_service/transports/__init__.py | 33 - .../product_service/transports/base.py | 323 - .../product_service/transports/grpc.py | 724 -- .../transports/grpc_asyncio.py | 723 -- .../services/search_service/__init__.py | 22 - .../services/search_service/async_client.py | 303 - .../services/search_service/client.py | 512 -- .../services/search_service/pagers.py | 139 - .../search_service/transports/__init__.py | 33 - .../search_service/transports/base.py | 150 - .../search_service/transports/grpc.py | 268 - .../search_service/transports/grpc_asyncio.py | 267 - .../serving_config_service/__init__.py | 22 - .../serving_config_service/async_client.py | 954 --- .../services/serving_config_service/client.py | 1162 --- .../services/serving_config_service/pagers.py | 140 - .../transports/__init__.py | 33 - .../serving_config_service/transports/base.py | 237 - .../serving_config_service/transports/grpc.py | 438 - .../transports/grpc_asyncio.py | 437 - .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 730 -- .../services/user_event_service/client.py | 929 --- .../user_event_service/transports/__init__.py | 33 - .../user_event_service/transports/base.py | 231 - .../user_event_service/transports/grpc.py | 415 - .../transports/grpc_asyncio.py | 414 - .../cloud/retail_v2alpha/types/__init__.py | 284 - .../cloud/retail_v2alpha/types/catalog.py | 528 -- .../retail_v2alpha/types/catalog_service.py | 453 -- .../cloud/retail_v2alpha/types/common.py | 1179 --- .../types/completion_service.py | 223 - .../cloud/retail_v2alpha/types/control.py | 123 - .../retail_v2alpha/types/control_service.py | 197 - .../retail_v2alpha/types/export_config.py | 134 - .../retail_v2alpha/types/import_config.py | 691 -- .../types/prediction_service.py | 263 - .../cloud/retail_v2alpha/types/product.py | 705 -- .../retail_v2alpha/types/product_service.py | 877 -- .../cloud/retail_v2alpha/types/promotion.py | 50 - .../retail_v2alpha/types/purge_config.py | 251 - .../retail_v2alpha/types/search_service.py | 1099 --- .../retail_v2alpha/types/serving_config.py | 309 - .../types/serving_config_service.py | 234 - .../cloud/retail_v2alpha/types/user_event.py | 507 -- .../types/user_event_service.py | 154 - owl-bot-staging/v2alpha/mypy.ini | 3 - owl-bot-staging/v2alpha/noxfile.py | 180 - ...log_service_add_catalog_attribute_async.py | 49 - ...alog_service_add_catalog_attribute_sync.py | 49 - ...log_service_get_attributes_config_async.py | 45 - ...alog_service_get_attributes_config_sync.py | 45 - ...log_service_get_completion_config_async.py | 45 - ...alog_service_get_completion_config_sync.py | 45 - ...atalog_service_get_default_branch_async.py | 44 - ...catalog_service_get_default_branch_sync.py | 44 - ...ted_catalog_service_list_catalogs_async.py | 46 - ...ated_catalog_service_list_catalogs_sync.py | 46 - ..._service_remove_catalog_attribute_async.py | 46 - ...g_service_remove_catalog_attribute_sync.py | 46 - ...service_replace_catalog_attribute_async.py | 49 - ..._service_replace_catalog_attribute_sync.py | 49 - ...atalog_service_set_default_branch_async.py | 42 - ...catalog_service_set_default_branch_sync.py | 42 - ..._service_update_attributes_config_async.py | 48 - ...g_service_update_attributes_config_sync.py | 48 - ...ed_catalog_service_update_catalog_async.py | 49 - ...ted_catalog_service_update_catalog_sync.py | 49 - ..._service_update_completion_config_async.py | 48 - ...g_service_update_completion_config_sync.py | 48 - ...completion_service_complete_query_async.py | 46 - ..._completion_service_complete_query_sync.py | 46 - ...on_service_import_completion_data_async.py | 54 - ...ion_service_import_completion_data_sync.py | 54 - ...ed_control_service_create_control_async.py | 53 - ...ted_control_service_create_control_sync.py | 53 - ...ed_control_service_delete_control_async.py | 43 - ...ted_control_service_delete_control_sync.py | 43 - ...rated_control_service_get_control_async.py | 45 - ...erated_control_service_get_control_sync.py | 45 - ...ted_control_service_list_controls_async.py | 46 - ...ated_control_service_list_controls_sync.py | 46 - ...ed_control_service_update_control_async.py | 51 - ...ted_control_service_update_control_sync.py | 51 - ...erated_prediction_service_predict_async.py | 50 - ...nerated_prediction_service_predict_sync.py | 50 - ...ct_service_add_fulfillment_places_async.py | 51 - ...uct_service_add_fulfillment_places_sync.py | 51 - ...uct_service_add_local_inventories_async.py | 49 - ...duct_service_add_local_inventories_sync.py | 49 - ...ed_product_service_create_product_async.py | 50 - ...ted_product_service_create_product_sync.py | 50 - ...ed_product_service_delete_product_async.py | 43 - ...ted_product_service_delete_product_sync.py | 43 - ...rated_product_service_get_product_async.py | 45 - ...erated_product_service_get_product_sync.py | 45 - ...d_product_service_import_products_async.py | 53 - ...ed_product_service_import_products_sync.py | 53 - ...ted_product_service_list_products_async.py | 46 - ...ated_product_service_list_products_sync.py | 46 - ...ed_product_service_purge_products_async.py | 50 - ...ted_product_service_purge_products_sync.py | 50 - ...service_remove_fulfillment_places_async.py | 51 - ..._service_remove_fulfillment_places_sync.py | 51 - ..._service_remove_local_inventories_async.py | 50 - ...t_service_remove_local_inventories_sync.py | 50 - ...ted_product_service_set_inventory_async.py | 52 - ...ated_product_service_set_inventory_sync.py | 52 - ...ed_product_service_update_product_async.py | 48 - ...ted_product_service_update_product_sync.py | 48 - ...a_generated_search_service_search_async.py | 47 - ...ha_generated_search_service_search_sync.py | 47 - ...erving_config_service_add_control_async.py | 46 - ...serving_config_service_add_control_sync.py | 46 - ...fig_service_create_serving_config_async.py | 51 - ...nfig_service_create_serving_config_sync.py | 51 - ...fig_service_delete_serving_config_async.py | 43 - ...nfig_service_delete_serving_config_sync.py | 43 - ...config_service_get_serving_config_async.py | 45 - ..._config_service_get_serving_config_sync.py | 45 - ...nfig_service_list_serving_configs_async.py | 46 - ...onfig_service_list_serving_configs_sync.py | 46 - ...ing_config_service_remove_control_async.py | 46 - ...ving_config_service_remove_control_sync.py | 46 - ...fig_service_update_serving_config_async.py | 49 - ...nfig_service_update_serving_config_sync.py | 49 - ..._event_service_collect_user_event_async.py | 46 - ...r_event_service_collect_user_event_sync.py | 46 - ..._event_service_import_user_events_async.py | 54 - ...r_event_service_import_user_events_sync.py | 54 - ...r_event_service_purge_user_events_async.py | 50 - ...er_event_service_purge_user_events_sync.py | 50 - ..._event_service_rejoin_user_events_async.py | 49 - ...r_event_service_rejoin_user_events_sync.py | 49 - ...er_event_service_write_user_event_async.py | 50 - ...ser_event_service_write_user_event_sync.py | 50 - .../snippet_metadata_retail_v2alpha.json | 7066 ----------------- .../scripts/fixup_retail_v2alpha_keywords.py | 219 - owl-bot-staging/v2alpha/setup.py | 59 - owl-bot-staging/v2alpha/tests/__init__.py | 16 - .../v2alpha/tests/unit/__init__.py | 16 - .../v2alpha/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/retail_v2alpha/__init__.py | 16 - .../retail_v2alpha/test_catalog_service.py | 3793 --------- .../retail_v2alpha/test_completion_service.py | 1451 ---- .../retail_v2alpha/test_control_service.py | 2566 ------ .../retail_v2alpha/test_prediction_service.py | 1279 --- .../retail_v2alpha/test_product_service.py | 4237 ---------- .../retail_v2alpha/test_search_service.py | 1496 ---- .../test_serving_config_service.py | 3279 -------- .../retail_v2alpha/test_user_event_service.py | 1988 ----- owl-bot-staging/v2beta/.coveragerc | 17 - owl-bot-staging/v2beta/.flake8 | 33 - owl-bot-staging/v2beta/MANIFEST.in | 2 - owl-bot-staging/v2beta/README.rst | 49 - owl-bot-staging/v2beta/docs/conf.py | 376 - owl-bot-staging/v2beta/docs/index.rst | 7 - .../docs/retail_v2beta/catalog_service.rst | 10 - .../docs/retail_v2beta/completion_service.rst | 6 - .../docs/retail_v2beta/control_service.rst | 10 - .../docs/retail_v2beta/prediction_service.rst | 6 - .../docs/retail_v2beta/product_service.rst | 10 - .../docs/retail_v2beta/search_service.rst | 10 - .../v2beta/docs/retail_v2beta/services.rst | 13 - .../retail_v2beta/serving_config_service.rst | 10 - .../v2beta/docs/retail_v2beta/types.rst | 7 - .../docs/retail_v2beta/user_event_service.rst | 6 - .../v2beta/google/cloud/retail/__init__.py | 275 - .../v2beta/google/cloud/retail/py.typed | 2 - .../google/cloud/retail_v2beta/__init__.py | 276 - .../cloud/retail_v2beta/gapic_metadata.json | 551 -- .../google/cloud/retail_v2beta/py.typed | 2 - .../cloud/retail_v2beta/services/__init__.py | 15 - .../services/catalog_service/__init__.py | 22 - .../services/catalog_service/async_client.py | 1350 ---- .../services/catalog_service/client.py | 1579 ---- .../services/catalog_service/pagers.py | 140 - .../catalog_service/transports/__init__.py | 33 - .../catalog_service/transports/base.py | 293 - .../catalog_service/transports/grpc.py | 598 -- .../transports/grpc_asyncio.py | 597 -- .../services/completion_service/__init__.py | 22 - .../completion_service/async_client.py | 391 - .../services/completion_service/client.py | 592 -- .../completion_service/transports/__init__.py | 33 - .../completion_service/transports/base.py | 172 - .../completion_service/transports/grpc.py | 323 - .../transports/grpc_asyncio.py | 322 - .../services/control_service/__init__.py | 22 - .../services/control_service/async_client.py | 742 -- .../services/control_service/client.py | 950 --- .../services/control_service/pagers.py | 140 - .../control_service/transports/__init__.py | 33 - .../control_service/transports/base.py | 209 - .../control_service/transports/grpc.py | 380 - .../transports/grpc_asyncio.py | 379 - .../services/prediction_service/__init__.py | 22 - .../prediction_service/async_client.py | 279 - .../services/prediction_service/client.py | 479 -- .../prediction_service/transports/__init__.py | 33 - .../prediction_service/transports/base.py | 150 - .../prediction_service/transports/grpc.py | 262 - .../transports/grpc_asyncio.py | 261 - .../services/product_service/__init__.py | 22 - .../services/product_service/async_client.py | 1692 ---- .../services/product_service/client.py | 1894 ----- .../services/product_service/pagers.py | 140 - .../product_service/transports/__init__.py | 33 - .../product_service/transports/base.py | 308 - .../product_service/transports/grpc.py | 678 -- .../transports/grpc_asyncio.py | 677 -- .../services/search_service/__init__.py | 22 - .../services/search_service/async_client.py | 303 - .../services/search_service/client.py | 512 -- .../services/search_service/pagers.py | 139 - .../search_service/transports/__init__.py | 33 - .../search_service/transports/base.py | 150 - .../search_service/transports/grpc.py | 268 - .../search_service/transports/grpc_asyncio.py | 267 - .../serving_config_service/__init__.py | 22 - .../serving_config_service/async_client.py | 954 --- .../services/serving_config_service/client.py | 1162 --- .../services/serving_config_service/pagers.py | 140 - .../transports/__init__.py | 33 - .../serving_config_service/transports/base.py | 237 - .../serving_config_service/transports/grpc.py | 438 - .../transports/grpc_asyncio.py | 437 - .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 730 -- .../services/user_event_service/client.py | 929 --- .../user_event_service/transports/__init__.py | 33 - .../user_event_service/transports/base.py | 231 - .../user_event_service/transports/grpc.py | 415 - .../transports/grpc_asyncio.py | 414 - .../cloud/retail_v2beta/types/__init__.py | 278 - .../cloud/retail_v2beta/types/catalog.py | 528 -- .../retail_v2beta/types/catalog_service.py | 453 -- .../cloud/retail_v2beta/types/common.py | 1178 --- .../retail_v2beta/types/completion_service.py | 223 - .../cloud/retail_v2beta/types/control.py | 112 - .../retail_v2beta/types/control_service.py | 197 - .../retail_v2beta/types/export_config.py | 134 - .../retail_v2beta/types/import_config.py | 691 -- .../retail_v2beta/types/prediction_service.py | 263 - .../cloud/retail_v2beta/types/product.py | 705 -- .../retail_v2beta/types/product_service.py | 844 -- .../cloud/retail_v2beta/types/promotion.py | 50 - .../cloud/retail_v2beta/types/purge_config.py | 107 - .../retail_v2beta/types/search_service.py | 1074 --- .../retail_v2beta/types/serving_config.py | 309 - .../types/serving_config_service.py | 234 - .../cloud/retail_v2beta/types/user_event.py | 507 -- .../retail_v2beta/types/user_event_service.py | 154 - owl-bot-staging/v2beta/mypy.ini | 3 - owl-bot-staging/v2beta/noxfile.py | 180 - ...log_service_add_catalog_attribute_async.py | 49 - ...alog_service_add_catalog_attribute_sync.py | 49 - ...log_service_get_attributes_config_async.py | 45 - ...alog_service_get_attributes_config_sync.py | 45 - ...log_service_get_completion_config_async.py | 45 - ...alog_service_get_completion_config_sync.py | 45 - ...atalog_service_get_default_branch_async.py | 44 - ...catalog_service_get_default_branch_sync.py | 44 - ...ted_catalog_service_list_catalogs_async.py | 46 - ...ated_catalog_service_list_catalogs_sync.py | 46 - ..._service_remove_catalog_attribute_async.py | 46 - ...g_service_remove_catalog_attribute_sync.py | 46 - ...service_replace_catalog_attribute_async.py | 49 - ..._service_replace_catalog_attribute_sync.py | 49 - ...atalog_service_set_default_branch_async.py | 42 - ...catalog_service_set_default_branch_sync.py | 42 - ..._service_update_attributes_config_async.py | 48 - ...g_service_update_attributes_config_sync.py | 48 - ...ed_catalog_service_update_catalog_async.py | 49 - ...ted_catalog_service_update_catalog_sync.py | 49 - ..._service_update_completion_config_async.py | 48 - ...g_service_update_completion_config_sync.py | 48 - ...completion_service_complete_query_async.py | 46 - ..._completion_service_complete_query_sync.py | 46 - ...on_service_import_completion_data_async.py | 54 - ...ion_service_import_completion_data_sync.py | 54 - ...ed_control_service_create_control_async.py | 52 - ...ted_control_service_create_control_sync.py | 52 - ...ed_control_service_delete_control_async.py | 43 - ...ted_control_service_delete_control_sync.py | 43 - ...rated_control_service_get_control_async.py | 45 - ...erated_control_service_get_control_sync.py | 45 - ...ted_control_service_list_controls_async.py | 46 - ...ated_control_service_list_controls_sync.py | 46 - ...ed_control_service_update_control_async.py | 50 - ...ted_control_service_update_control_sync.py | 50 - ...erated_prediction_service_predict_async.py | 50 - ...nerated_prediction_service_predict_sync.py | 50 - ...ct_service_add_fulfillment_places_async.py | 51 - ...uct_service_add_fulfillment_places_sync.py | 51 - ...uct_service_add_local_inventories_async.py | 49 - ...duct_service_add_local_inventories_sync.py | 49 - ...ed_product_service_create_product_async.py | 50 - ...ted_product_service_create_product_sync.py | 50 - ...ed_product_service_delete_product_async.py | 43 - ...ted_product_service_delete_product_sync.py | 43 - ...rated_product_service_get_product_async.py | 45 - ...erated_product_service_get_product_sync.py | 45 - ...d_product_service_import_products_async.py | 53 - ...ed_product_service_import_products_sync.py | 53 - ...ted_product_service_list_products_async.py | 46 - ...ated_product_service_list_products_sync.py | 46 - ...service_remove_fulfillment_places_async.py | 51 - ..._service_remove_fulfillment_places_sync.py | 51 - ..._service_remove_local_inventories_async.py | 50 - ...t_service_remove_local_inventories_sync.py | 50 - ...ted_product_service_set_inventory_async.py | 52 - ...ated_product_service_set_inventory_sync.py | 52 - ...ed_product_service_update_product_async.py | 48 - ...ted_product_service_update_product_sync.py | 48 - ...a_generated_search_service_search_async.py | 47 - ...ta_generated_search_service_search_sync.py | 47 - ...erving_config_service_add_control_async.py | 46 - ...serving_config_service_add_control_sync.py | 46 - ...fig_service_create_serving_config_async.py | 51 - ...nfig_service_create_serving_config_sync.py | 51 - ...fig_service_delete_serving_config_async.py | 43 - ...nfig_service_delete_serving_config_sync.py | 43 - ...config_service_get_serving_config_async.py | 45 - ..._config_service_get_serving_config_sync.py | 45 - ...nfig_service_list_serving_configs_async.py | 46 - ...onfig_service_list_serving_configs_sync.py | 46 - ...ing_config_service_remove_control_async.py | 46 - ...ving_config_service_remove_control_sync.py | 46 - ...fig_service_update_serving_config_async.py | 49 - ...nfig_service_update_serving_config_sync.py | 49 - ..._event_service_collect_user_event_async.py | 46 - ...r_event_service_collect_user_event_sync.py | 46 - ..._event_service_import_user_events_async.py | 54 - ...r_event_service_import_user_events_sync.py | 54 - ...r_event_service_purge_user_events_async.py | 50 - ...er_event_service_purge_user_events_sync.py | 50 - ..._event_service_rejoin_user_events_async.py | 49 - ...r_event_service_rejoin_user_events_sync.py | 49 - ...er_event_service_write_user_event_async.py | 50 - ...ser_event_service_write_user_event_sync.py | 50 - .../snippet_metadata_retail_v2beta.json | 6913 ---------------- .../scripts/fixup_retail_v2beta_keywords.py | 218 - owl-bot-staging/v2beta/setup.py | 59 - owl-bot-staging/v2beta/tests/__init__.py | 16 - owl-bot-staging/v2beta/tests/unit/__init__.py | 16 - .../v2beta/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/retail_v2beta/__init__.py | 16 - .../retail_v2beta/test_catalog_service.py | 3793 --------- .../retail_v2beta/test_completion_service.py | 1451 ---- .../retail_v2beta/test_control_service.py | 2554 ------ .../retail_v2beta/test_prediction_service.py | 1279 --- .../retail_v2beta/test_product_service.py | 4085 ---------- .../retail_v2beta/test_search_service.py | 1496 ---- .../test_serving_config_service.py | 3279 -------- .../retail_v2beta/test_user_event_service.py | 1988 ----- scripts/fixup_retail_v2_keywords.py | 2 +- 568 files changed, 271 insertions(+), 174295 deletions(-) delete mode 100644 owl-bot-staging/v2/.coveragerc delete mode 100644 owl-bot-staging/v2/.flake8 delete mode 100644 owl-bot-staging/v2/MANIFEST.in delete mode 100644 owl-bot-staging/v2/README.rst delete mode 100644 owl-bot-staging/v2/docs/conf.py delete mode 100644 owl-bot-staging/v2/docs/index.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/catalog_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/completion_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/prediction_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/product_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/search_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/services.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/types.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/user_event_service.rst delete mode 100644 owl-bot-staging/v2/google/cloud/retail/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/common.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/product.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py delete mode 100644 owl-bot-staging/v2/mypy.ini delete mode 100644 owl-bot-staging/v2/noxfile.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json delete mode 100644 owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py delete mode 100644 owl-bot-staging/v2/setup.py delete mode 100644 owl-bot-staging/v2/tests/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py delete mode 100644 owl-bot-staging/v2alpha/.coveragerc delete mode 100644 owl-bot-staging/v2alpha/.flake8 delete mode 100644 owl-bot-staging/v2alpha/MANIFEST.in delete mode 100644 owl-bot-staging/v2alpha/README.rst delete mode 100644 owl-bot-staging/v2alpha/docs/conf.py delete mode 100644 owl-bot-staging/v2alpha/docs/index.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail/py.typed delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py delete mode 100644 owl-bot-staging/v2alpha/mypy.ini delete mode 100644 owl-bot-staging/v2alpha/noxfile.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json delete mode 100644 owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py delete mode 100644 owl-bot-staging/v2alpha/setup.py delete mode 100644 owl-bot-staging/v2alpha/tests/__init__.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py delete mode 100644 owl-bot-staging/v2beta/.coveragerc delete mode 100644 owl-bot-staging/v2beta/.flake8 delete mode 100644 owl-bot-staging/v2beta/MANIFEST.in delete mode 100644 owl-bot-staging/v2beta/README.rst delete mode 100644 owl-bot-staging/v2beta/docs/conf.py delete mode 100644 owl-bot-staging/v2beta/docs/index.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/services.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/types.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail/py.typed delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py delete mode 100644 owl-bot-staging/v2beta/mypy.ini delete mode 100644 owl-bot-staging/v2beta/noxfile.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json delete mode 100644 owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py delete mode 100644 owl-bot-staging/v2beta/setup.py delete mode 100644 owl-bot-staging/v2beta/tests/__init__.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py diff --git a/google/cloud/retail_v2/services/product_service/async_client.py b/google/cloud/retail_v2/services/product_service/async_client.py index bd747a5d..45921dfb 100644 --- a/google/cloud/retail_v2/services/product_service/async_client.py +++ b/google/cloud/retail_v2/services/product_service/async_client.py @@ -641,6 +641,11 @@ async def sample_update_product(): If an unsupported or unknown field is provided, an INVALID_ARGUMENT error is returned. + The attribute key can be updated by setting the mask + path as "attributes.${key_name}". If a key name is + present in the mask but not in the patching product from + the request, this key will be deleted after the update. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -820,8 +825,8 @@ async def import_products( r"""Bulk import of multiple [Product][google.cloud.retail.v2.Product]s. - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. + Request processing may be synchronous. Non-existing items are + created. Note that it is possible for a subset of the [Product][google.cloud.retail.v2.Product]s to be successfully @@ -970,7 +975,7 @@ async def set_inventory( Pre-existing inventory information can only be updated with [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], and [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. @@ -1211,7 +1216,8 @@ async def sample_add_fulfillment_places(): Args: request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): The request object. Request message for - [AddFulfillmentPlaces][] method. + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. product (:class:`str`): Required. Full resource name of [Product][google.cloud.retail.v2.Product], such as @@ -1237,7 +1243,8 @@ async def sample_add_fulfillment_places(): The result type for the operation will be :class:`google.cloud.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. """ # Create or coerce a protobuf request object. @@ -1486,7 +1493,8 @@ async def sample_add_local_inventories(): Args: request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): The request object. Request message for - [AddLocalInventories][] method. + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. product (:class:`str`): Required. Full resource name of [Product][google.cloud.retail.v2.Product], such as @@ -1510,9 +1518,12 @@ async def sample_add_local_inventories(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.retail_v2.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. + The result type for the operation will be :class:`google.cloud.retail_v2.types.AddLocalInventoriesResponse` Response of the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + API. Currently empty because there is no meaningful + response populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. """ # Create or coerce a protobuf request object. diff --git a/google/cloud/retail_v2/services/product_service/client.py b/google/cloud/retail_v2/services/product_service/client.py index 281bcbc5..49bce788 100644 --- a/google/cloud/retail_v2/services/product_service/client.py +++ b/google/cloud/retail_v2/services/product_service/client.py @@ -891,6 +891,11 @@ def sample_update_product(): If an unsupported or unknown field is provided, an INVALID_ARGUMENT error is returned. + The attribute key can be updated by setting the mask + path as "attributes.${key_name}". If a key name is + present in the mask but not in the patching product from + the request, this key will be deleted after the update. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1070,8 +1075,8 @@ def import_products( r"""Bulk import of multiple [Product][google.cloud.retail.v2.Product]s. - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. + Request processing may be synchronous. Non-existing items are + created. Note that it is possible for a subset of the [Product][google.cloud.retail.v2.Product]s to be successfully @@ -1211,7 +1216,7 @@ def set_inventory( Pre-existing inventory information can only be updated with [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], and [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. @@ -1452,7 +1457,8 @@ def sample_add_fulfillment_places(): Args: request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): The request object. Request message for - [AddFulfillmentPlaces][] method. + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. product (str): Required. Full resource name of [Product][google.cloud.retail.v2.Product], such as @@ -1478,7 +1484,8 @@ def sample_add_fulfillment_places(): The result type for the operation will be :class:`google.cloud.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. """ # Create or coerce a protobuf request object. @@ -1729,7 +1736,8 @@ def sample_add_local_inventories(): Args: request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): The request object. Request message for - [AddLocalInventories][] method. + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. product (str): Required. Full resource name of [Product][google.cloud.retail.v2.Product], such as @@ -1753,9 +1761,12 @@ def sample_add_local_inventories(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.retail_v2.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. + The result type for the operation will be :class:`google.cloud.retail_v2.types.AddLocalInventoriesResponse` Response of the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + API. Currently empty because there is no meaningful + response populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. """ # Create or coerce a protobuf request object. diff --git a/google/cloud/retail_v2/services/product_service/transports/grpc.py b/google/cloud/retail_v2/services/product_service/transports/grpc.py index 42dfc211..18a1234c 100644 --- a/google/cloud/retail_v2/services/product_service/transports/grpc.py +++ b/google/cloud/retail_v2/services/product_service/transports/grpc.py @@ -388,8 +388,8 @@ def import_products( Bulk import of multiple [Product][google.cloud.retail.v2.Product]s. - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. + Request processing may be synchronous. Non-existing items are + created. Note that it is possible for a subset of the [Product][google.cloud.retail.v2.Product]s to be successfully @@ -458,7 +458,7 @@ def set_inventory( Pre-existing inventory information can only be updated with [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], and [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. diff --git a/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py b/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py index 105eb745..1c9546ca 100644 --- a/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py @@ -400,8 +400,8 @@ def import_products( Bulk import of multiple [Product][google.cloud.retail.v2.Product]s. - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. + Request processing may be synchronous. Non-existing items are + created. Note that it is possible for a subset of the [Product][google.cloud.retail.v2.Product]s to be successfully @@ -472,7 +472,7 @@ def set_inventory( Pre-existing inventory information can only be updated with [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], and [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. diff --git a/google/cloud/retail_v2/types/catalog.py b/google/cloud/retail_v2/types/catalog.py index e435a0db..afa707a2 100644 --- a/google/cloud/retail_v2/types/catalog.py +++ b/google/cloud/retail_v2/types/catalog.py @@ -42,7 +42,8 @@ class ProductLevelConfig(proto.Message): default to [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] if unset. - - ``variant``: You can only ingest + - ``variant`` (incompatible with Retail Search): You can + only ingest [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] [Product][google.cloud.retail.v2.Product]s. This means [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] @@ -55,8 +56,8 @@ class ProductLevelConfig(proto.Message): [merchant_center_product_id_field][google.cloud.retail.v2.ProductLevelConfig.merchant_center_product_id_field] is ``itemGroupId``, an INVALID_ARGUMENT error is returned. - See `Using product - levels `__ + See `Product + levels `__ for more details. merchant_center_product_id_field (str): Which field of `Merchant Center @@ -79,8 +80,8 @@ class ProductLevelConfig(proto.Message): [ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] is ``variant``, an INVALID_ARGUMENT error is returned. - See `Using product - levels `__ + See `Product + levels `__ for more details. """ diff --git a/google/cloud/retail_v2/types/common.py b/google/cloud/retail_v2/types/common.py index ff0f4fb0..a2edc865 100644 --- a/google/cloud/retail_v2/types/common.py +++ b/google/cloud/retail_v2/types/common.py @@ -153,11 +153,15 @@ class CustomAttribute(proto.Message): should be set. Otherwise, an INVALID_ARGUMENT error is returned. searchable (bool): - This field will only be used when + This field is normally ignored unless [AttributesConfig.attribute_config_level][] of the - [Catalog][google.cloud.retail.v2.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are searchable by text queries in + [Catalog][google.cloud.retail.v2.Catalog] is set to the + deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For + information about product-level attribute configuration, see + `Configuration + modes `__. + If true, custom attribute values are searchable by text + queries in [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. This field is ignored in a @@ -169,12 +173,15 @@ class CustomAttribute(proto.Message): This field is a member of `oneof`_ ``_searchable``. indexable (bool): - This field will only be used when + This field is normally ignored unless [AttributesConfig.attribute_config_level][] of the - [Catalog][google.cloud.retail.v2.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are indexed, so that it can be filtered, faceted or - boosted in + [Catalog][google.cloud.retail.v2.Catalog] is set to the + deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For + information about product-level attribute configuration, see + `Configuration + modes `__. + If true, custom attribute values are indexed, so that they + can be filtered, faceted or boosted in [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. This field is ignored in a @@ -384,7 +391,11 @@ class PriceInfo(proto.Message): original_price (float): Price of the product without any discount. If zero, by default set to be the - [price][google.cloud.retail.v2.PriceInfo.price]. + [price][google.cloud.retail.v2.PriceInfo.price]. If set, + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + should be greater than or equal to + [price][google.cloud.retail.v2.PriceInfo.price], otherwise + an INVALID_ARGUMENT error is thrown. cost (float): The costs associated with the sale of a particular product. Used for gross profit reporting. @@ -561,10 +572,15 @@ class UserInfo(proto.Message): Attributes: user_id (str): Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. + for logged-in user, such as a user name. Don't set for + anonymous users. Always use a hashed value for this ID. + Don't set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + The field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. diff --git a/google/cloud/retail_v2/types/completion_service.py b/google/cloud/retail_v2/types/completion_service.py index 1381a017..d8b9c951 100644 --- a/google/cloud/retail_v2/types/completion_service.py +++ b/google/cloud/retail_v2/types/completion_service.py @@ -86,9 +86,9 @@ class CompleteQueryRequest(proto.Message): - user-data - - cloud-retail This option requires additional - allowlisting. Before using cloud-retail, contact Cloud - Retail support team first. + - cloud-retail: This option requires enabling auto-learning + function first. See + `guidelines `__. max_suggestions (int): Completion max suggestions. If left unset or set to 0, then will fallback to the configured value @@ -154,10 +154,13 @@ class CompleteQueryResponse(proto.Message): The recent searches satisfy the follow rules: - They are ordered from latest to oldest. + - They are matched with [CompleteQueryRequest.query][google.cloud.retail.v2.CompleteQueryRequest.query] case insensitively. + - They are transformed to lower cases. + - They are UTF-8 safe. Recent searches are deduplicated. More recent searches will @@ -175,8 +178,11 @@ class CompletionResult(proto.Message): - For "user-data", the attributes are additional custom attributes ingested through BigQuery. + - For "cloud-retail", the attributes are product attributes - generated by Cloud Retail. + generated by Cloud Retail. This is an experimental + feature. Contact Retail Search support team if you are + interested in enabling it. """ suggestion = proto.Field( diff --git a/google/cloud/retail_v2/types/import_config.py b/google/cloud/retail_v2/types/import_config.py index 576e7524..a3990c66 100644 --- a/google/cloud/retail_v2/types/import_config.py +++ b/google/cloud/retail_v2/types/import_config.py @@ -278,12 +278,22 @@ class ImportProductsRequest(proto.Message): products to be imported. Defaults to [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. + Full Pub/Sub topic name for receiving notification. If this + field is set, when the import is finished, a notification + will be sent to specified Pub/Sub topic. The message data + will be JSON string of a + [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. + ``projects/{project}/topics/{topic}``. It has to be within + the same project as + [ImportProductsRequest.parent][google.cloud.retail.v2.ImportProductsRequest.parent]. + Make sure that both + ``cloud-retail-customer-data-access@system.gserviceaccount.com`` + and + ``service-@gcp-sa-retail.iam.gserviceaccount.com`` + have the ``pubsub.topics.publish`` IAM permission on the + topic. Only supported when [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] diff --git a/google/cloud/retail_v2/types/prediction_service.py b/google/cloud/retail_v2/types/prediction_service.py index 191780e3..403ebe0e 100644 --- a/google/cloud/retail_v2/types/prediction_service.py +++ b/google/cloud/retail_v2/types/prediction_service.py @@ -43,12 +43,24 @@ class PredictRequest(proto.Message): The full list of available placements can be seen at https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements user_event (google.cloud.retail_v2.types.UserEvent): - Required. Context about the user, what they - are looking at and what action they took to - trigger the predict request. Note that this user - event detail won't be ingested to userEvent - logs. Thus, a separate userEvent write request - is required for event logging. + Required. Context about the user, what they are looking at + and what action they took to trigger the predict request. + Note that this user event detail won't be ingested to + userEvent logs. Thus, a separate userEvent write request is + required for event logging. + + Don't set + [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] + or + [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] + to the same fixed ID for different users. If you are trying + to receive non-personalized recommendations (not + recommended; this can negatively impact model performance), + instead set + [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] + to a random unique ID and leave + [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] + unset. page_size (int): Maximum number of results to return per page. Set this property to the number of prediction @@ -134,8 +146,8 @@ class PredictRequest(proto.Message): of 64. - Each label must be a key-value pair. - Keys have a minimum length of 1 character and a maximum - length of 63 characters, and cannot be empty. Values can - be empty, and have a maximum length of 63 characters. + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. - Keys and values can contain only lowercase letters, numeric characters, underscores, and dashes. All characters must use UTF-8 encoding, and international @@ -221,11 +233,11 @@ class PredictionResult(proto.Message): Possible values: - - ``product``: JSON representation of the product. Will be - set if ``returnProduct`` is set to true in + - ``product``: JSON representation of the product. Is set + if ``returnProduct`` is set to true in ``PredictRequest.params``. - - ``score``: Prediction score in double value. Will be set - if ``returnScore`` is set to true in + - ``score``: Prediction score in double value. Is set if + ``returnScore`` is set to true in ``PredictRequest.params``. """ diff --git a/google/cloud/retail_v2/types/product.py b/google/cloud/retail_v2/types/product.py index 9e32ebd5..f7b2474a 100644 --- a/google/cloud/retail_v2/types/product.py +++ b/google/cloud/retail_v2/types/product.py @@ -506,11 +506,11 @@ class Product(proto.Message): - [name][google.cloud.retail.v2.Product.name] - [color_info][google.cloud.retail.v2.Product.color_info] - Maximum number of paths is 30. Otherwise, an + The maximum number of paths is 30. Otherwise, an INVALID_ARGUMENT error is returned. Note: Returning more fields in - [SearchResponse][google.cloud.retail.v2.SearchResponse] may + [SearchResponse][google.cloud.retail.v2.SearchResponse] can increase response payload size and serving latency. variants (Sequence[google.cloud.retail_v2.types.Product]): Output only. Product variants grouped together on primary diff --git a/google/cloud/retail_v2/types/product_service.py b/google/cloud/retail_v2/types/product_service.py index d47f1997..587e5e8b 100644 --- a/google/cloud/retail_v2/types/product_service.py +++ b/google/cloud/retail_v2/types/product_service.py @@ -143,6 +143,11 @@ class UpdateProductRequest(proto.Message): If an unsupported or unknown field is provided, an INVALID_ARGUMENT error is returned. + + The attribute key can be updated by setting the mask path as + "attributes.${key_name}". If a key name is present in the + mask but not in the patching product from the request, this + key will be deleted after the update. allow_missing (bool): If set to true, and the [Product][google.cloud.retail.v2.Product] is not found, a @@ -471,7 +476,9 @@ class SetInventoryResponse(proto.Message): class AddFulfillmentPlacesRequest(proto.Message): - r"""Request message for [AddFulfillmentPlaces][] method. + r"""Request message for + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. Attributes: product (str): @@ -563,7 +570,9 @@ class AddFulfillmentPlacesRequest(proto.Message): class AddFulfillmentPlacesMetadata(proto.Message): r"""Metadata related to the progress of the AddFulfillmentPlaces operation. Currently empty because there is no meaningful metadata - populated from the [AddFulfillmentPlaces][] method. + populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. """ @@ -571,13 +580,16 @@ class AddFulfillmentPlacesMetadata(proto.Message): class AddFulfillmentPlacesResponse(proto.Message): r"""Response of the AddFulfillmentPlacesRequest. Currently empty because there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. """ class AddLocalInventoriesRequest(proto.Message): - r"""Request message for [AddLocalInventories][] method. + r"""Request message for + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. Attributes: product (str): @@ -656,15 +668,20 @@ class AddLocalInventoriesRequest(proto.Message): class AddLocalInventoriesMetadata(proto.Message): r"""Metadata related to the progress of the AddLocalInventories operation. Currently empty because there is no meaningful metadata - populated from the [AddLocalInventories][] method. + populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. """ class AddLocalInventoriesResponse(proto.Message): - r"""Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. + r"""Response of the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + API. Currently empty because there is no meaningful response + populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. """ @@ -770,7 +787,7 @@ class RemoveFulfillmentPlacesRequest(proto.Message): an INVALID_ARGUMENT error is returned. This field directly corresponds to - [Product.fulfillment_info.type][]. + [Product.fulfillment_info.type][google.cloud.retail.v2.FulfillmentInfo.type]. place_ids (Sequence[str]): Required. The IDs for this [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type], diff --git a/google/cloud/retail_v2/types/search_service.py b/google/cloud/retail_v2/types/search_service.py index e7e767d3..e1d560a8 100644 --- a/google/cloud/retail_v2/types/search_service.py +++ b/google/cloud/retail_v2/types/search_service.py @@ -38,7 +38,7 @@ class SearchRequest(proto.Message): placement (str): Required. The resource name of the search engine placement, such as - ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` + ``projects/*/locations/global/catalogs/default_catalog/placements/default_search``. This field is used to identify the serving configuration name and the set of models that will be used to make the search. @@ -50,6 +50,11 @@ class SearchRequest(proto.Message): empty, to search products under the default branch. query (str): Raw search query. + + If this field is empty, the request is considered a category + browsing request and returned results are based on + [filter][google.cloud.retail.v2.SearchRequest.filter] and + [page_categories][google.cloud.retail.v2.SearchRequest.page_categories]. visitor_id (str): Required. A unique identifier for tracking visitors. For example, this could be implemented with an HTTP cookie, @@ -147,11 +152,11 @@ class SearchRequest(proto.Message): guide `__. Notice that if both [ServingConfig.boost_control_ids][] and - [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. + [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] + are set, the boost conditions from both places are + evaluated. If a search request matches multiple boost + conditions, the final boost score is equal to the sum of the + boost scores from all matched boost conditions. query_expansion_spec (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec): The query expansion specification that specifies the conditions under which query expansion will occur. See more @@ -187,7 +192,9 @@ class SearchRequest(proto.Message): - inventory(place_id,price) - inventory(place_id,original_price) - inventory(place_id,attributes.key), where key is any key - in the [Product.inventories.attributes][] map. + in the + [Product.local_inventories.attributes][google.cloud.retail.v2.LocalInventory.attributes] + map. - attributes.key, where key is any key in the [Product.attributes][google.cloud.retail.v2.Product.attributes] map. @@ -259,6 +266,34 @@ class SearchRequest(proto.Message): product search and faceted search. personalization_spec (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec): The specification for personalization. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + spell_correction_spec (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec): + The spell correction specification that + specifies the mode under which spell correction + will take effect. + + This field is a member of `oneof`_ ``_spell_correction_spec``. """ class SearchMode(proto.Enum): @@ -287,17 +322,28 @@ class FacetSpec(proto.Message): is not excluded from the filter unless it is listed in this field. - For example, suppose there are 100 products with color facet - "Red" and 200 products with color facet "Blue". A query - containing the filter "colorFamilies:ANY("Red")" and have - "colorFamilies" as - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - will by default return the "Red" with count 100. + Listing a facet key in this field allows its values to + appear as facet results, even when they are filtered out of + search results. Using this field does not affect what search + results are returned. - If this field contains "colorFamilies", then the query - returns both the "Red" with count 100 and "Blue" with count - 200, because the "colorFamilies" key is now excluded from - the filter. + For example, suppose there are 100 products with the color + facet "Red" and 200 products with the color facet "Blue". A + query containing the filter "colorFamilies:ANY("Red")" and + having "colorFamilies" as + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + would by default return only "Red" products in the search + results, and also return "Red" with count 100 as the only + color facet. Although there are also blue products + available, "Blue" would not be shown as an available facet + value. + + If "colorFamilies" is listed in "excludedFilterKeys", then + the query returns the facet values "Red" with count 100 and + "Blue" with count 200, because the "colorFamilies" key is + now excluded from the filter. Because this field doesn't + affect search results, the search results are still + correctly filtered to return only "Red" products. A maximum of 100 values are allowed. Otherwise, an INVALID_ARGUMENT error is returned. @@ -394,8 +440,9 @@ class FacetKey(proto.Message): Only get facet for the given restricted values. For example, when using "pickupInStore" as key and set restricted values to ["store123", "store456"], only facets for "store123" and - "store456" are returned. Only supported on textual fields - and fulfillments. Maximum is 20. + "store456" are returned. Only supported on predefined + textual fields, custom textual attributes and fulfillments. + Maximum is 20. Must be set for the fulfillment facet keys: @@ -557,7 +604,7 @@ class BoostSpec(proto.Message): specifictions, boost scores from these specifications are all applied and combined in a non-linear way. Maximum number of specifications - is 10. + is 20. skip_boost_spec_validation (bool): Whether to skip boostspec validation. If this field is set to true, invalid @@ -683,6 +730,30 @@ class Mode(proto.Enum): enum="SearchRequest.PersonalizationSpec.Mode", ) + class SpellCorrectionSpec(proto.Message): + r"""The specification for query spell correction. + + Attributes: + mode (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec.Mode): + The mode under which spell correction should take effect to + replace the original search query. Default to + [Mode.AUTO][google.cloud.retail.v2.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. + """ + + class Mode(proto.Enum): + r"""Enum describing under which mode spell correction should + occur. + """ + MODE_UNSPECIFIED = 0 + SUGGESTION_ONLY = 1 + AUTO = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum="SearchRequest.SpellCorrectionSpec.Mode", + ) + placement = proto.Field( proto.STRING, number=1, @@ -766,6 +837,17 @@ class Mode(proto.Enum): number=32, message=PersonalizationSpec, ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=34, + ) + spell_correction_spec = proto.Field( + proto.MESSAGE, + number=35, + optional=True, + message=SpellCorrectionSpec, + ) class SearchResponse(proto.Message): @@ -787,8 +869,10 @@ class SearchResponse(proto.Message): [total_size][google.cloud.retail.v2.SearchResponse.total_size] that matches. corrected_query (str): - If spell correction applies, the corrected - query. Otherwise, empty. + Contains the spell corrected query, if found. If the spell + correction type is AUTOMATIC, then the search results are + based on corrected_query. Otherwise the original query will + be used for search. attribution_token (str): A unique search token. This should be included in the [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting @@ -804,11 +888,11 @@ class SearchResponse(proto.Message): results. redirect_uri (str): The URI of a customer-defined redirect page. If redirect - action is triggered, no search will be performed, and only + action is triggered, no search is performed, and only [redirect_uri][google.cloud.retail.v2.SearchResponse.redirect_uri] and [attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] - will be set in the response. + are set in the response. applied_controls (Sequence[str]): The fully qualified resource name of applied `controls `__. diff --git a/google/cloud/retail_v2/types/user_event.py b/google/cloud/retail_v2/types/user_event.py index 9ae374eb..ceacbc41 100644 --- a/google/cloud/retail_v2/types/user_event.py +++ b/google/cloud/retail_v2/types/user_event.py @@ -59,12 +59,16 @@ class UserEvent(proto.Message): single device. This unique identifier should not change if the visitor log in/out of the website. + Don't set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + The field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. The field should not contain PII or user-data. We recommend - to use Google Analystics `Client + to use Google Analytics `Client ID `__ for this field. session_id (str): @@ -116,12 +120,11 @@ class UserEvent(proto.Message): product_details (Sequence[google.cloud.retail_v2.types.ProductDetail]): The main product details related to the event. - This field is required for the following event types: + This field is optional except for the following event types: - ``add-to-cart`` - ``detail-page-view`` - ``purchase-complete`` - - ``search`` In a ``search`` event, this field represents the products returned to the end user on the current page (the end user diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc deleted file mode 100644 index a8b114f0..00000000 --- a/owl-bot-staging/v2/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/retail/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2/.flake8 b/owl-bot-staging/v2/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v2/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in deleted file mode 100644 index 985b915c..00000000 --- a/owl-bot-staging/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/retail *.py -recursive-include google/cloud/retail_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst deleted file mode 100644 index cb039760..00000000 --- a/owl-bot-staging/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Retail API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Retail API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py deleted file mode 100644 index 5be9eb4b..00000000 --- a/owl-bot-staging/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-retail documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-retail" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-retail-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-retail.tex", - u"google-cloud-retail Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-retail", - u"Google Cloud Retail Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-retail", - u"google-cloud-retail Documentation", - author, - "google-cloud-retail", - "GAPIC library for Google Cloud Retail API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst deleted file mode 100644 index c70f61bc..00000000 --- a/owl-bot-staging/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - retail_v2/services - retail_v2/types diff --git a/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst b/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst deleted file mode 100644 index 5b7227d9..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CatalogService --------------------------------- - -.. automodule:: google.cloud.retail_v2.services.catalog_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2.services.catalog_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/completion_service.rst b/owl-bot-staging/v2/docs/retail_v2/completion_service.rst deleted file mode 100644 index 551f89ed..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/completion_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CompletionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2.services.completion_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst b/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst deleted file mode 100644 index 12ffb6ee..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -PredictionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2.services.prediction_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/product_service.rst b/owl-bot-staging/v2/docs/retail_v2/product_service.rst deleted file mode 100644 index 0b8fa911..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/product_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ProductService --------------------------------- - -.. automodule:: google.cloud.retail_v2.services.product_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2.services.product_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/search_service.rst b/owl-bot-staging/v2/docs/retail_v2/search_service.rst deleted file mode 100644 index af72819d..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SearchService -------------------------------- - -.. automodule:: google.cloud.retail_v2.services.search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2.services.search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/services.rst b/owl-bot-staging/v2/docs/retail_v2/services.rst deleted file mode 100644 index f86138d7..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/services.rst +++ /dev/null @@ -1,11 +0,0 @@ -Services for Google Cloud Retail v2 API -======================================= -.. toctree:: - :maxdepth: 2 - - catalog_service - completion_service - prediction_service - product_service - search_service - user_event_service diff --git a/owl-bot-staging/v2/docs/retail_v2/types.rst b/owl-bot-staging/v2/docs/retail_v2/types.rst deleted file mode 100644 index 54951beb..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Retail v2 API -==================================== - -.. automodule:: google.cloud.retail_v2.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst b/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst deleted file mode 100644 index 00e214a9..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.retail_v2.services.user_event_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/google/cloud/retail/__init__.py b/owl-bot-staging/v2/google/cloud/retail/__init__.py deleted file mode 100644 index 0d70ed64..00000000 --- a/owl-bot-staging/v2/google/cloud/retail/__init__.py +++ /dev/null @@ -1,193 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.retail_v2.services.catalog_service.client import CatalogServiceClient -from google.cloud.retail_v2.services.catalog_service.async_client import CatalogServiceAsyncClient -from google.cloud.retail_v2.services.completion_service.client import CompletionServiceClient -from google.cloud.retail_v2.services.completion_service.async_client import CompletionServiceAsyncClient -from google.cloud.retail_v2.services.prediction_service.client import PredictionServiceClient -from google.cloud.retail_v2.services.prediction_service.async_client import PredictionServiceAsyncClient -from google.cloud.retail_v2.services.product_service.client import ProductServiceClient -from google.cloud.retail_v2.services.product_service.async_client import ProductServiceAsyncClient -from google.cloud.retail_v2.services.search_service.client import SearchServiceClient -from google.cloud.retail_v2.services.search_service.async_client import SearchServiceAsyncClient -from google.cloud.retail_v2.services.user_event_service.client import UserEventServiceClient -from google.cloud.retail_v2.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.retail_v2.types.catalog import Catalog -from google.cloud.retail_v2.types.catalog import ProductLevelConfig -from google.cloud.retail_v2.types.catalog_service import GetDefaultBranchRequest -from google.cloud.retail_v2.types.catalog_service import GetDefaultBranchResponse -from google.cloud.retail_v2.types.catalog_service import ListCatalogsRequest -from google.cloud.retail_v2.types.catalog_service import ListCatalogsResponse -from google.cloud.retail_v2.types.catalog_service import SetDefaultBranchRequest -from google.cloud.retail_v2.types.catalog_service import UpdateCatalogRequest -from google.cloud.retail_v2.types.common import Audience -from google.cloud.retail_v2.types.common import ColorInfo -from google.cloud.retail_v2.types.common import CustomAttribute -from google.cloud.retail_v2.types.common import FulfillmentInfo -from google.cloud.retail_v2.types.common import Image -from google.cloud.retail_v2.types.common import Interval -from google.cloud.retail_v2.types.common import LocalInventory -from google.cloud.retail_v2.types.common import PriceInfo -from google.cloud.retail_v2.types.common import Rating -from google.cloud.retail_v2.types.common import UserInfo -from google.cloud.retail_v2.types.completion_service import CompleteQueryRequest -from google.cloud.retail_v2.types.completion_service import CompleteQueryResponse -from google.cloud.retail_v2.types.import_config import BigQuerySource -from google.cloud.retail_v2.types.import_config import CompletionDataInputConfig -from google.cloud.retail_v2.types.import_config import GcsSource -from google.cloud.retail_v2.types.import_config import ImportCompletionDataRequest -from google.cloud.retail_v2.types.import_config import ImportCompletionDataResponse -from google.cloud.retail_v2.types.import_config import ImportErrorsConfig -from google.cloud.retail_v2.types.import_config import ImportMetadata -from google.cloud.retail_v2.types.import_config import ImportProductsRequest -from google.cloud.retail_v2.types.import_config import ImportProductsResponse -from google.cloud.retail_v2.types.import_config import ImportUserEventsRequest -from google.cloud.retail_v2.types.import_config import ImportUserEventsResponse -from google.cloud.retail_v2.types.import_config import ProductInlineSource -from google.cloud.retail_v2.types.import_config import ProductInputConfig -from google.cloud.retail_v2.types.import_config import UserEventImportSummary -from google.cloud.retail_v2.types.import_config import UserEventInlineSource -from google.cloud.retail_v2.types.import_config import UserEventInputConfig -from google.cloud.retail_v2.types.prediction_service import PredictRequest -from google.cloud.retail_v2.types.prediction_service import PredictResponse -from google.cloud.retail_v2.types.product import Product -from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesMetadata -from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesRequest -from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesResponse -from google.cloud.retail_v2.types.product_service import AddLocalInventoriesMetadata -from google.cloud.retail_v2.types.product_service import AddLocalInventoriesRequest -from google.cloud.retail_v2.types.product_service import AddLocalInventoriesResponse -from google.cloud.retail_v2.types.product_service import CreateProductRequest -from google.cloud.retail_v2.types.product_service import DeleteProductRequest -from google.cloud.retail_v2.types.product_service import GetProductRequest -from google.cloud.retail_v2.types.product_service import ListProductsRequest -from google.cloud.retail_v2.types.product_service import ListProductsResponse -from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesMetadata -from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesRequest -from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesResponse -from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesMetadata -from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesRequest -from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesResponse -from google.cloud.retail_v2.types.product_service import SetInventoryMetadata -from google.cloud.retail_v2.types.product_service import SetInventoryRequest -from google.cloud.retail_v2.types.product_service import SetInventoryResponse -from google.cloud.retail_v2.types.product_service import UpdateProductRequest -from google.cloud.retail_v2.types.promotion import Promotion -from google.cloud.retail_v2.types.purge_config import PurgeMetadata -from google.cloud.retail_v2.types.purge_config import PurgeUserEventsRequest -from google.cloud.retail_v2.types.purge_config import PurgeUserEventsResponse -from google.cloud.retail_v2.types.search_service import SearchRequest -from google.cloud.retail_v2.types.search_service import SearchResponse -from google.cloud.retail_v2.types.user_event import CompletionDetail -from google.cloud.retail_v2.types.user_event import ProductDetail -from google.cloud.retail_v2.types.user_event import PurchaseTransaction -from google.cloud.retail_v2.types.user_event import UserEvent -from google.cloud.retail_v2.types.user_event_service import CollectUserEventRequest -from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsMetadata -from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsRequest -from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsResponse -from google.cloud.retail_v2.types.user_event_service import WriteUserEventRequest - -__all__ = ('CatalogServiceClient', - 'CatalogServiceAsyncClient', - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', - 'ProductServiceClient', - 'ProductServiceAsyncClient', - 'SearchServiceClient', - 'SearchServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'Catalog', - 'ProductLevelConfig', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'SetDefaultBranchRequest', - 'UpdateCatalogRequest', - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2/google/cloud/retail/py.typed b/owl-bot-staging/v2/google/cloud/retail/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2/google/cloud/retail/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py deleted file mode 100644 index c7f56a8d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.catalog_service import CatalogServiceClient -from .services.catalog_service import CatalogServiceAsyncClient -from .services.completion_service import CompletionServiceClient -from .services.completion_service import CompletionServiceAsyncClient -from .services.prediction_service import PredictionServiceClient -from .services.prediction_service import PredictionServiceAsyncClient -from .services.product_service import ProductServiceClient -from .services.product_service import ProductServiceAsyncClient -from .services.search_service import SearchServiceClient -from .services.search_service import SearchServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.catalog import Catalog -from .types.catalog import ProductLevelConfig -from .types.catalog_service import GetDefaultBranchRequest -from .types.catalog_service import GetDefaultBranchResponse -from .types.catalog_service import ListCatalogsRequest -from .types.catalog_service import ListCatalogsResponse -from .types.catalog_service import SetDefaultBranchRequest -from .types.catalog_service import UpdateCatalogRequest -from .types.common import Audience -from .types.common import ColorInfo -from .types.common import CustomAttribute -from .types.common import FulfillmentInfo -from .types.common import Image -from .types.common import Interval -from .types.common import LocalInventory -from .types.common import PriceInfo -from .types.common import Rating -from .types.common import UserInfo -from .types.completion_service import CompleteQueryRequest -from .types.completion_service import CompleteQueryResponse -from .types.import_config import BigQuerySource -from .types.import_config import CompletionDataInputConfig -from .types.import_config import GcsSource -from .types.import_config import ImportCompletionDataRequest -from .types.import_config import ImportCompletionDataResponse -from .types.import_config import ImportErrorsConfig -from .types.import_config import ImportMetadata -from .types.import_config import ImportProductsRequest -from .types.import_config import ImportProductsResponse -from .types.import_config import ImportUserEventsRequest -from .types.import_config import ImportUserEventsResponse -from .types.import_config import ProductInlineSource -from .types.import_config import ProductInputConfig -from .types.import_config import UserEventImportSummary -from .types.import_config import UserEventInlineSource -from .types.import_config import UserEventInputConfig -from .types.prediction_service import PredictRequest -from .types.prediction_service import PredictResponse -from .types.product import Product -from .types.product_service import AddFulfillmentPlacesMetadata -from .types.product_service import AddFulfillmentPlacesRequest -from .types.product_service import AddFulfillmentPlacesResponse -from .types.product_service import AddLocalInventoriesMetadata -from .types.product_service import AddLocalInventoriesRequest -from .types.product_service import AddLocalInventoriesResponse -from .types.product_service import CreateProductRequest -from .types.product_service import DeleteProductRequest -from .types.product_service import GetProductRequest -from .types.product_service import ListProductsRequest -from .types.product_service import ListProductsResponse -from .types.product_service import RemoveFulfillmentPlacesMetadata -from .types.product_service import RemoveFulfillmentPlacesRequest -from .types.product_service import RemoveFulfillmentPlacesResponse -from .types.product_service import RemoveLocalInventoriesMetadata -from .types.product_service import RemoveLocalInventoriesRequest -from .types.product_service import RemoveLocalInventoriesResponse -from .types.product_service import SetInventoryMetadata -from .types.product_service import SetInventoryRequest -from .types.product_service import SetInventoryResponse -from .types.product_service import UpdateProductRequest -from .types.promotion import Promotion -from .types.purge_config import PurgeMetadata -from .types.purge_config import PurgeUserEventsRequest -from .types.purge_config import PurgeUserEventsResponse -from .types.search_service import SearchRequest -from .types.search_service import SearchResponse -from .types.user_event import CompletionDetail -from .types.user_event import ProductDetail -from .types.user_event import PurchaseTransaction -from .types.user_event import UserEvent -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import RejoinUserEventsMetadata -from .types.user_event_service import RejoinUserEventsRequest -from .types.user_event_service import RejoinUserEventsResponse -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CatalogServiceAsyncClient', - 'CompletionServiceAsyncClient', - 'PredictionServiceAsyncClient', - 'ProductServiceAsyncClient', - 'SearchServiceAsyncClient', - 'UserEventServiceAsyncClient', -'AddFulfillmentPlacesMetadata', -'AddFulfillmentPlacesRequest', -'AddFulfillmentPlacesResponse', -'AddLocalInventoriesMetadata', -'AddLocalInventoriesRequest', -'AddLocalInventoriesResponse', -'Audience', -'BigQuerySource', -'Catalog', -'CatalogServiceClient', -'CollectUserEventRequest', -'ColorInfo', -'CompleteQueryRequest', -'CompleteQueryResponse', -'CompletionDataInputConfig', -'CompletionDetail', -'CompletionServiceClient', -'CreateProductRequest', -'CustomAttribute', -'DeleteProductRequest', -'FulfillmentInfo', -'GcsSource', -'GetDefaultBranchRequest', -'GetDefaultBranchResponse', -'GetProductRequest', -'Image', -'ImportCompletionDataRequest', -'ImportCompletionDataResponse', -'ImportErrorsConfig', -'ImportMetadata', -'ImportProductsRequest', -'ImportProductsResponse', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'Interval', -'ListCatalogsRequest', -'ListCatalogsResponse', -'ListProductsRequest', -'ListProductsResponse', -'LocalInventory', -'PredictRequest', -'PredictResponse', -'PredictionServiceClient', -'PriceInfo', -'Product', -'ProductDetail', -'ProductInlineSource', -'ProductInputConfig', -'ProductLevelConfig', -'ProductServiceClient', -'Promotion', -'PurchaseTransaction', -'PurgeMetadata', -'PurgeUserEventsRequest', -'PurgeUserEventsResponse', -'Rating', -'RejoinUserEventsMetadata', -'RejoinUserEventsRequest', -'RejoinUserEventsResponse', -'RemoveFulfillmentPlacesMetadata', -'RemoveFulfillmentPlacesRequest', -'RemoveFulfillmentPlacesResponse', -'RemoveLocalInventoriesMetadata', -'RemoveLocalInventoriesRequest', -'RemoveLocalInventoriesResponse', -'SearchRequest', -'SearchResponse', -'SearchServiceClient', -'SetDefaultBranchRequest', -'SetInventoryMetadata', -'SetInventoryRequest', -'SetInventoryResponse', -'UpdateCatalogRequest', -'UpdateProductRequest', -'UserEvent', -'UserEventImportSummary', -'UserEventInlineSource', -'UserEventInputConfig', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json deleted file mode 100644 index 9e04aec8..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json +++ /dev/null @@ -1,333 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.retail_v2", - "protoPackage": "google.cloud.retail.v2", - "schema": "1.0", - "services": { - "CatalogService": { - "clients": { - "grpc": { - "libraryClient": "CatalogServiceClient", - "rpcs": { - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CatalogServiceAsyncClient", - "rpcs": { - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - } - } - } - } - }, - "CompletionService": { - "clients": { - "grpc": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CompletionServiceAsyncClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - } - } - }, - "PredictionService": { - "clients": { - "grpc": { - "libraryClient": "PredictionServiceClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PredictionServiceAsyncClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - } - } - }, - "ProductService": { - "clients": { - "grpc": { - "libraryClient": "ProductServiceClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProductServiceAsyncClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - } - } - }, - "SearchService": { - "clients": { - "grpc": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SearchServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/py.typed b/owl-bot-staging/v2/google/cloud/retail_v2/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py deleted file mode 100644 index d276b897..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CatalogServiceClient -from .async_client import CatalogServiceAsyncClient - -__all__ = ( - 'CatalogServiceClient', - 'CatalogServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py deleted file mode 100644 index b0a1b99e..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py +++ /dev/null @@ -1,653 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.services.catalog_service import pagers -from google.cloud.retail_v2.types import catalog -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport -from .client import CatalogServiceClient - - -class CatalogServiceAsyncClient: - """Service for managing catalog configuration.""" - - _client: CatalogServiceClient - - DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(CatalogServiceClient.branch_path) - parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) - catalog_path = staticmethod(CatalogServiceClient.catalog_path) - parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) - common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CatalogServiceClient.common_project_path) - parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) - common_location_path = staticmethod(CatalogServiceClient.common_location_path) - parse_common_location_path = staticmethod(CatalogServiceClient.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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CatalogServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsAsyncPager: - r"""Lists all the [Catalog][google.cloud.retail.v2.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_list_catalogs(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - parent (:class:`str`): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2.Catalog]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.retail_v2.services.catalog_service.pagers.ListCatalogsAsyncPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.ListCatalogsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_catalogs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCatalogsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_update_catalog(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] - method. - catalog (:class:`google.cloud.retail_v2.types.Catalog`): - Required. The [Catalog][google.cloud.retail.v2.Catalog] - to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2.Catalog], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCatalogRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_catalog, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_set_default_branch(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (:class:`str`): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.SetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_get_default_branch(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (:class:`str`): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # 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_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py deleted file mode 100644 index e6b97cfd..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py +++ /dev/null @@ -1,861 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.services.catalog_service import pagers -from google.cloud.retail_v2.types import catalog -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CatalogServiceGrpcTransport -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -class CatalogServiceClientMeta(type): - """Metaclass for the CatalogService 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[CatalogServiceTransport]] - _transport_registry["grpc"] = CatalogServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CatalogServiceTransport]: - """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): - """Service for managing catalog configuration.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CatalogServiceClient: 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: - CatalogServiceClient: 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) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CatalogServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CatalogServiceTransport): - # transport is a CatalogServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsPager: - r"""Lists all the [Catalog][google.cloud.retail.v2.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_list_catalogs(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2.Catalog]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.retail_v2.services.catalog_service.pagers.ListCatalogsPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ListCatalogsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ListCatalogsRequest): - request = catalog_service.ListCatalogsRequest(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_catalogs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCatalogsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_update_catalog(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] - method. - catalog (google.cloud.retail_v2.types.Catalog): - Required. The [Catalog][google.cloud.retail.v2.Catalog] - to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2.Catalog], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCatalogRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCatalogRequest): - request = catalog_service.UpdateCatalogRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - 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_catalog] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_set_default_branch(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.SetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.SetDefaultBranchRequest): - request = catalog_service.SetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_get_default_branch(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetDefaultBranchRequest): - request = catalog_service.GetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py deleted file mode 100644 index 11dd0677..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2.types import catalog -from google.cloud.retail_v2.types import catalog_service - - -class ListCatalogsPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.ListCatalogsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.ListCatalogsResponse` - 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[..., catalog_service.ListCatalogsResponse], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - for page in self.pages: - yield from page.catalogs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCatalogsAsyncPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.ListCatalogsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.ListCatalogsResponse` - 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[catalog_service.ListCatalogsResponse]], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - async def async_generator(): - async for page in self.pages: - for response in page.catalogs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py deleted file mode 100644 index 0cffa336..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CatalogServiceTransport -from .grpc import CatalogServiceGrpcTransport -from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] -_transport_registry['grpc'] = CatalogServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport - -__all__ = ( - 'CatalogServiceTransport', - 'CatalogServiceGrpcTransport', - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py deleted file mode 100644 index 5f86e6d3..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CatalogServiceTransport(abc.ABC): - """Abstract transport class for CatalogService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_catalogs: gapic_v1.method.wrap_method( - self.list_catalogs, - default_timeout=None, - client_info=client_info, - ), - self.update_catalog: gapic_v1.method.wrap_method( - self.update_catalog, - default_timeout=None, - client_info=client_info, - ), - self.set_default_branch: gapic_v1.method.wrap_method( - self.set_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_default_branch: gapic_v1.method.wrap_method( - self.get_default_branch, - 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Union[ - catalog_service.ListCatalogsResponse, - Awaitable[catalog_service.ListCatalogsResponse] - ]]: - raise NotImplementedError() - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Union[ - gcr_catalog.Catalog, - Awaitable[gcr_catalog.Catalog] - ]]: - raise NotImplementedError() - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Union[ - catalog_service.GetDefaultBranchResponse, - Awaitable[catalog_service.GetDefaultBranchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CatalogServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py deleted file mode 100644 index e4f36175..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py +++ /dev/null @@ -1,379 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO - - -class CatalogServiceGrpcTransport(CatalogServiceTransport): - """gRPC backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - catalog_service.ListCatalogsResponse]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - ~.ListCatalogsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - gcr_catalog.Catalog]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - ~.Catalog]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - empty_pb2.Empty]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - ~.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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - catalog_service.GetDefaultBranchResponse]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - ~.GetDefaultBranchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CatalogServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py deleted file mode 100644 index 38344d17..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,378 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CatalogServiceGrpcTransport - - -class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): - """gRPC AsyncIO backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Awaitable[catalog_service.ListCatalogsResponse]]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - Awaitable[~.ListCatalogsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Awaitable[gcr_catalog.Catalog]]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - Awaitable[~.Catalog]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - 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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Awaitable[catalog_service.GetDefaultBranchResponse]]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - Awaitable[~.GetDefaultBranchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py deleted file mode 100644 index b8af95bd..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CompletionServiceClient -from .async_client import CompletionServiceAsyncClient - -__all__ = ( - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py deleted file mode 100644 index 9e5d6432..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py +++ /dev/null @@ -1,391 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .client import CompletionServiceClient - - -class CompletionServiceAsyncClient: - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: CompletionServiceClient - - DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(CompletionServiceClient.catalog_path) - parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) - common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CompletionServiceClient.common_project_path) - parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) - common_location_path = staticmethod(CompletionServiceClient.common_location_path) - parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CompletionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_complete_query(): - # Create a client - client = retail_v2.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.complete_query, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_import_completion_data(): - # Create a client - client = retail_v2.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. - 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. - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_completion_data, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py deleted file mode 100644 index 95aa31c3..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py +++ /dev/null @@ -1,592 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CompletionServiceGrpcTransport -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -class CompletionServiceClientMeta(type): - """Metaclass for the CompletionService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] - _transport_registry["grpc"] = CompletionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CompletionServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class CompletionServiceClient(metaclass=CompletionServiceClientMeta): - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CompletionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CompletionServiceTransport): - # transport is a CompletionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_complete_query(): - # Create a client - client = retail_v2.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a completion_service.CompleteQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, completion_service.CompleteQueryRequest): - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_import_completion_data(): - # Create a client - client = retail_v2.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. - 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. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportCompletionDataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportCompletionDataRequest): - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_completion_data] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py deleted file mode 100644 index a0c9542f..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CompletionServiceTransport -from .grpc import CompletionServiceGrpcTransport -from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] -_transport_registry['grpc'] = CompletionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport - -__all__ = ( - 'CompletionServiceTransport', - 'CompletionServiceGrpcTransport', - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py deleted file mode 100644 index 3cc2b0e8..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py +++ /dev/null @@ -1,172 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CompletionServiceTransport(abc.ABC): - """Abstract transport class for CompletionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.complete_query: gapic_v1.method.wrap_method( - self.complete_query, - default_timeout=None, - client_info=client_info, - ), - self.import_completion_data: gapic_v1.method.wrap_method( - self.import_completion_data, - 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Union[ - completion_service.CompleteQueryResponse, - Awaitable[completion_service.CompleteQueryResponse] - ]]: - raise NotImplementedError() - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CompletionServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py deleted file mode 100644 index 383f0bf9..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py +++ /dev/null @@ -1,323 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO - - -class CompletionServiceGrpcTransport(CompletionServiceTransport): - """gRPC backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - ~.CompleteQueryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - operations_pb2.Operation]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CompletionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py deleted file mode 100644 index f945dec1..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,322 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CompletionServiceGrpcTransport - - -class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): - """gRPC AsyncIO backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Awaitable[completion_service.CompleteQueryResponse]]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - Awaitable[~.CompleteQueryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - 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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py deleted file mode 100644 index 7c079c80..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import PredictionServiceClient -from .async_client import PredictionServiceAsyncClient - -__all__ = ( - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py deleted file mode 100644 index ae9f9c86..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py +++ /dev/null @@ -1,279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport -from .client import PredictionServiceClient - - -class PredictionServiceAsyncClient: - """Service for making recommendation prediction.""" - - _client: PredictionServiceClient - - DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT - - product_path = staticmethod(PredictionServiceClient.product_path) - parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) - common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(PredictionServiceClient.common_project_path) - parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) - common_location_path = staticmethod(PredictionServiceClient.common_location_path) - parse_common_location_path = staticmethod(PredictionServiceClient.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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PredictionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_predict(): - # Create a client - client = retail_v2.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - request = prediction_service.PredictRequest(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.predict, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py deleted file mode 100644 index 51ab0482..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py +++ /dev/null @@ -1,479 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PredictionServiceGrpcTransport -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -class PredictionServiceClientMeta(type): - """Metaclass for the PredictionService 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[PredictionServiceTransport]] - _transport_registry["grpc"] = PredictionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PredictionServiceTransport]: - """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): - """Service for making recommendation prediction.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PredictionServiceClient: 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: - PredictionServiceClient: 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) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, PredictionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, PredictionServiceTransport): - # transport is a PredictionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_predict(): - # Create a client - client = retail_v2.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a prediction_service.PredictRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_service.PredictRequest): - request = prediction_service.PredictRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.predict] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py deleted file mode 100644 index bb65c664..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PredictionServiceTransport -from .grpc import PredictionServiceGrpcTransport -from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] -_transport_registry['grpc'] = PredictionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport - -__all__ = ( - 'PredictionServiceTransport', - 'PredictionServiceGrpcTransport', - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py deleted file mode 100644 index 4bf1f54d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import prediction_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PredictionServiceTransport(abc.ABC): - """Abstract transport class for PredictionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.predict: gapic_v1.method.wrap_method( - self.predict, - 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - Union[ - prediction_service.PredictResponse, - Awaitable[prediction_service.PredictResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PredictionServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py deleted file mode 100644 index 5b717f9b..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py +++ /dev/null @@ -1,262 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO - - -class PredictionServiceGrpcTransport(PredictionServiceTransport): - """gRPC backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - prediction_service.PredictResponse]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - ~.PredictResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PredictionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py deleted file mode 100644 index 1805223d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,261 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import PredictionServiceGrpcTransport - - -class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): - """gRPC AsyncIO backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def predict(self) -> Callable[ - [prediction_service.PredictRequest], - Awaitable[prediction_service.PredictResponse]]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - Awaitable[~.PredictResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py deleted file mode 100644 index 0fa6330a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ProductServiceClient -from .async_client import ProductServiceAsyncClient - -__all__ = ( - 'ProductServiceClient', - 'ProductServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py deleted file mode 100644 index db29be72..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py +++ /dev/null @@ -1,1701 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.services.product_service import pagers -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.cloud.retail_v2.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport -from .client import ProductServiceClient - - -class ProductServiceAsyncClient: - """Service for ingesting [Product][google.cloud.retail.v2.Product] - information of the customer's website. - """ - - _client: ProductServiceClient - - DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(ProductServiceClient.branch_path) - parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) - product_path = staticmethod(ProductServiceClient.product_path) - parse_product_path = staticmethod(ProductServiceClient.parse_product_path) - common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProductServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProductServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ProductServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) - common_location_path = staticmethod(ProductServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProductServiceClient.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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ProductServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ProductServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_create_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (:class:`str`): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (:class:`google.cloud.retail_v2.types.Product`): - Required. The [Product][google.cloud.retail.v2.Product] - to create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (:class:`str`): - Required. The ID to use for the - [Product][google.cloud.retail.v2.Product], which will - become the final component of the - [Product.name][google.cloud.retail.v2.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2.Product]s with the same - [parent][google.cloud.retail.v2.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.CreateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_get_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested - [Product][google.cloud.retail.v2.Product] 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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.GetProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsAsyncPager: - r"""Gets a list of [Product][google.cloud.retail.v2.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_list_products(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - parent (:class:`str`): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2.Product]s under this - branch, regardless of whether or not this branch exists, - a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.services.product_service.pagers.ListProductsAsyncPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.ListProductsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_products, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProductsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_update_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (:class:`google.cloud.retail_v2.types.Product`): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2.Product] to update. The - immutable and output only fields are NOT supported. If - not set, all supported fields (the fields that are - neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - The attribute key can be updated by setting the mask - path as "attributes.${key_name}". If a key name is - present in the mask but not in the patching product from - the request, this key will be deleted after the update. - - 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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.UpdateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_delete_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2.Product] to delete - can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] with more than - one - [variants][google.cloud.retail.v2.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.DeleteProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2.Product]s. - - Request processing may be synchronous. Non-existing items are - created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2.Product]s to be successfully - updated. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_import_products(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2.Product] while respecting the - last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_set_inventory(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2.Product() - inventory.title = "title_value" - - request = retail_v2.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (:class:`google.cloud.retail_v2.types.Product`): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product] named in - [Product.name][google.cloud.retail.v2.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.SetInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_inventory, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - async def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places, - while respecting the last update timestamps of each inventory - field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_add_local_inventories(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.AddLocalInventoriesResponse` Response of the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - API. Currently empty because there is no meaningful - response populated from the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places at - a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_remove_local_inventories(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py deleted file mode 100644 index 4a598563..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py +++ /dev/null @@ -1,1903 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.services.product_service import pagers -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.cloud.retail_v2.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProductServiceGrpcTransport -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -class ProductServiceClientMeta(type): - """Metaclass for the ProductService 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[ProductServiceTransport]] - _transport_registry["grpc"] = ProductServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ProductServiceTransport]: - """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 ProductServiceClient(metaclass=ProductServiceClientMeta): - """Service for ingesting [Product][google.cloud.retail.v2.Product] - information of the customer's website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProductServiceClient: 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: - ProductServiceClient: 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) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProductServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ProductServiceTransport): - # transport is a ProductServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_create_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (google.cloud.retail_v2.types.Product): - Required. The [Product][google.cloud.retail.v2.Product] - to create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2.Product], which will - become the final component of the - [Product.name][google.cloud.retail.v2.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2.Product]s with the same - [parent][google.cloud.retail.v2.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.CreateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.CreateProductRequest): - request = product_service.CreateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_get_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested - [Product][google.cloud.retail.v2.Product] 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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.GetProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.GetProductRequest): - request = product_service.GetProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsPager: - r"""Gets a list of [Product][google.cloud.retail.v2.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_list_products(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2.Product]s under this - branch, regardless of whether or not this branch exists, - a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.services.product_service.pagers.ListProductsPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.ListProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.ListProductsRequest): - request = product_service.ListProductsRequest(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_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProductsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_update_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (google.cloud.retail_v2.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2.Product] to update. The - immutable and output only fields are NOT supported. If - not set, all supported fields (the fields that are - neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - The attribute key can be updated by setting the mask - path as "attributes.${key_name}". If a key name is - present in the mask but not in the patching product from - the request, this key will be deleted after the update. - - 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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.UpdateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.UpdateProductRequest): - request = product_service.UpdateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - 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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_delete_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2.Product] to delete - can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] with more than - one - [variants][google.cloud.retail.v2.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.DeleteProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.DeleteProductRequest): - request = product_service.DeleteProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2.Product]s. - - Request processing may be synchronous. Non-existing items are - created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2.Product]s to be successfully - updated. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_import_products(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportProductsRequest): - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2.Product] while respecting the - last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_set_inventory(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2.Product() - inventory.title = "title_value" - - request = retail_v2.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (google.cloud.retail_v2.types.Product): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product] named in - [Product.name][google.cloud.retail.v2.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.SetInventoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.SetInventoryRequest): - request = product_service.SetInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_add_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddFulfillmentPlacesRequest): - request = product_service.AddFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): - request = product_service.RemoveFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places, - while respecting the last update timestamps of each inventory - field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_add_local_inventories(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.AddLocalInventoriesResponse` Response of the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - API. Currently empty because there is no meaningful - response populated from the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddLocalInventoriesRequest): - request = product_service.AddLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places at - a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_remove_local_inventories(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveLocalInventoriesRequest): - request = product_service.RemoveLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py deleted file mode 100644 index f9e49958..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product_service - - -class ListProductsPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.ListProductsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.ListProductsResponse` - 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[..., product_service.ListProductsResponse], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[product_service.ListProductsResponse]: - 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[product.Product]: - for page in self.pages: - yield from page.products - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProductsAsyncPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.ListProductsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.ListProductsResponse` - 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[product_service.ListProductsResponse]], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: - 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[product.Product]: - async def async_generator(): - async for page in self.pages: - for response in page.products: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py deleted file mode 100644 index db824dec..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ProductServiceTransport -from .grpc import ProductServiceGrpcTransport -from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] -_transport_registry['grpc'] = ProductServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport - -__all__ = ( - 'ProductServiceTransport', - 'ProductServiceGrpcTransport', - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py deleted file mode 100644 index 7d737508..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py +++ /dev/null @@ -1,308 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ProductServiceTransport(abc.ABC): - """Abstract transport class for ProductService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_product: gapic_v1.method.wrap_method( - self.create_product, - default_timeout=None, - client_info=client_info, - ), - self.get_product: gapic_v1.method.wrap_method( - self.get_product, - default_timeout=None, - client_info=client_info, - ), - self.list_products: gapic_v1.method.wrap_method( - self.list_products, - default_timeout=None, - client_info=client_info, - ), - self.update_product: gapic_v1.method.wrap_method( - self.update_product, - default_timeout=None, - client_info=client_info, - ), - self.delete_product: gapic_v1.method.wrap_method( - self.delete_product, - default_timeout=None, - client_info=client_info, - ), - self.import_products: gapic_v1.method.wrap_method( - self.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.set_inventory: gapic_v1.method.wrap_method( - self.set_inventory, - default_timeout=None, - client_info=client_info, - ), - self.add_fulfillment_places: gapic_v1.method.wrap_method( - self.add_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.remove_fulfillment_places: gapic_v1.method.wrap_method( - self.remove_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.add_local_inventories: gapic_v1.method.wrap_method( - self.add_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.remove_local_inventories: gapic_v1.method.wrap_method( - self.remove_local_inventories, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Union[ - product.Product, - Awaitable[product.Product] - ]]: - raise NotImplementedError() - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Union[ - product_service.ListProductsResponse, - Awaitable[product_service.ListProductsResponse] - ]]: - raise NotImplementedError() - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ProductServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py deleted file mode 100644 index b61a4b0e..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py +++ /dev/null @@ -1,678 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO - - -class ProductServiceGrpcTransport(ProductServiceTransport): - """gRPC backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - gcr_product.Product]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.CreateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - product.Product]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.GetProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - product_service.ListProductsResponse]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - ~.ListProductsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - gcr_product.Product]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - ~.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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2.Product]s. - - Request processing may be synchronous. Non-existing items are - created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2.Product]s to be successfully - updated. - - Returns: - Callable[[~.ImportProductsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - operations_pb2.Operation]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2.Product] while respecting the - last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places, - while respecting the last update timestamps of each inventory - field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places at - a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProductServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py deleted file mode 100644 index 1433a72f..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,677 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ProductServiceGrpcTransport - - -class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): - """gRPC AsyncIO backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.CreateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Awaitable[product.Product]]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.GetProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Awaitable[product_service.ListProductsResponse]]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - Awaitable[~.ListProductsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - 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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2.Product]s. - - Request processing may be synchronous. Non-existing items are - created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2.Product]s to be successfully - updated. - - Returns: - Callable[[~.ImportProductsRequest], - 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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2.Product] while respecting the - last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - 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 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - 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 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places, - while respecting the last update timestamps of each inventory - field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - 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 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places at - a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - 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 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py deleted file mode 100644 index 2f63fc22..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SearchServiceClient -from .async_client import SearchServiceAsyncClient - -__all__ = ( - 'SearchServiceClient', - 'SearchServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py deleted file mode 100644 index c48710b8..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.services.search_service import pagers -from google.cloud.retail_v2.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .client import SearchServiceClient - - -class SearchServiceAsyncClient: - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: SearchServiceClient - - DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(SearchServiceClient.branch_path) - parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) - product_path = staticmethod(SearchServiceClient.product_path) - parse_product_path = staticmethod(SearchServiceClient.parse_product_path) - common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(SearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SearchServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAsyncPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_search(): - # Create a client - client = retail_v2.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.services.search_service.pagers.SearchAsyncPager: - Response message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py deleted file mode 100644 index aabc6c30..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py +++ /dev/null @@ -1,512 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.services.search_service import pagers -from google.cloud.retail_v2.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SearchServiceGrpcTransport -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -class SearchServiceClientMeta(type): - """Metaclass for the SearchService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] - _transport_registry["grpc"] = SearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SearchServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SearchServiceClient(metaclass=SearchServiceClientMeta): - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SearchServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SearchServiceTransport): - # transport is a SearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_search(): - # Create a client - client = retail_v2.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.services.search_service.pagers.SearchPager: - Response message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a search_service.SearchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, search_service.SearchRequest): - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py deleted file mode 100644 index 524810e2..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2.types import search_service - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., search_service.SearchResponse], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[search_service.SearchResponse]], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py deleted file mode 100644 index 7917cd1d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SearchServiceTransport -from .grpc import SearchServiceGrpcTransport -from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] -_transport_registry['grpc'] = SearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport - -__all__ = ( - 'SearchServiceTransport', - 'SearchServiceGrpcTransport', - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py deleted file mode 100644 index 4d31461b..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import search_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class SearchServiceTransport(abc.ABC): - """Abstract transport class for SearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search: gapic_v1.method.wrap_method( - self.search, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Union[ - search_service.SearchResponse, - Awaitable[search_service.SearchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SearchServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py deleted file mode 100644 index 0c575b65..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py +++ /dev/null @@ -1,268 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO - - -class SearchServiceGrpcTransport(SearchServiceTransport): - """gRPC backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py deleted file mode 100644 index 84a64ed9..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,267 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SearchServiceGrpcTransport - - -class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): - """gRPC AsyncIO backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Awaitable[search_service.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py deleted file mode 100644 index 5f5171c1..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py deleted file mode 100644 index 99002514..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py +++ /dev/null @@ -1,730 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on the customer - website. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(UserEventServiceClient.catalog_path) - parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) - product_path = staticmethod(UserEventServiceClient.product_path) - parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_write_user_event(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_collect_user_event(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_purge_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_import_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_rejoin_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py deleted file mode 100644 index 8422b4b6..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py +++ /dev/null @@ -1,929 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[UserEventServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on the customer - website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_write_user_event(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_collect_user_event(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_purge_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeUserEventsRequest): - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_import_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportUserEventsRequest): - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_rejoin_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.RejoinUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.RejoinUserEventsRequest): - request = user_event_service.RejoinUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py deleted file mode 100644 index f53ee5d7..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py deleted file mode 100644 index 4a2436f6..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py +++ /dev/null @@ -1,231 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_timeout=None, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_timeout=None, - client_info=client_info, - ), - self.purge_user_events: gapic_v1.method.wrap_method( - self.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.rejoin_user_events: gapic_v1.method.wrap_method( - self.rejoin_user_events, - 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 write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - user_event.UserEvent, - Awaitable[user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py deleted file mode 100644 index cfd04d9b..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,415 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index 94b3b4e5..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,414 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - 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 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py deleted file mode 100644 index 8e0ea23a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .catalog import ( - Catalog, - ProductLevelConfig, -) -from .catalog_service import ( - GetDefaultBranchRequest, - GetDefaultBranchResponse, - ListCatalogsRequest, - ListCatalogsResponse, - SetDefaultBranchRequest, - UpdateCatalogRequest, -) -from .common import ( - Audience, - ColorInfo, - CustomAttribute, - FulfillmentInfo, - Image, - Interval, - LocalInventory, - PriceInfo, - Rating, - UserInfo, -) -from .completion_service import ( - CompleteQueryRequest, - CompleteQueryResponse, -) -from .import_config import ( - BigQuerySource, - CompletionDataInputConfig, - GcsSource, - ImportCompletionDataRequest, - ImportCompletionDataResponse, - ImportErrorsConfig, - ImportMetadata, - ImportProductsRequest, - ImportProductsResponse, - ImportUserEventsRequest, - ImportUserEventsResponse, - ProductInlineSource, - ProductInputConfig, - UserEventImportSummary, - UserEventInlineSource, - UserEventInputConfig, -) -from .prediction_service import ( - PredictRequest, - PredictResponse, -) -from .product import ( - Product, -) -from .product_service import ( - AddFulfillmentPlacesMetadata, - AddFulfillmentPlacesRequest, - AddFulfillmentPlacesResponse, - AddLocalInventoriesMetadata, - AddLocalInventoriesRequest, - AddLocalInventoriesResponse, - CreateProductRequest, - DeleteProductRequest, - GetProductRequest, - ListProductsRequest, - ListProductsResponse, - RemoveFulfillmentPlacesMetadata, - RemoveFulfillmentPlacesRequest, - RemoveFulfillmentPlacesResponse, - RemoveLocalInventoriesMetadata, - RemoveLocalInventoriesRequest, - RemoveLocalInventoriesResponse, - SetInventoryMetadata, - SetInventoryRequest, - SetInventoryResponse, - UpdateProductRequest, -) -from .promotion import ( - Promotion, -) -from .purge_config import ( - PurgeMetadata, - PurgeUserEventsRequest, - PurgeUserEventsResponse, -) -from .search_service import ( - SearchRequest, - SearchResponse, -) -from .user_event import ( - CompletionDetail, - ProductDetail, - PurchaseTransaction, - UserEvent, -) -from .user_event_service import ( - CollectUserEventRequest, - RejoinUserEventsMetadata, - RejoinUserEventsRequest, - RejoinUserEventsResponse, - WriteUserEventRequest, -) - -__all__ = ( - 'Catalog', - 'ProductLevelConfig', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'SetDefaultBranchRequest', - 'UpdateCatalogRequest', - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py deleted file mode 100644 index 47a372fb..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py +++ /dev/null @@ -1,131 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'ProductLevelConfig', - 'Catalog', - }, -) - - -class ProductLevelConfig(proto.Message): - r"""Configures what level the product should be uploaded with - regards to how users will be send events and how predictions - will be made. - - Attributes: - ingestion_product_type (str): - The type of [Product][google.cloud.retail.v2.Product]s - allowed to be ingested into the catalog. Acceptable values - are: - - - ``primary`` (default): You can ingest - [Product][google.cloud.retail.v2.Product]s of all types. - When ingesting a - [Product][google.cloud.retail.v2.Product], its type will - default to - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - if unset. - - ``variant`` (incompatible with Retail Search): You can - only ingest - [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s. This means - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] - cannot be empty. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``variant`` and - [merchant_center_product_id_field][google.cloud.retail.v2.ProductLevelConfig.merchant_center_product_id_field] - is ``itemGroupId``, an INVALID_ARGUMENT error is returned. - - See `Product - levels `__ - for more details. - merchant_center_product_id_field (str): - Which field of `Merchant Center - Product `__ - should be imported as - [Product.id][google.cloud.retail.v2.Product.id]. Acceptable - values are: - - - ``offerId`` (default): Import ``offerId`` as the product - ID. - - ``itemGroupId``: Import ``itemGroupId`` as the product - ID. Notice that Retail API will choose one item from the - ones with the same ``itemGroupId``, and use it to - represent the item group. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``itemGroupId`` and - [ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] - is ``variant``, an INVALID_ARGUMENT error is returned. - - See `Product - levels `__ - for more details. - """ - - ingestion_product_type = proto.Field( - proto.STRING, - number=1, - ) - merchant_center_product_id_field = proto.Field( - proto.STRING, - number=2, - ) - - -class Catalog(proto.Message): - r"""The catalog configuration. - - Attributes: - name (str): - Required. Immutable. The fully qualified - resource name of the catalog. - display_name (str): - Required. Immutable. The catalog display name. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - product_level_config (google.cloud.retail_v2.types.ProductLevelConfig): - Required. The product level configuration. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - product_level_config = proto.Field( - proto.MESSAGE, - number=4, - message='ProductLevelConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py deleted file mode 100644 index 721ef858..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py +++ /dev/null @@ -1,248 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'UpdateCatalogRequest', - 'SetDefaultBranchRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - }, -) - - -class ListCatalogsRequest(proto.Message): - r"""Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - - Attributes: - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2.Catalog]s under this - location, regardless of whether or not this location exists, - a PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of [Catalog][google.cloud.retail.v2.Catalog]s - to return. If unspecified, defaults to 50. The maximum - allowed value is 1000. Values above 1000 will be coerced to - 1000. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [ListCatalogsResponse.next_page_token][google.cloud.retail.v2.ListCatalogsResponse.next_page_token], - received from a previous - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListCatalogsResponse(proto.Message): - r"""Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - - Attributes: - catalogs (Sequence[google.cloud.retail_v2.types.Catalog]): - All the customer's - [Catalog][google.cloud.retail.v2.Catalog]s. - next_page_token (str): - A token that can be sent as - [ListCatalogsRequest.page_token][google.cloud.retail.v2.ListCatalogsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - catalogs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateCatalogRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] - method. - - Attributes: - catalog (google.cloud.retail_v2.types.Catalog): - Required. The [Catalog][google.cloud.retail.v2.Catalog] to - update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2.Catalog], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2.Catalog] 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 - [Catalog][google.cloud.retail.v2.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - catalog = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class SetDefaultBranchRequest(proto.Message): - r"""Request message to set a specified branch as new default_branch. - - Attributes: - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - branch_id (str): - The final component of the resource name of a branch. - - This field must be one of "0", "1" or "2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If there are no sufficient active products in the targeted - branch and - [force][google.cloud.retail.v2.SetDefaultBranchRequest.force] - is not set, a FAILED_PRECONDITION error is returned. - note (str): - Some note on this request, this can be retrieved by - [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch] - before next valid default branch set occurs. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - force (bool): - If set to true, it permits switching to a branch with - [branch_id][google.cloud.retail.v2.SetDefaultBranchRequest.branch_id] - even if it has no sufficient active products. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - force = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetDefaultBranchRequest(proto.Message): - r"""Request message to show which branch is currently the default - branch. - - Attributes: - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - - -class GetDefaultBranchResponse(proto.Message): - r"""Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. - - Attributes: - branch (str): - Full resource name of the branch id currently - set as default branch. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when this branch is set to default. - note (str): - This corresponds to - [SetDefaultBranchRequest.note][google.cloud.retail.v2.SetDefaultBranchRequest.note] - field, when this branch was set as default. - """ - - branch = proto.Field( - proto.STRING, - number=1, - ) - set_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py deleted file mode 100644 index fe50745a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py +++ /dev/null @@ -1,736 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'LocalInventory', - }, -) - - -class Audience(proto.Message): - r"""An intended audience of the - [Product][google.cloud.retail.v2.Product] for whom it's sold. - - Attributes: - genders (Sequence[str]): - The genders of the audience. Strongly encouraged to use the - standard values: "male", "female", "unisex". - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `gender `__. - Schema.org property - `Product.audience.suggestedGender `__. - age_groups (Sequence[str]): - The age groups of the audience. Strongly encouraged to use - the standard values: "newborn" (up to 3 months old), - "infant" (3–12 months old), "toddler" (1–5 years old), - "kids" (5–13 years old), "adult" (typically teens or older). - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `age_group `__. - Schema.org property - `Product.audience.suggestedMinAge `__ - and - `Product.audience.suggestedMaxAge `__. - """ - - genders = proto.RepeatedField( - proto.STRING, - number=1, - ) - age_groups = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class ColorInfo(proto.Message): - r"""The color information of a - [Product][google.cloud.retail.v2.Product]. - - Attributes: - color_families (Sequence[str]): - The standard color families. Strongly recommended to use the - following standard color groups: "Red", "Pink", "Orange", - "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", - "White", "Gray", "Black" and "Mixed". Normally it is - expected to have only 1 color family. May consider using - single "Mixed" instead of multiple values. - - A maximum of 5 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - colors (Sequence[str]): - The color display names, which may be different from - standard color family names, such as the color aliases used - in the website frontend. Normally it is expected to have - only 1 color. May consider using single "Mixed" instead of - multiple values. - - A maximum of 25 colors are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - """ - - color_families = proto.RepeatedField( - proto.STRING, - number=1, - ) - colors = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class CustomAttribute(proto.Message): - r"""A custom attribute that is not explicitly modeled in - [Product][google.cloud.retail.v2.Product]. - - Attributes: - text (Sequence[str]): - The textual values of this custom attribute. For example, - ``["yellow", "green"]`` when the key is "color". - - Empty string is not allowed. Otherwise, an INVALID_ARGUMENT - error is returned. - - Exactly one of - [text][google.cloud.retail.v2.CustomAttribute.text] or - [numbers][google.cloud.retail.v2.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - numbers (Sequence[float]): - The numerical values of this custom attribute. For example, - ``[2.3, 15.4]`` when the key is "lengths_cm". - - Exactly one of - [text][google.cloud.retail.v2.CustomAttribute.text] or - [numbers][google.cloud.retail.v2.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - searchable (bool): - This field is normally ignored unless - [AttributesConfig.attribute_config_level][] of the - [Catalog][google.cloud.retail.v2.Catalog] is set to the - deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For - information about product-level attribute configuration, see - `Configuration - modes `__. - If true, custom attribute values are searchable by text - queries in - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2.UserEvent]. - - Only set if type - [text][google.cloud.retail.v2.CustomAttribute.text] is set. - Otherwise, a INVALID_ARGUMENT error is returned. - - This field is a member of `oneof`_ ``_searchable``. - indexable (bool): - This field is normally ignored unless - [AttributesConfig.attribute_config_level][] of the - [Catalog][google.cloud.retail.v2.Catalog] is set to the - deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For - information about product-level attribute configuration, see - `Configuration - modes `__. - If true, custom attribute values are indexed, so that they - can be filtered, faceted or boosted in - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2.UserEvent]. - - See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter], - [SearchRequest.facet_specs][google.cloud.retail.v2.SearchRequest.facet_specs] - and - [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] - for more details. - - This field is a member of `oneof`_ ``_indexable``. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - numbers = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - searchable = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - indexable = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - -class FulfillmentInfo(proto.Message): - r"""Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - Attributes: - type_ (str): - The fulfillment type, including commonly used types (such as - pickup in store and same day delivery), and custom types. - Customers have to map custom types to their display names - before rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - place_ids (Sequence[str]): - The IDs for this - [type][google.cloud.retail.v2.FulfillmentInfo.type], such as - the store IDs for - [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2.FulfillmentInfo.type] - or the region IDs for - [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2.FulfillmentInfo.type]. - - A maximum of 3000 values are allowed. Each value must be a - string with a length limit of 30 characters, matching the - pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". - Otherwise, an INVALID_ARGUMENT error is returned. - """ - - type_ = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class Image(proto.Message): - r"""[Product][google.cloud.retail.v2.Product] image. Recommendations AI - and Retail Search do not use product images to improve prediction - and search results. However, product images can be returned in - results, and are shown in prediction or search previews in the - console. - - Attributes: - uri (str): - Required. URI of the image. - - This field must be a valid UTF-8 encoded URI with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - height (int): - Height of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - width (int): - Width of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - height = proto.Field( - proto.INT32, - number=2, - ) - width = proto.Field( - proto.INT32, - number=3, - ) - - -class Interval(proto.Message): - r"""A floating point interval. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - minimum (float): - Inclusive lower bound. - - This field is a member of `oneof`_ ``min``. - exclusive_minimum (float): - Exclusive lower bound. - - This field is a member of `oneof`_ ``min``. - maximum (float): - Inclusive upper bound. - - This field is a member of `oneof`_ ``max``. - exclusive_maximum (float): - Exclusive upper bound. - - This field is a member of `oneof`_ ``max``. - """ - - minimum = proto.Field( - proto.DOUBLE, - number=1, - oneof='min', - ) - exclusive_minimum = proto.Field( - proto.DOUBLE, - number=2, - oneof='min', - ) - maximum = proto.Field( - proto.DOUBLE, - number=3, - oneof='max', - ) - exclusive_maximum = proto.Field( - proto.DOUBLE, - number=4, - oneof='max', - ) - - -class PriceInfo(proto.Message): - r"""The price information of a - [Product][google.cloud.retail.v2.Product]. - - Attributes: - currency_code (str): - The 3-letter currency code defined in `ISO - 4217 `__. - - If this field is an unrecognizable currency code, an - INVALID_ARGUMENT error is returned. - - The - [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s with the same - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] - must share the same - [currency_code][google.cloud.retail.v2.PriceInfo.currency_code]. - Otherwise, a FAILED_PRECONDITION error is returned. - price (float): - Price of the product. - - Google Merchant Center property - `price `__. - Schema.org property - `Offer.price `__. - original_price (float): - Price of the product without any discount. If zero, by - default set to be the - [price][google.cloud.retail.v2.PriceInfo.price]. If set, - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - should be greater than or equal to - [price][google.cloud.retail.v2.PriceInfo.price], otherwise - an INVALID_ARGUMENT error is thrown. - cost (float): - The costs associated with the sale of a particular product. - Used for gross profit reporting. - - - Profit = [price][google.cloud.retail.v2.PriceInfo.price] - - [cost][google.cloud.retail.v2.PriceInfo.cost] - - Google Merchant Center property - `cost_of_goods_sold `__. - price_effective_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2.PriceInfo.price] starts to be - effective. This can be set as a future timestamp, and the - [price][google.cloud.retail.v2.PriceInfo.price] is only used - for search after - [price_effective_time][google.cloud.retail.v2.PriceInfo.price_effective_time]. - If so, the - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - is used before - [price_effective_time][google.cloud.retail.v2.PriceInfo.price_effective_time]. - - Do not set if - [price][google.cloud.retail.v2.PriceInfo.price] is always - effective because it will cause additional latency during - search. - price_expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2.PriceInfo.price] stops to be - effective. The - [price][google.cloud.retail.v2.PriceInfo.price] is used for - search before - [price_expire_time][google.cloud.retail.v2.PriceInfo.price_expire_time]. - If this field is set, the - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - is used after - [price_expire_time][google.cloud.retail.v2.PriceInfo.price_expire_time]. - - Do not set if - [price][google.cloud.retail.v2.PriceInfo.price] is always - effective because it will cause additional latency during - search. - price_range (google.cloud.retail_v2.types.PriceInfo.PriceRange): - Output only. The price range of all the child - [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s grouped together - on the - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]. Only populated - for - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]. - Do not set this field in API requests. - """ - - class PriceRange(proto.Message): - r"""The price range of all - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. - - Attributes: - price (google.cloud.retail_v2.types.Interval): - The inclusive - [Product.pricing_info.price][google.cloud.retail.v2.PriceInfo.price] - interval of all - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. - original_price (google.cloud.retail_v2.types.Interval): - The inclusive - [Product.pricing_info.original_price][google.cloud.retail.v2.PriceInfo.original_price] - internal of all - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. - """ - - price = proto.Field( - proto.MESSAGE, - number=1, - message='Interval', - ) - original_price = proto.Field( - proto.MESSAGE, - number=2, - message='Interval', - ) - - currency_code = proto.Field( - proto.STRING, - number=1, - ) - price = proto.Field( - proto.FLOAT, - number=2, - ) - original_price = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - price_effective_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - price_expire_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - price_range = proto.Field( - proto.MESSAGE, - number=7, - message=PriceRange, - ) - - -class Rating(proto.Message): - r"""The rating of a [Product][google.cloud.retail.v2.Product]. - - Attributes: - rating_count (int): - The total number of ratings. This value is independent of - the value of - [rating_histogram][google.cloud.retail.v2.Rating.rating_histogram]. - - This value must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - average_rating (float): - The average rating of the - [Product][google.cloud.retail.v2.Product]. - - The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT - error is returned. - rating_histogram (Sequence[int]): - List of rating counts per rating value (index = rating - 1). - The list is empty if there is no rating. If the list is - non-empty, its size is always 5. Otherwise, an - INVALID_ARGUMENT error is returned. - - For example, [41, 14, 13, 47, 303]. It means that the - [Product][google.cloud.retail.v2.Product] got 41 ratings - with 1 star, 14 ratings with 2 star, and so on. - """ - - rating_count = proto.Field( - proto.INT32, - number=1, - ) - average_rating = proto.Field( - proto.FLOAT, - number=2, - ) - rating_histogram = proto.RepeatedField( - proto.INT32, - number=3, - ) - - -class UserInfo(proto.Message): - r"""Information of an end user. - - Attributes: - user_id (str): - Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. Don't set for - anonymous users. - - Always use a hashed value for this ID. - - Don't set the field to the same fixed ID for different - users. This mixes the event history of those users together, - which results in degraded model quality. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - ip_address (str): - The end user's IP address. This field is used to extract - location information for personalization. - - This field must be either an IPv4 address (e.g. - "104.133.9.80") or an IPv6 address (e.g. - "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an - INVALID_ARGUMENT error is returned. - - This should not be set when: - - - setting - [SearchRequest.user_info][google.cloud.retail.v2.SearchRequest.user_info]. - - using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request] - is set. - user_agent (str): - User agent as included in the HTTP header. Required for - getting - [SearchResponse.sponsored_results][google.cloud.retail.v2.SearchResponse.sponsored_results]. - - The field must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This should not be set when using the client side event - reporting with GTM or JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request] - is set. - direct_user_request (bool): - True if the request is made directly from the end user, in - which case the - [ip_address][google.cloud.retail.v2.UserInfo.ip_address] and - [user_agent][google.cloud.retail.v2.UserInfo.user_agent] can - be populated from the HTTP request. This flag should be set - only if the API request is made directly from the end user - such as a mobile app (and not if a gateway or a server is - processing and pushing the user events). - - This should not be set when using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent]. - """ - - user_id = proto.Field( - proto.STRING, - number=1, - ) - ip_address = proto.Field( - proto.STRING, - number=2, - ) - user_agent = proto.Field( - proto.STRING, - number=3, - ) - direct_user_request = proto.Field( - proto.BOOL, - number=4, - ) - - -class LocalInventory(proto.Message): - r"""The inventory information at a place (e.g. a store) - identified by a place ID. - - Attributes: - place_id (str): - The place ID for the current set of inventory - information. - price_info (google.cloud.retail_v2.types.PriceInfo): - Product price and cost information. - - Google Merchant Center property - `price `__. - attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): - Additional local inventory attributes, for example, store - name, promotion tags, etc. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - At most 30 attributes are allowed. - - The key must be a UTF-8 encoded string with a length - limit of 32 characters. - - The key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis - or KEY_1_LIKE_THIS. - - The attribute values must be of the same type (text or - number). - - Only 1 value is allowed for each attribute. - - For text values, the length limit is 256 UTF-8 - characters. - - The attribute does not support search. The ``searchable`` - field should be unset or set to false. - - The max summed total bytes of custom attribute keys and - values per product is 5MiB. - fulfillment_types (Sequence[str]): - Input only. Supported fulfillment types. Valid fulfillment - type values include commonly used types (such as pickup in - store and same day delivery), and custom types. Customers - have to map custom types to their display names before - rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - All the elements must be distinct. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - place_id = proto.Field( - proto.STRING, - number=1, - ) - price_info = proto.Field( - proto.MESSAGE, - number=2, - message='PriceInfo', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='CustomAttribute', - ) - fulfillment_types = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py deleted file mode 100644 index 421cc1c0..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py +++ /dev/null @@ -1,229 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'CompleteQueryRequest', - 'CompleteQueryResponse', - }, -) - - -class CompleteQueryRequest(proto.Message): - r"""Auto-complete parameters. - - Attributes: - catalog (str): - Required. Catalog for which the completion is performed. - - Full resource name of catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - query (str): - Required. The query used to generate - suggestions. - The maximum number of allowed characters is 255. - visitor_id (str): - Required field. A unique identifier for tracking visitors. - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - language_codes (Sequence[str]): - The language filters applied to the output suggestions. If - set, it should contain the language of the query. If not - set, suggestions are returned without considering language - restrictions. This is the BCP-47 language code, such as - "en-US" or "sr-Latn". For more information, see `Tags for - Identifying - Languages `__. The - maximum number of language codes is 3. - device_type (str): - The device type context for completion suggestions. It is - useful to apply different suggestions on different device - types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the - suggestions are across all device types. - - Supported formats: - - - ``UNKNOWN_DEVICE_TYPE`` - - - ``DESKTOP`` - - - ``MOBILE`` - - - A customized string starts with ``OTHER_``, e.g. - ``OTHER_IPHONE``. - dataset (str): - Determines which dataset to use for fetching completion. - "user-data" will use the imported dataset through - [CompletionService.ImportCompletionData][google.cloud.retail.v2.CompletionService.ImportCompletionData]. - "cloud-retail" will use the dataset generated by cloud - retail based on user events. If leave empty, it will use the - "user-data". - - Current supported values: - - - user-data - - - cloud-retail: This option requires enabling auto-learning - function first. See - `guidelines `__. - max_suggestions (int): - Completion max suggestions. If left unset or set to 0, then - will fallback to the configured value - [CompletionConfig.max_suggestions][]. - - The maximum allowed max suggestions is 20. If it is set - higher, it will be capped by 20. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - visitor_id = proto.Field( - proto.STRING, - number=7, - ) - language_codes = proto.RepeatedField( - proto.STRING, - number=3, - ) - device_type = proto.Field( - proto.STRING, - number=4, - ) - dataset = proto.Field( - proto.STRING, - number=6, - ) - max_suggestions = proto.Field( - proto.INT32, - number=5, - ) - - -class CompleteQueryResponse(proto.Message): - r"""Response of the auto-complete query. - - Attributes: - completion_results (Sequence[google.cloud.retail_v2.types.CompleteQueryResponse.CompletionResult]): - Results of the matching suggestions. The - result list is ordered and the first result is - top suggestion. - attribution_token (str): - A unique complete token. This should be included in the - [UserEvent.completion_detail][google.cloud.retail.v2.UserEvent.completion_detail] - for search events resulting from this completion, which - enables accurate attribution of complete model performance. - recent_search_results (Sequence[google.cloud.retail_v2.types.CompleteQueryResponse.RecentSearchResult]): - Matched recent searches of this user. The maximum number of - recent searches is 10. This field is a restricted feature. - Contact Retail Search support team if you are interested in - enabling it. - - This feature is only available when - [CompleteQueryRequest.visitor_id][google.cloud.retail.v2.CompleteQueryRequest.visitor_id] - field is set and - [UserEvent][google.cloud.retail.v2.UserEvent] is imported. - The recent searches satisfy the follow rules: - - - They are ordered from latest to oldest. - - - They are matched with - [CompleteQueryRequest.query][google.cloud.retail.v2.CompleteQueryRequest.query] - case insensitively. - - - They are transformed to lower cases. - - - They are UTF-8 safe. - - Recent searches are deduplicated. More recent searches will - be reserved when duplication happens. - """ - - class CompletionResult(proto.Message): - r"""Resource that represents completion results. - - Attributes: - suggestion (str): - The suggestion for the query. - attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): - Custom attributes for the suggestion term. - - - For "user-data", the attributes are additional custom - attributes ingested through BigQuery. - - - For "cloud-retail", the attributes are product attributes - generated by Cloud Retail. This is an experimental - feature. Contact Retail Search support team if you are - interested in enabling it. - """ - - suggestion = proto.Field( - proto.STRING, - number=1, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=common.CustomAttribute, - ) - - class RecentSearchResult(proto.Message): - r"""Recent search of this user. - - Attributes: - recent_search (str): - The recent search query. - """ - - recent_search = proto.Field( - proto.STRING, - number=1, - ) - - completion_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=CompletionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - recent_search_results = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=RecentSearchResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py deleted file mode 100644 index 983e15df..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py +++ /dev/null @@ -1,697 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import user_event -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'GcsSource', - 'BigQuerySource', - 'ProductInlineSource', - 'UserEventInlineSource', - 'ImportErrorsConfig', - 'ImportProductsRequest', - 'ImportUserEventsRequest', - 'ImportCompletionDataRequest', - 'ProductInputConfig', - 'UserEventInputConfig', - 'CompletionDataInputConfig', - 'ImportMetadata', - 'ImportProductsResponse', - 'ImportUserEventsResponse', - 'UserEventImportSummary', - 'ImportCompletionDataResponse', - }, -) - - -class GcsSource(proto.Message): - r"""Google Cloud Storage location for input content. - format. - - Attributes: - input_uris (Sequence[str]): - Required. Google Cloud Storage URIs to input files. URI can - be up to 2000 characters long. URIs can match the full - object path (for example, - ``gs://bucket/directory/object.json``) or a pattern matching - one or more files, such as ``gs://bucket/directory/*.json``. - A request can contain at most 100 files, and each file can - be up to 2 GB. See `Importing product - information `__ - for the expected file format and setup instructions. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2.Product] per line. Each - product must have a valid - [Product.id][google.cloud.retail.v2.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2.UserEvent] per line. - - ``user_event_ga360``: Using - https://support.google.com/analytics/answer/3437719. - - Supported values for control imports: - - - 'control' (default): One JSON [Control][] per line. - - Supported values for catalog attribute imports: - - - 'catalog_attribute' (default): One CSV - [CatalogAttribute][] per line. - """ - - input_uris = proto.RepeatedField( - proto.STRING, - number=1, - ) - data_schema = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""BigQuery source import data from. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - partition_date (google.type.date_pb2.Date): - BigQuery time partitioned table's \_PARTITIONDATE in - YYYY-MM-DD format. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - - This field is a member of `oneof`_ ``partition``. - project_id (str): - The project ID (can be project # or ID) that - the BigQuery source is in with a length limit of - 128 characters. If not specified, inherits the - project ID from the parent request. - dataset_id (str): - Required. The BigQuery data set to copy the - data from with a length limit of 1,024 - characters. - table_id (str): - Required. The BigQuery table to copy the data - from with a length limit of 1,024 characters. - gcs_staging_dir (str): - Intermediate Cloud Storage directory used for - the import with a length limit of 2,000 - characters. Can be specified if one wants to - have the BigQuery export to a specific Cloud - Storage directory. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2.Product] per line. Each - product must have a valid - [Product.id][google.cloud.retail.v2.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2.UserEvent] per line. - - ``user_event_ga360``: The schema is available here: - https://support.google.com/analytics/answer/3437719. - - ``user_event_ga4``: This feature is in private preview. - Please contact the support team for importing Google - Analytics 4 events. The schema is available here: - https://support.google.com/analytics/answer/7029846. - - Supported values for auto-completion imports: - - - ``suggestions`` (default): One JSON completion suggestion - per line. - - ``denylist``: One JSON deny suggestion per line. - - ``allowlist``: One JSON allow suggestion per line. - """ - - partition_date = proto.Field( - proto.MESSAGE, - number=6, - oneof='partition', - message=date_pb2.Date, - ) - project_id = proto.Field( - proto.STRING, - number=5, - ) - dataset_id = proto.Field( - proto.STRING, - number=1, - ) - table_id = proto.Field( - proto.STRING, - number=2, - ) - gcs_staging_dir = proto.Field( - proto.STRING, - number=3, - ) - data_schema = proto.Field( - proto.STRING, - number=4, - ) - - -class ProductInlineSource(proto.Message): - r"""The inline source for the input config for ImportProducts - method. - - Attributes: - products (Sequence[google.cloud.retail_v2.types.Product]): - Required. A list of products to update/create. Each product - must have a valid - [Product.id][google.cloud.retail.v2.Product.id]. Recommended - max of 100 items. - """ - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=product.Product, - ) - - -class UserEventInlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (Sequence[google.cloud.retail_v2.types.UserEvent]): - Required. A list of user events to import. - Recommended max of 10k items. - """ - - user_events = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - -class ImportErrorsConfig(proto.Message): - r"""Configuration of destination for Import related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage prefix for import errors. This must be - an empty, existing Cloud Storage directory. Import errors - will be written to sharded files in this directory, one per - line, as a JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportProductsRequest(proto.Message): - r"""Request message for Import methods. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` - - If no updateMask is specified, requires products.create - permission. If updateMask is specified, requires - products.update permission. - request_id (str): - Deprecated. This field has no effect. - input_config (google.cloud.retail_v2.types.ProductInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - imported 'products' to update. If not set, will - by default update all fields. - reconciliation_mode (google.cloud.retail_v2.types.ImportProductsRequest.ReconciliationMode): - The mode of reconciliation between existing products and the - products to be imported. Defaults to - [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. - notification_pubsub_topic (str): - Full Pub/Sub topic name for receiving notification. If this - field is set, when the import is finished, a notification - will be sent to specified Pub/Sub topic. The message data - will be JSON string of a - [Operation][google.longrunning.Operation]. - - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. It has to be within - the same project as - [ImportProductsRequest.parent][google.cloud.retail.v2.ImportProductsRequest.parent]. - Make sure that both - ``cloud-retail-customer-data-access@system.gserviceaccount.com`` - and - ``service-@gcp-sa-retail.iam.gserviceaccount.com`` - have the ``pubsub.topics.publish`` IAM permission on the - topic. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - """ - class ReconciliationMode(proto.Enum): - r"""Indicates how imported products are reconciled with the - existing products created or imported before. - """ - RECONCILIATION_MODE_UNSPECIFIED = 0 - INCREMENTAL = 1 - FULL = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - request_id = proto.Field( - proto.STRING, - number=6, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='ProductInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - reconciliation_mode = proto.Field( - proto.ENUM, - number=5, - enum=ReconciliationMode, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=7, - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog`` - input_config (google.cloud.retail_v2.types.UserEventInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. Cannot be set for inline user - event imports. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='UserEventInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - - -class ImportCompletionDataRequest(proto.Message): - r"""Request message for ImportCompletionData methods. - - Attributes: - parent (str): - Required. The catalog which the suggestions dataset belongs - to. - - Format: - ``projects/1234/locations/global/catalogs/default_catalog``. - input_config (google.cloud.retail_v2.types.CompletionDataInputConfig): - Required. The desired input location of the - data. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='CompletionDataInputConfig', - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=3, - ) - - -class ProductInputConfig(proto.Message): - r"""The input config source for products. - - 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: - product_inline_source (google.cloud.retail_v2.types.ProductInlineSource): - The Inline source for the input content for - products. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2.types.GcsSource): - Google Cloud Storage location for the input - content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - product_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='ProductInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class UserEventInputConfig(proto.Message): - r"""The input config source for user events. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - user_event_inline_source (google.cloud.retail_v2.types.UserEventInlineSource): - Required. The Inline source for the input - content for UserEvents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2.types.GcsSource): - Required. Google Cloud Storage location for - the input content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2.types.BigQuerySource): - Required. BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - user_event_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='UserEventInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class CompletionDataInputConfig(proto.Message): - r"""The input config source for completion data. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - big_query_source (google.cloud.retail_v2.types.BigQuerySource): - Required. BigQuery input source. - Add the IAM permission "BigQuery Data Viewer" - for - cloud-retail-customer-data-access@system.gserviceaccount.com - before using this feature otherwise an error is - thrown. - - This field is a member of `oneof`_ ``source``. - """ - - big_query_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='BigQuerySource', - ) - - -class ImportMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - request_id (str): - Deprecated. This field is never set. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=3, - ) - failure_count = proto.Field( - proto.INT64, - number=4, - ) - request_id = proto.Field( - proto.STRING, - number=5, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=6, - ) - - -class ImportProductsResponse(proto.Message): - r"""Response of the - [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. - If the long running operation is done, then this message is returned - by the google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - import_summary (google.cloud.retail_v2.types.UserEventImportSummary): - Aggregated statistics of user event import - status. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - import_summary = proto.Field( - proto.MESSAGE, - number=3, - message='UserEventImportSummary', - ) - - -class UserEventImportSummary(proto.Message): - r"""A summary of import result. The UserEventImportSummary - summarizes the import status for user events. - - Attributes: - joined_events_count (int): - Count of user events imported with complete - existing catalog information. - unjoined_events_count (int): - Count of user events imported, but with - catalog information not found in the imported - catalog. - """ - - joined_events_count = proto.Field( - proto.INT64, - number=1, - ) - unjoined_events_count = proto.Field( - proto.INT64, - number=2, - ) - - -class ImportCompletionDataResponse(proto.Message): - r"""Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. - 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 (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py deleted file mode 100644 index 68e8c74b..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py +++ /dev/null @@ -1,275 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import user_event as gcr_user_event -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'PredictRequest', - 'PredictResponse', - }, -) - - -class PredictRequest(proto.Message): - r"""Request message for Predict method. - - Attributes: - placement (str): - Required. Full resource name of the format: - {name=projects/*/locations/global/catalogs/default_catalog/placements/*} - The ID of the Recommendations AI placement. Before you can - request predictions from your model, you must create at - least one placement for it. For more information, see - `Managing - placements `__. - - The full list of available placements can be seen at - https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements - user_event (google.cloud.retail_v2.types.UserEvent): - Required. Context about the user, what they are looking at - and what action they took to trigger the predict request. - Note that this user event detail won't be ingested to - userEvent logs. Thus, a separate userEvent write request is - required for event logging. - - Don't set - [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] - or - [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] - to the same fixed ID for different users. If you are trying - to receive non-personalized recommendations (not - recommended; this can negatively impact model performance), - instead set - [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] - to a random unique ID and leave - [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] - unset. - page_size (int): - Maximum number of results to return per page. - Set this property to the number of prediction - results needed. If zero, the service will choose - a reasonable default. The maximum allowed value - is 100. Values above 100 will be coerced to 100. - page_token (str): - The previous PredictResponse.next_page_token. - filter (str): - Filter for restricting prediction results with a length - limit of 5,000 characters. Accepts values for tags and the - ``filterOutOfStockItems`` flag. - - - Tag expressions. Restricts predictions to products that - match all of the specified tags. Boolean operators ``OR`` - and ``NOT`` are supported if the expression is enclosed - in parentheses, and must be separated from the tag values - by a space. ``-"tagA"`` is also supported and is - equivalent to ``NOT "tagA"``. Tag values must be double - quoted UTF-8 encoded strings with a size limit of 1,000 - characters. - - Note: "Recently viewed" models don't support tag - filtering at the moment. - - - filterOutOfStockItems. Restricts predictions to products - that do not have a stockState value of OUT_OF_STOCK. - - Examples: - - - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT - "promotional") - - filterOutOfStockItems tag=(-"promotional") - - filterOutOfStockItems - - If your filter blocks all prediction results, the API will - return generic (unfiltered) popular products. If you only - want results strictly matching the filters, set - ``strictFiltering`` to True in ``PredictRequest.params`` to - receive empty results instead. Note that the API will never - return items with storageStatus of "EXPIRED" or "DELETED" - regardless of filter choices. - validate_only (bool): - Use validate only mode for this prediction - query. If set to true, a dummy model will be - used that returns arbitrary products. Note that - the validate only mode should only be used for - testing the API, or if the model is not ready. - params (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional domain specific parameters for the predictions. - - Allowed values: - - - ``returnProduct``: Boolean. If set to true, the - associated product object will be returned in the - ``results.metadata`` field in the prediction response. - - ``returnScore``: Boolean. If set to true, the prediction - 'score' corresponding to each returned product will be - set in the ``results.metadata`` field in the prediction - response. The given 'score' indicates the probability of - an product being clicked/purchased given the user's - context and history. - - ``strictFiltering``: Boolean. True by default. If set to - false, the service will return generic (unfiltered) - popular products instead of empty if your filter blocks - all prediction results. - - ``priceRerankLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of - {'no-price-reranking', 'low-price-reranking', - 'medium-price-reranking', 'high-price-reranking'}. This - gives request-level control and adjusts prediction - results based on product price. - - ``diversityLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of {'no-diversity', - 'low-diversity', 'medium-diversity', 'high-diversity', - 'auto-diversity'}. This gives request-level control and - adjusts prediction results based on product category. - labels (Mapping[str, str]): - The labels applied to a resource must meet the following - requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - """ - - placement = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - validate_only = proto.Field( - proto.BOOL, - number=6, - ) - params = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class PredictResponse(proto.Message): - r"""Response message for predict method. - - Attributes: - results (Sequence[google.cloud.retail_v2.types.PredictResponse.PredictionResult]): - A list of recommended products. The order - represents the ranking (from the most relevant - product to the least). - attribution_token (str): - A unique attribution token. This should be included in the - [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting - from this recommendation, which enables accurate attribution - of recommendation model performance. - missing_ids (Sequence[str]): - IDs of products in the request that were - missing from the inventory. - validate_only (bool): - True if the validateOnly property was set in - the request. - """ - - class PredictionResult(proto.Message): - r"""PredictionResult represents the recommendation prediction - results. - - Attributes: - id (str): - ID of the recommended product - metadata (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional product metadata / annotations. - - Possible values: - - - ``product``: JSON representation of the product. Is set - if ``returnProduct`` is set to true in - ``PredictRequest.params``. - - ``score``: Prediction score in double value. Is set if - ``returnScore`` is set to true in - ``PredictRequest.params``. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - metadata = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=PredictionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - missing_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py deleted file mode 100644 index bff41d83..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py +++ /dev/null @@ -1,701 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'Product', - }, -) - - -class Product(proto.Message): - r"""Product captures all metadata information of items to be - recommended or searched. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this product becomes unavailable for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - - If it is set, the [Product][google.cloud.retail.v2.Product] - is not available for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - after - [expire_time][google.cloud.retail.v2.Product.expire_time]. - However, the product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - [expire_time][google.cloud.retail.v2.Product.expire_time] - must be later than - [available_time][google.cloud.retail.v2.Product.available_time] - and - [publish_time][google.cloud.retail.v2.Product.publish_time], - otherwise an INVALID_ARGUMENT error is thrown. - - Corresponding properties: Google Merchant Center property - `expiration_date `__. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Input only. The TTL (time to live) of the product. - - If it is set, it must be a non-negative value, and - [expire_time][google.cloud.retail.v2.Product.expire_time] is - set as current timestamp plus - [ttl][google.cloud.retail.v2.Product.ttl]. The derived - [expire_time][google.cloud.retail.v2.Product.expire_time] is - returned in the output and - [ttl][google.cloud.retail.v2.Product.ttl] is left blank when - retrieving the [Product][google.cloud.retail.v2.Product]. - - If it is set, the product is not available for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - after current timestamp plus - [ttl][google.cloud.retail.v2.Product.ttl]. However, the - product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This field is a member of `oneof`_ ``expiration``. - name (str): - Immutable. Full resource name of the product, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. - id (str): - Immutable. [Product][google.cloud.retail.v2.Product] - identifier, which is the final component of - [name][google.cloud.retail.v2.Product.name]. For example, - this field is "id_1", if - [name][google.cloud.retail.v2.Product.name] is - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `id `__. - Schema.org property - `Product.sku `__. - type_ (google.cloud.retail_v2.types.Product.Type): - Immutable. The type of the product. Default to - [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] - if unset. - primary_product_id (str): - Variant group identifier. Must be an - [id][google.cloud.retail.v2.Product.id], with the same - parent branch with this product. Otherwise, an error is - thrown. - - For - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]s, this field can - only be empty or set to the same value as - [id][google.cloud.retail.v2.Product.id]. - - For VARIANT [Product][google.cloud.retail.v2.Product]s, this - field cannot be empty. A maximum of 2,000 products are - allowed to share the same - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `item_group_id `__. - Schema.org property - `Product.inProductGroupWithID `__. - collection_member_ids (Sequence[str]): - The [id][google.cloud.retail.v2.Product.id] of the - collection members when - [type][google.cloud.retail.v2.Product.type] is - [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]. - - Non-existent product ids are allowed. The - [type][google.cloud.retail.v2.Product.type] of the members - must be either - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - or - [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - otherwise and INVALID_ARGUMENT error is thrown. Should not - set it for other types. A maximum of 1000 values are - allowed. Otherwise, an INVALID_ARGUMENT error is return. - gtin (str): - The Global Trade Item Number (GTIN) of the product. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This field must be a Unigram. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `gtin `__. - Schema.org property - `Product.isbn `__, - `Product.gtin8 `__, - `Product.gtin12 `__, - `Product.gtin13 `__, or - `Product.gtin14 `__. - - If the value is not a valid GTIN, an INVALID_ARGUMENT error - is returned. - categories (Sequence[str]): - Product categories. This field is repeated for supporting - one product belonging to several parallel categories. - Strongly recommended using the full path for better search / - recommendation quality. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - For example, if a shoes product belongs to both ["Shoes & - Accessories" -> "Shoes"] and ["Sports & Fitness" -> - "Athletic Clothing" -> "Shoes"], it could be represented as: - - :: - - "categories": [ - "Shoes & Accessories > Shoes", - "Sports & Fitness > Athletic Clothing > Shoes" - ] - - Must be set for - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] otherwise an - INVALID_ARGUMENT error is returned. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2.Product]. Empty values are - not allowed. Each value must be a UTF-8 encoded string with - a length limit of 5,000 characters. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `google_product_category `__. - Schema.org property [Product.category] - (https://schema.org/category). - title (str): - Required. Product title. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `title `__. - Schema.org property - `Product.name `__. - brands (Sequence[str]): - The brands of the product. - - A maximum of 30 brands are allowed. Each brand must be a - UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `brand `__. - Schema.org property - `Product.brand `__. - description (str): - Product description. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `description `__. - Schema.org property - `Product.description `__. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. - - For product prediction, this field is ignored and the model - automatically detects the text language. The - [Product][google.cloud.retail.v2.Product] can include text - in different languages, but duplicating - [Product][google.cloud.retail.v2.Product]s to provide text - in multiple languages can result in degraded model - performance. - - For product search this field is in use. It defaults to - "en-US" if unset. - attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): - Highly encouraged. Extra product attributes to be included. - For example, for products, this could include the store - name, vendor, style, color, etc. These are very strong - signals for recommendation model, thus we highly recommend - providing the attributes here. - - Features that can take on one of a limited number of - possible values. Two types of features can be set are: - - Textual features. some examples would be the brand/maker of - a product, or country of a customer. Numerical features. - Some examples would be the height/weight of a product, or - age of a customer. - - For example: - ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - Max entries count: 200. - - The key must be a UTF-8 encoded string with a length - limit of 128 characters. - - For indexable attribute, the key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, - ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a - non-empty UTF-8 encoded string with a length limit of 256 - characters. - - For number attributes, at most 400 values are allowed. - tags (Sequence[str]): - Custom tags associated with the product. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2.Product]. This value must - be a UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This tag can be used for filtering recommendation results by - passing the tag as part of the - [PredictRequest.filter][google.cloud.retail.v2.PredictRequest.filter]. - - Corresponding properties: Google Merchant Center property - `custom_label_0–4 `__. - price_info (google.cloud.retail_v2.types.PriceInfo): - Product price and cost information. - - Corresponding properties: Google Merchant Center property - `price `__. - rating (google.cloud.retail_v2.types.Rating): - The rating of this product. - available_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this - [Product][google.cloud.retail.v2.Product] becomes available - for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - availability (google.cloud.retail_v2.types.Product.Availability): - The online availability of the - [Product][google.cloud.retail.v2.Product]. Default to - [Availability.IN_STOCK][google.cloud.retail.v2.Product.Availability.IN_STOCK]. - - Corresponding properties: Google Merchant Center property - `availability `__. - Schema.org property - `Offer.availability `__. - available_quantity (google.protobuf.wrappers_pb2.Int32Value): - The available quantity of the item. - fulfillment_info (Sequence[google.cloud.retail_v2.types.FulfillmentInfo]): - Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - All the elements must have distinct - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type]. - Otherwise, an INVALID_ARGUMENT error is returned. - uri (str): - Canonical URL directly linking to the product detail page. - - It is strongly recommended to provide a valid uri for the - product, otherwise the service performance could be - significantly degraded. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `link `__. - Schema.org property `Offer.url `__. - images (Sequence[google.cloud.retail_v2.types.Image]): - Product images for the product. We highly recommend putting - the main image first. - - A maximum of 300 images are allowed. - - Corresponding properties: Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - audience (google.cloud.retail_v2.types.Audience): - The target group associated with a given - audience (e.g. male, veterans, car owners, - musicians, etc.) of the product. - color_info (google.cloud.retail_v2.types.ColorInfo): - The color of the product. - - Corresponding properties: Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - sizes (Sequence[str]): - The size of the product. To represent different size systems - or size types, consider using this format: - [[[size_system:]size_type:]size_value]. - - For example, in "US:MENS:M", "US" represents size system; - "MENS" represents size type; "M" represents size value. In - "GIRLS:27", size system is empty; "GIRLS" represents size - type; "27" represents size value. In "32 inches", both size - system and size type are empty, while size value is "32 - inches". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2.Product]. Each value must - be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `size `__, - `size_type `__, - and - `size_system `__. - Schema.org property - `Product.size `__. - materials (Sequence[str]): - The material of the product. For example, "leather", - "wooden". - - A maximum of 20 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 200 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `material `__. - Schema.org property - `Product.material `__. - patterns (Sequence[str]): - The pattern or graphic print of the product. For example, - "striped", "polka dot", "paisley". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2.Product]. Each value must - be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `pattern `__. - Schema.org property - `Product.pattern `__. - conditions (Sequence[str]): - The condition of the product. Strongly encouraged to use the - standard values: "new", "refurbished", "used". - - A maximum of 1 value is allowed per - [Product][google.cloud.retail.v2.Product]. Each value must - be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `condition `__. - Schema.org property - `Offer.itemCondition `__. - promotions (Sequence[google.cloud.retail_v2.types.Promotion]): - The promotions applied to the product. A maximum of 10 - values are allowed per - [Product][google.cloud.retail.v2.Product]. Only - [Promotion.promotion_id][google.cloud.retail.v2.Promotion.promotion_id] - will be used, other fields will be ignored if set. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the product is published by the retailer - for the first time, which indicates the freshness of the - products. Note that this field is different from - [available_time][google.cloud.retail.v2.Product.available_time], - given it purely describes product freshness regardless of - when it is available on search and recommendation. - retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the - [Product][google.cloud.retail.v2.Product]s are returned in - [SearchResponse][google.cloud.retail.v2.SearchResponse]. - - Supported fields for all - [type][google.cloud.retail.v2.Product.type]s: - - - [audience][google.cloud.retail.v2.Product.audience] - - [availability][google.cloud.retail.v2.Product.availability] - - [brands][google.cloud.retail.v2.Product.brands] - - [color_info][google.cloud.retail.v2.Product.color_info] - - [conditions][google.cloud.retail.v2.Product.conditions] - - [gtin][google.cloud.retail.v2.Product.gtin] - - [materials][google.cloud.retail.v2.Product.materials] - - [name][google.cloud.retail.v2.Product.name] - - [patterns][google.cloud.retail.v2.Product.patterns] - - [price_info][google.cloud.retail.v2.Product.price_info] - - [rating][google.cloud.retail.v2.Product.rating] - - [sizes][google.cloud.retail.v2.Product.sizes] - - [title][google.cloud.retail.v2.Product.title] - - [uri][google.cloud.retail.v2.Product.uri] - - Supported fields only for - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]: - - - [categories][google.cloud.retail.v2.Product.categories] - - [description][google.cloud.retail.v2.Product.description] - - [images][google.cloud.retail.v2.Product.images] - - Supported fields only for - [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT]: - - - Only the first image in - [images][google.cloud.retail.v2.Product.images] - - To mark - [attributes][google.cloud.retail.v2.Product.attributes] as - retrievable, include paths of the form "attributes.key" - where "key" is the key of a custom attribute, as specified - in [attributes][google.cloud.retail.v2.Product.attributes]. - - For - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION], - the following fields are always returned in - [SearchResponse][google.cloud.retail.v2.SearchResponse] by - default: - - - [name][google.cloud.retail.v2.Product.name] - - For - [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT], - the following fields are always returned in by default: - - - [name][google.cloud.retail.v2.Product.name] - - [color_info][google.cloud.retail.v2.Product.color_info] - - The maximum number of paths is 30. Otherwise, an - INVALID_ARGUMENT error is returned. - - Note: Returning more fields in - [SearchResponse][google.cloud.retail.v2.SearchResponse] can - increase response payload size and serving latency. - variants (Sequence[google.cloud.retail_v2.types.Product]): - Output only. Product variants grouped together on primary - product which share similar product attributes. It's - automatically grouped by - [primary_product_id][google.cloud.retail.v2.Product.primary_product_id] - for all the product variants. Only populated for - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]. - Do not set this field in API requests. - """ - class Type(proto.Enum): - r"""The type of this product.""" - TYPE_UNSPECIFIED = 0 - PRIMARY = 1 - VARIANT = 2 - COLLECTION = 3 - - class Availability(proto.Enum): - r"""Product availability. If this field is unspecified, the - product is assumed to be in stock. - """ - AVAILABILITY_UNSPECIFIED = 0 - IN_STOCK = 1 - OUT_OF_STOCK = 2 - PREORDER = 3 - BACKORDER = 4 - - expire_time = proto.Field( - proto.MESSAGE, - number=16, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl = proto.Field( - proto.MESSAGE, - number=17, - oneof='expiration', - message=duration_pb2.Duration, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - type_ = proto.Field( - proto.ENUM, - number=3, - enum=Type, - ) - primary_product_id = proto.Field( - proto.STRING, - number=4, - ) - collection_member_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - gtin = proto.Field( - proto.STRING, - number=6, - ) - categories = proto.RepeatedField( - proto.STRING, - number=7, - ) - title = proto.Field( - proto.STRING, - number=8, - ) - brands = proto.RepeatedField( - proto.STRING, - number=9, - ) - description = proto.Field( - proto.STRING, - number=10, - ) - language_code = proto.Field( - proto.STRING, - number=11, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=12, - message=common.CustomAttribute, - ) - tags = proto.RepeatedField( - proto.STRING, - number=13, - ) - price_info = proto.Field( - proto.MESSAGE, - number=14, - message=common.PriceInfo, - ) - rating = proto.Field( - proto.MESSAGE, - number=15, - message=common.Rating, - ) - available_time = proto.Field( - proto.MESSAGE, - number=18, - message=timestamp_pb2.Timestamp, - ) - availability = proto.Field( - proto.ENUM, - number=19, - enum=Availability, - ) - available_quantity = proto.Field( - proto.MESSAGE, - number=20, - message=wrappers_pb2.Int32Value, - ) - fulfillment_info = proto.RepeatedField( - proto.MESSAGE, - number=21, - message=common.FulfillmentInfo, - ) - uri = proto.Field( - proto.STRING, - number=22, - ) - images = proto.RepeatedField( - proto.MESSAGE, - number=23, - message=common.Image, - ) - audience = proto.Field( - proto.MESSAGE, - number=24, - message=common.Audience, - ) - color_info = proto.Field( - proto.MESSAGE, - number=25, - message=common.ColorInfo, - ) - sizes = proto.RepeatedField( - proto.STRING, - number=26, - ) - materials = proto.RepeatedField( - proto.STRING, - number=27, - ) - patterns = proto.RepeatedField( - proto.STRING, - number=28, - ) - conditions = proto.RepeatedField( - proto.STRING, - number=29, - ) - promotions = proto.RepeatedField( - proto.MESSAGE, - number=34, - message=promotion.Promotion, - ) - publish_time = proto.Field( - proto.MESSAGE, - number=33, - message=timestamp_pb2.Timestamp, - ) - retrievable_fields = proto.Field( - proto.MESSAGE, - number=30, - message=field_mask_pb2.FieldMask, - ) - variants = proto.RepeatedField( - proto.MESSAGE, - number=31, - message='Product', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py deleted file mode 100644 index ce4d5c3e..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py +++ /dev/null @@ -1,858 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'CreateProductRequest', - 'GetProductRequest', - 'UpdateProductRequest', - 'DeleteProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'SetInventoryRequest', - 'SetInventoryMetadata', - 'SetInventoryResponse', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesResponse', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesResponse', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesResponse', - }, -) - - -class CreateProductRequest(proto.Message): - r"""Request message for [CreateProduct][] method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - product (google.cloud.retail_v2.types.Product): - Required. The [Product][google.cloud.retail.v2.Product] to - create. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2.Product], which will become - the final component of the - [Product.name][google.cloud.retail.v2.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2.Product]s with the same - [parent][google.cloud.retail.v2.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - product_id = proto.Field( - proto.STRING, - number=3, - ) - - -class GetProductRequest(proto.Message): - r"""Request message for [GetProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested [Product][google.cloud.retail.v2.Product] - does not exist, a NOT_FOUND error is returned. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateProductRequest(proto.Message): - r"""Request message for [UpdateProduct][] method. - - Attributes: - product (google.cloud.retail_v2.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to update - does not exist and - [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Product][google.cloud.retail.v2.Product] to update. The - immutable and output only fields are NOT supported. If not - set, all supported fields (the fields that are neither - immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - The attribute key can be updated by setting the mask path as - "attributes.${key_name}". If a key name is present in the - mask but not in the patching product from the request, this - key will be deleted after the update. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, a - new [Product][google.cloud.retail.v2.Product] will be - created. In this situation, ``update_mask`` is ignored. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteProductRequest(proto.Message): - r"""Request message for [DeleteProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to delete - does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2.Product] to delete can - neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] with more than one - [variants][google.cloud.retail.v2.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2.Product] will be deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProductsRequest(proto.Message): - r"""Request message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - - Attributes: - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list products - under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2.Product]s under this - branch, regardless of whether or not this branch exists, a - PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of [Product][google.cloud.retail.v2.Product]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 - [ListProductsResponse.next_page_token][google.cloud.retail.v2.ListProductsResponse.next_page_token], - received from a previous - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - filter (str): - A filter to apply on the list results. Supported features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2.ListProductsRequest.filter] - is unset. - - List - [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s sharing the - same - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]. For example: - ``primary_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2.Product]s bundled - in a - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product]. For example: - ``collection_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2.Product]s with a - partibular type. For example: ``type = "PRIMARY"`` - ``type = "VARIANT"`` ``type = "COLLECTION"`` - - If the field is unrecognizable, an INVALID_ARGUMENT error is - returned. - - If the specified - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] or - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product] does not exist, a - NOT_FOUND error is returned. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields of [Product][google.cloud.retail.v2.Product] to - return in the responses. If not set or empty, the following - fields are returned: - - - [Product.name][google.cloud.retail.v2.Product.name] - - [Product.id][google.cloud.retail.v2.Product.id] - - [Product.title][google.cloud.retail.v2.Product.title] - - [Product.uri][google.cloud.retail.v2.Product.uri] - - [Product.images][google.cloud.retail.v2.Product.images] - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.brands][google.cloud.retail.v2.Product.brands] - - If "*" is provided, all fields are returned. - [Product.name][google.cloud.retail.v2.Product.name] is - always returned no matter what mask is set. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class ListProductsResponse(proto.Message): - r"""Response message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - - Attributes: - products (Sequence[google.cloud.retail_v2.types.Product]): - The [Product][google.cloud.retail.v2.Product]s. - next_page_token (str): - A token that can be sent as - [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class SetInventoryRequest(proto.Message): - r"""Request message for [SetInventory][] method. - - Attributes: - inventory (google.cloud.retail_v2.types.Product): - Required. The inventory information to update. The allowable - fields to update are: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product] named in - [Product.name][google.cloud.retail.v2.Product.name], - regardless of whether or not it exists, a PERMISSION_DENIED - error is returned. - - If the [Product][google.cloud.retail.v2.Product] to update - does not have existing inventory information, the provided - inventory information will be inserted. - - If the [Product][google.cloud.retail.v2.Product] to update - has existing inventory information, the provided inventory - information will be merged while respecting the last update - time for each inventory field, using the provided or default - value for - [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of fulfillment - types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear in - [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types have - empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following inventory - fields: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - - If a full overwrite of inventory information while ignoring - timestamps is needed, [UpdateProduct][] should be invoked - instead. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the request is issued, used to - prevent out-of-order updates on inventory fields - with the last update time recorded. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] with name - [Product.name][google.cloud.retail.v2.Product.name] is not - found, the inventory update will still be processed and - retained for at most 1 day until the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - inventory = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - set_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - set_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=4, - ) - - -class SetInventoryMetadata(proto.Message): - r"""Metadata related to the progress of the SetInventory operation. - Currently empty because there is no meaningful metadata populated - from the [SetInventory][] method. - - """ - - -class SetInventoryResponse(proto.Message): - r"""Response of the SetInventoryRequest. Currently empty because there - is no meaningful response populated from the [SetInventory][] - method. - - """ - - -class AddFulfillmentPlacesRequest(proto.Message): - r"""Request message for - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery" to be added for this - [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type]. - Duplicate IDs will be automatically ignored. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If the total number of place IDs exceeds 2000 for this - [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type] - after adding, then the update will be rejected. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, the - fulfillment information will still be processed and retained - for at most 1 day and processed once the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - add_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class AddFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the AddFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - """ - - -class AddFulfillmentPlacesResponse(proto.Message): - r"""Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - """ - - -class AddLocalInventoriesRequest(proto.Message): - r"""Request message for - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - local_inventories (Sequence[google.cloud.retail_v2.types.LocalInventory]): - Required. A list of inventory information at - difference places. Each place is identified by - its place ID. At most 3000 inventories are - allowed per request. - add_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided list of - [LocalInventory][google.cloud.retail.v2.LocalInventory] to - update. The field is updated to the provided value. - - If a field is set while the place does not have a previous - local inventory, the local inventory at that store is - created. - - If a field is set while the value of that field is not - provided, the original field value, if it exists, is - deleted. - - If the mask is not set or set with empty paths, all - inventory fields will be updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory updates are - issued. Used to prevent out-of-order updates on - local inventory fields. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, the - local inventory will still be processed and retained for at - most 1 day and processed once the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - local_inventories = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.LocalInventory, - ) - add_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - add_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=6, - ) - - -class AddLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the AddLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - """ - - -class AddLocalInventoriesResponse(proto.Message): - r"""Response of the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - API. Currently empty because there is no meaningful response - populated from the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - """ - - -class RemoveLocalInventoriesRequest(proto.Message): - r"""Request message for [RemoveLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - place_ids (Sequence[str]): - Required. A list of place IDs to have their - inventory deleted. At most 3000 place IDs are - allowed per request. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory deletions are - issued. Used to prevent out-of-order updates and - deletions on local inventory fields. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, the - local inventory removal request will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class RemoveLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesResponse(proto.Message): - r"""Response of the [RemoveLocalInventories][] API. Currently empty - because there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - - -class RemoveFulfillmentPlacesRequest(proto.Message): - r"""Request message for [RemoveFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][google.cloud.retail.v2.FulfillmentInfo.type]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery", to be removed for this - [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type]. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, the - fulfillment information will still be processed and retained - for at most 1 day and processed once the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class RemoveFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveFulfillmentPlaces][] method. - - """ - - -class RemoveFulfillmentPlacesResponse(proto.Message): - r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty - because there is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py deleted file mode 100644 index e8d80a4e..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'Promotion', - }, -) - - -class Promotion(proto.Message): - r"""Promotion information. - - Attributes: - promotion_id (str): - ID of the promotion. For example, "free gift". - - The value must be a UTF-8 encoded string with a length limit - of 128 characters, and match the pattern: - ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or - ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is - returned. - - Google Merchant Center property - `promotion `__. - """ - - promotion_id = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py deleted file mode 100644 index b8159aa6..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py +++ /dev/null @@ -1,107 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - }, -) - - -class PurgeMetadata(proto.Message): - r"""Metadata related to the progress of the Purge operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - """ - - -class PurgeUserEventsRequest(proto.Message): - r"""Request message for PurgeUserEvents method. - - Attributes: - parent (str): - Required. The resource name of the catalog under which the - events are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}`` - filter (str): - Required. The filter string to specify the events to be - deleted with a length limit of 5,000 characters. Empty - string filter is not allowed. The eligible fields for - filtering are: - - - ``eventType``: Double quoted - [UserEvent.event_type][google.cloud.retail.v2.UserEvent.event_type] - string. - - ``eventTime``: in ISO 8601 "zulu" format. - - ``visitorId``: Double quoted string. Specifying this will - delete all events associated with a visitor. - - ``userId``: Double quoted string. Specifying this will - delete all events associated with a user. - - Examples: - - - Deleting all events in a time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - - Deleting specific eventType in time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` - - Deleting all events for a specific visitor: - ``visitorId = "visitor1024"`` - - The filtering fields are assumed to have an implicit AND. - force (bool): - Actually perform the purge. If ``force`` is set to false, - the method will return the expected purge count without - deleting any user events. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeUserEventsResponse(proto.Message): - r"""Response of the PurgeUserEventsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purged_events_count (int): - The total count of events purged as a result - of the operation. - """ - - purged_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py deleted file mode 100644 index e6274278..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py +++ /dev/null @@ -1,1150 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'SearchRequest', - 'SearchResponse', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - - Attributes: - placement (str): - Required. The resource name of the search engine placement, - such as - ``projects/*/locations/global/catalogs/default_catalog/placements/default_search``. - This field is used to identify the serving configuration - name and the set of models that will be used to make the - search. - branch (str): - The branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - - Use "default_branch" as the branch ID or leave this field - empty, to search products under the default branch. - query (str): - Raw search query. - - If this field is empty, the request is considered a category - browsing request and returned results are based on - [filter][google.cloud.retail.v2.SearchRequest.filter] and - [page_categories][google.cloud.retail.v2.SearchRequest.page_categories]. - visitor_id (str): - Required. A unique identifier for tracking visitors. For - example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - This should be the same identifier as - [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id]. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2.types.UserInfo): - User information. - page_size (int): - Maximum number of [Product][google.cloud.retail.v2.Product]s - to return. If unspecified, defaults to a reasonable value. - The maximum allowed value is 120. Values above 120 will be - coerced to 120. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [SearchResponse.next_page_token][google.cloud.retail.v2.SearchResponse.next_page_token], - received from a previous - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - offset (int): - A 0-indexed integer that specifies the current offset (that - is, starting result location, amongst the - [Product][google.cloud.retail.v2.Product]s deemed by the API - as relevant) in search results. This field is only - considered if - [page_token][google.cloud.retail.v2.SearchRequest.page_token] - is unset. - - If this field is negative, an INVALID_ARGUMENT is returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. Filter expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - canonical_filter (str): - The default filter that is applied when a user performs a - search without checking any filters on the search page. - - The filter applied to every search request when quality - improvement such as query expansion is needed. For example, - if a query does not have enough results, an expanded query - with - [SearchRequest.canonical_filter][google.cloud.retail.v2.SearchRequest.canonical_filter] - will be returned as a supplement of the original query. This - field is strongly recommended to achieve high search - quality. - - See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] - for more details about filter syntax. - order_by (str): - The order in which products are returned. Products can be - ordered by a field in an - [Product][google.cloud.retail.v2.Product] object. Leave it - unset if ordered by relevance. OrderBy expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - facet_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.FacetSpec]): - Facet specifications for faceted search. If empty, no facets - are returned. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - dynamic_facet_spec (google.cloud.retail_v2.types.SearchRequest.DynamicFacetSpec): - Deprecated. Refer to - https://cloud.google.com/retail/docs/configs#dynamic - to enable dynamic facets. Do not set this field. - The specification for dynamically generated - facets. Notice that only textual facets can be - dynamically generated. - boost_spec (google.cloud.retail_v2.types.SearchRequest.BoostSpec): - Boost specification to boost certain products. See more - details at this `user - guide `__. - - Notice that if both [ServingConfig.boost_control_ids][] and - [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] - are set, the boost conditions from both places are - evaluated. If a search request matches multiple boost - conditions, the final boost score is equal to the sum of the - boost scores from all matched boost conditions. - query_expansion_spec (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec): - The query expansion specification that specifies the - conditions under which query expansion will occur. See more - details at this `user - guide `__. - variant_rollup_keys (Sequence[str]): - The keys to fetch and rollup the matching - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s attributes, - [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo] or - [LocalInventory][google.cloud.retail.v2.LocalInventory]s - attributes. The attributes from all the matching - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s or - [LocalInventory][google.cloud.retail.v2.LocalInventory]s are - merged and de-duplicated. Notice that rollup attributes will - lead to extra query latency. Maximum number of keys is 30. - - For - [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], a - fulfillment type and a fulfillment ID must be provided in - the format of "fulfillmentType.fulfillmentId". E.g., in - "pickupInStore.store123", "pickupInStore" is fulfillment - type and "store123" is the store ID. - - Supported keys are: - - - colorFamilies - - price - - originalPrice - - discount - - variantId - - inventory(place_id,price) - - inventory(place_id,original_price) - - inventory(place_id,attributes.key), where key is any key - in the - [Product.local_inventories.attributes][google.cloud.retail.v2.LocalInventory.attributes] - map. - - attributes.key, where key is any key in the - [Product.attributes][google.cloud.retail.v2.Product.attributes] - map. - - pickupInStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "pickup-in-store". - - shipToStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "ship-to-store". - - sameDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "same-day-delivery". - - nextDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "next-day-delivery". - - customFulfillment1.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-1". - - customFulfillment2.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-2". - - customFulfillment3.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-3". - - customFulfillment4.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-4". - - customFulfillment5.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-5". - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. Required for - category navigation queries to achieve good search quality. - The format should be the same as - [UserEvent.page_categories][google.cloud.retail.v2.UserEvent.page_categories]; - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - search_mode (google.cloud.retail_v2.types.SearchRequest.SearchMode): - The search mode of the search request. If not - specified, a single search request triggers both - product search and faceted search. - personalization_spec (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec): - The specification for personalization. - labels (Mapping[str, str]): - The labels applied to a resource must meet the following - requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - spell_correction_spec (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec): - The spell correction specification that - specifies the mode under which spell correction - will take effect. - - This field is a member of `oneof`_ ``_spell_correction_spec``. - """ - class SearchMode(proto.Enum): - r"""The search mode of each search request.""" - SEARCH_MODE_UNSPECIFIED = 0 - PRODUCT_SEARCH_ONLY = 1 - FACETED_SEARCH_ONLY = 2 - - class FacetSpec(proto.Message): - r"""A facet specification to perform faceted search. - - Attributes: - facet_key (google.cloud.retail_v2.types.SearchRequest.FacetSpec.FacetKey): - Required. The facet key specification. - limit (int): - Maximum of facet values that should be returned for this - facet. If unspecified, defaults to 20. The maximum allowed - value is 300. Values above 300 will be coerced to 300. - - If this field is negative, an INVALID_ARGUMENT is returned. - excluded_filter_keys (Sequence[str]): - List of keys to exclude when faceting. - - By default, - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - is not excluded from the filter unless it is listed in this - field. - - Listing a facet key in this field allows its values to - appear as facet results, even when they are filtered out of - search results. Using this field does not affect what search - results are returned. - - For example, suppose there are 100 products with the color - facet "Red" and 200 products with the color facet "Blue". A - query containing the filter "colorFamilies:ANY("Red")" and - having "colorFamilies" as - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - would by default return only "Red" products in the search - results, and also return "Red" with count 100 as the only - color facet. Although there are also blue products - available, "Blue" would not be shown as an available facet - value. - - If "colorFamilies" is listed in "excludedFilterKeys", then - the query returns the facet values "Red" with count 100 and - "Blue" with count 200, because the "colorFamilies" key is - now excluded from the filter. Because this field doesn't - affect search results, the search results are still - correctly filtered to return only "Red" products. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - enable_dynamic_position (bool): - Enables dynamic position for this facet. If set to true, the - position of this facet among all facets in the response is - determined by Google Retail Search. It will be ordered - together with dynamic facets if dynamic facets is enabled. - If set to false, the position of this facet in the response - will be the same as in the request, and it will be ranked - before the facets with dynamic position enable and all - dynamic facets. - - For example, you may always want to have rating facet - returned in the response, but it's not necessarily to always - display the rating facet at the top. In that case, you can - set enable_dynamic_position to true so that the position of - rating facet in response will be determined by Google Retail - Search. - - Another example, assuming you have the following facets in - the request: - - - "rating", enable_dynamic_position = true - - - "price", enable_dynamic_position = false - - - "brands", enable_dynamic_position = false - - And also you have a dynamic facets enable, which will - generate a facet 'gender'. Then the final order of the - facets in the response can be ("price", "brands", "rating", - "gender") or ("price", "brands", "gender", "rating") depends - on how Google Retail Search orders "gender" and "rating" - facets. However, notice that "price" and "brands" will - always be ranked at 1st and 2nd position since their - enable_dynamic_position are false. - """ - - class FacetKey(proto.Message): - r"""Specifies how a facet is computed. - - Attributes: - key (str): - Required. Supported textual and numerical facet keys in - [Product][google.cloud.retail.v2.Product] object, over which - the facet values are computed. Facet key is case-sensitive. - - Allowed facet keys when - [FacetKey.query][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.query] - is not specified: - - - textual_field = - - - "brands" - - "categories" - - "genders" - - "ageGroups" - - "availability" - - "colorFamilies" - - "colors" - - "sizes" - - "materials" - - "patterns" - - "conditions" - - "attributes.key" - - "pickupInStore" - - "shipToStore" - - "sameDayDelivery" - - "nextDayDelivery" - - "customFulfillment1" - - "customFulfillment2" - - "customFulfillment3" - - "customFulfillment4" - - "customFulfillment5" - - "inventory(place_id,attributes.key)" - - - numerical_field = - - - "price" - - "discount" - - "rating" - - "ratingCount" - - "attributes.key" - - "inventory(place_id,price)" - - "inventory(place_id,original_price)" - - "inventory(place_id,attributes.key)". - intervals (Sequence[google.cloud.retail_v2.types.Interval]): - Set only if values should be bucketized into - intervals. Must be set for facets with numerical - values. Must not be set for facet with text - values. Maximum number of intervals is 30. - restricted_values (Sequence[str]): - Only get facet for the given restricted values. For example, - when using "pickupInStore" as key and set restricted values - to ["store123", "store456"], only facets for "store123" and - "store456" are returned. Only supported on predefined - textual fields, custom textual attributes and fulfillments. - Maximum is 20. - - Must be set for the fulfillment facet keys: - - - pickupInStore - - - shipToStore - - - sameDayDelivery - - - nextDayDelivery - - - customFulfillment1 - - - customFulfillment2 - - - customFulfillment3 - - - customFulfillment4 - - - customFulfillment5 - prefixes (Sequence[str]): - Only get facet values that start with the - given string prefix. For example, suppose - "categories" has three values "Women > Shoe", - "Women > Dress" and "Men > Shoe". If set - "prefixes" to "Women", the "categories" facet - will give only "Women > Shoe" and "Women > - Dress". Only supported on textual fields. - Maximum is 10. - contains (Sequence[str]): - Only get facet values that contains the given - strings. For example, suppose "categories" has - three values "Women > Shoe", "Women > Dress" and - "Men > Shoe". If set "contains" to "Shoe", the - "categories" facet will give only "Women > Shoe" - and "Men > Shoe". Only supported on textual - fields. Maximum is 10. - order_by (str): - The order in which [Facet.values][] are returned. - - Allowed values are: - - - "count desc", which means order by - [Facet.FacetValue.count][] descending. - - - "value desc", which means order by - [Facet.FacetValue.value][] descending. Only applies to - textual facets. - - If not set, textual values are sorted in `natural - order `__; - numerical intervals are sorted in the order given by - [FacetSpec.FacetKey.intervals][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.intervals]; - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - are sorted in the order given by - [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.restricted_values]. - query (str): - The query that is used to compute facet for the given facet - key. When provided, it will override the default behavior of - facet computation. The query syntax is the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] - for detail syntax and limitations. Notice that there is no - limitation on - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - when query is specified. - - In the response, [FacetValue.value][] will be always "1" and - [FacetValue.count][] will be the number of results that - matches the query. - - For example, you can set a customized facet for - "shipToStore", where - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - is "customizedShipToStore", and - [FacetKey.query][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.query] - is "availability: ANY("IN_STOCK") AND shipToStore: - ANY("123")". Then the facet will count the products that are - both in stock and ship to store "123". - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - intervals = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Interval, - ) - restricted_values = proto.RepeatedField( - proto.STRING, - number=3, - ) - prefixes = proto.RepeatedField( - proto.STRING, - number=8, - ) - contains = proto.RepeatedField( - proto.STRING, - number=9, - ) - order_by = proto.Field( - proto.STRING, - number=4, - ) - query = proto.Field( - proto.STRING, - number=5, - ) - - facet_key = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.FacetSpec.FacetKey', - ) - limit = proto.Field( - proto.INT32, - number=2, - ) - excluded_filter_keys = proto.RepeatedField( - proto.STRING, - number=3, - ) - enable_dynamic_position = proto.Field( - proto.BOOL, - number=4, - ) - - class DynamicFacetSpec(proto.Message): - r"""The specifications of dynamically generated facets. - - Attributes: - mode (google.cloud.retail_v2.types.SearchRequest.DynamicFacetSpec.Mode): - Mode of the DynamicFacet feature. Defaults to - [Mode.DISABLED][google.cloud.retail.v2.SearchRequest.DynamicFacetSpec.Mode.DISABLED] - if it's unset. - """ - class Mode(proto.Enum): - r"""Enum to control DynamicFacet mode""" - MODE_UNSPECIFIED = 0 - DISABLED = 1 - ENABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.DynamicFacetSpec.Mode', - ) - - class BoostSpec(proto.Message): - r"""Boost specification to boost certain items. - - Attributes: - condition_boost_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - Condition boost specifications. If a product - matches multiple conditions in the - specifictions, boost scores from these - specifications are all applied and combined in a - non-linear way. Maximum number of specifications - is 20. - skip_boost_spec_validation (bool): - Whether to skip boostspec validation. If this field is set - to true, invalid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] - will be ignored and valid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] - will still be applied. - - This field is a member of `oneof`_ ``_skip_boost_spec_validation``. - """ - - class ConditionBoostSpec(proto.Message): - r"""Boost applies to products which match a condition. - - Attributes: - condition (str): - An expression which specifies a boost condition. The syntax - and supported fields are the same as a filter expression. - See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": - - - (id: ANY("product_1", "product_2")) AND - (colorFamilies: ANY("Red","Blue")) - boost (float): - Strength of the condition boost, which should be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - """ - - condition = proto.Field( - proto.STRING, - number=1, - ) - boost = proto.Field( - proto.FLOAT, - number=2, - ) - - condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - skip_boost_spec_validation = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - - class QueryExpansionSpec(proto.Message): - r"""Specification to determine under which conditions query - expansion should occur. - - Attributes: - condition (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec.Condition): - The condition under which query expansion should occur. - Default to - [Condition.DISABLED][google.cloud.retail.v2.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - pin_unexpanded_results (bool): - Whether to pin unexpanded results. If this - field is set to true, unexpanded products are - always at the top of the search results, - followed by the expanded results. - """ - class Condition(proto.Enum): - r"""Enum describing under which condition query expansion should - occur. - """ - CONDITION_UNSPECIFIED = 0 - DISABLED = 1 - AUTO = 3 - - condition = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.QueryExpansionSpec.Condition', - ) - pin_unexpanded_results = proto.Field( - proto.BOOL, - number=2, - ) - - class PersonalizationSpec(proto.Message): - r"""The specification for personalization. - - Attributes: - mode (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec.Mode): - Defaults to - [Mode.AUTO][google.cloud.retail.v2.SearchRequest.PersonalizationSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""The personalization mode of each search request.""" - MODE_UNSPECIFIED = 0 - AUTO = 1 - DISABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.PersonalizationSpec.Mode', - ) - - class SpellCorrectionSpec(proto.Message): - r"""The specification for query spell correction. - - Attributes: - mode (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec.Mode): - The mode under which spell correction should take effect to - replace the original search query. Default to - [Mode.AUTO][google.cloud.retail.v2.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""Enum describing under which mode spell correction should - occur. - """ - MODE_UNSPECIFIED = 0 - SUGGESTION_ONLY = 1 - AUTO = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.SpellCorrectionSpec.Mode', - ) - - placement = proto.Field( - proto.STRING, - number=1, - ) - branch = proto.Field( - proto.STRING, - number=2, - ) - query = proto.Field( - proto.STRING, - number=3, - ) - visitor_id = proto.Field( - proto.STRING, - number=4, - ) - user_info = proto.Field( - proto.MESSAGE, - number=5, - message=common.UserInfo, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - offset = proto.Field( - proto.INT32, - number=9, - ) - filter = proto.Field( - proto.STRING, - number=10, - ) - canonical_filter = proto.Field( - proto.STRING, - number=28, - ) - order_by = proto.Field( - proto.STRING, - number=11, - ) - facet_specs = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=FacetSpec, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=21, - message=DynamicFacetSpec, - ) - boost_spec = proto.Field( - proto.MESSAGE, - number=13, - message=BoostSpec, - ) - query_expansion_spec = proto.Field( - proto.MESSAGE, - number=14, - message=QueryExpansionSpec, - ) - variant_rollup_keys = proto.RepeatedField( - proto.STRING, - number=17, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=23, - ) - search_mode = proto.Field( - proto.ENUM, - number=31, - enum=SearchMode, - ) - personalization_spec = proto.Field( - proto.MESSAGE, - number=32, - message=PersonalizationSpec, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=34, - ) - spell_correction_spec = proto.Field( - proto.MESSAGE, - number=35, - optional=True, - message=SpellCorrectionSpec, - ) - - -class SearchResponse(proto.Message): - r"""Response message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - - Attributes: - results (Sequence[google.cloud.retail_v2.types.SearchResponse.SearchResult]): - A list of matched items. The order represents - the ranking. - facets (Sequence[google.cloud.retail_v2.types.SearchResponse.Facet]): - Results of facets requested by user. - total_size (int): - The estimated total count of matched items irrespective of - pagination. The count of - [results][google.cloud.retail.v2.SearchResponse.results] - returned by pagination may be less than the - [total_size][google.cloud.retail.v2.SearchResponse.total_size] - that matches. - corrected_query (str): - Contains the spell corrected query, if found. If the spell - correction type is AUTOMATIC, then the search results are - based on corrected_query. Otherwise the original query will - be used for search. - attribution_token (str): - A unique search token. This should be included in the - [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting - from this search, which enables accurate attribution of - search model performance. - next_page_token (str): - A token that can be sent as - [SearchRequest.page_token][google.cloud.retail.v2.SearchRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - query_expansion_info (google.cloud.retail_v2.types.SearchResponse.QueryExpansionInfo): - Query expansion information for the returned - results. - redirect_uri (str): - The URI of a customer-defined redirect page. If redirect - action is triggered, no search is performed, and only - [redirect_uri][google.cloud.retail.v2.SearchResponse.redirect_uri] - and - [attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] - are set in the response. - applied_controls (Sequence[str]): - The fully qualified resource name of applied - `controls `__. - invalid_condition_boost_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - The invalid - [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] - that are not applied during serving. - """ - - class SearchResult(proto.Message): - r"""Represents the search results. - - Attributes: - id (str): - [Product.id][google.cloud.retail.v2.Product.id] of the - searched [Product][google.cloud.retail.v2.Product]. - product (google.cloud.retail_v2.types.Product): - The product data snippet in the search response. Only - [Product.name][google.cloud.retail.v2.Product.name] is - guaranteed to be populated. - - [Product.variants][google.cloud.retail.v2.Product.variants] - contains the product variants that match the search query. - If there are multiple product variants matching the query, - top 5 most relevant product variants are returned and - ordered by relevancy. - - If relevancy can be deternmined, use - [matching_variant_fields][google.cloud.retail.v2.SearchResponse.SearchResult.matching_variant_fields] - to look up matched product variants fields. If relevancy - cannot be determined, e.g. when searching "shoe" all - products in a shoe product can be a match, 5 product - variants are returned but order is meaningless. - matching_variant_count (int): - The count of matched - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s. - matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): - If a [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] matches the search - query, this map indicates which - [Product][google.cloud.retail.v2.Product] fields are - matched. The key is the - [Product.name][google.cloud.retail.v2.Product.name], the - value is a field mask of the matched - [Product][google.cloud.retail.v2.Product] fields. If matched - attributes cannot be determined, this map will be empty. - - For example, a key "sku1" with field mask - "products.color_info" indicates there is a match between - "sku1" [ColorInfo][google.cloud.retail.v2.ColorInfo] and the - query. - variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): - The rollup matching - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] attributes. The - key is one of the - [SearchRequest.variant_rollup_keys][google.cloud.retail.v2.SearchRequest.variant_rollup_keys]. - The values are the merged and de-duplicated - [Product][google.cloud.retail.v2.Product] attributes. Notice - that the rollup values are respect filter. For example, when - filtering by "colorFamilies:ANY("red")" and rollup - "colorFamilies", only "red" is returned. - - For textual and numerical attributes, the rollup values is a - list of string or double values with type - [google.protobuf.ListValue][google.protobuf.ListValue]. For - example, if there are two variants with colors "red" and - "blue", the rollup values are - - :: - - { key: "colorFamilies" - value { - list_value { - values { string_value: "red" } - values { string_value: "blue" } - } - } - } - - For - [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], - the rollup values is a double value with type - [google.protobuf.Value][google.protobuf.Value]. For example, - ``{key: "pickupInStore.store1" value { number_value: 10 }}`` - means a there are 10 variants in this product are available - in the store "store1". - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - matching_variant_count = proto.Field( - proto.INT32, - number=3, - ) - matching_variant_fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - variant_rollup_values = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - - class Facet(proto.Message): - r"""A facet result. - - Attributes: - key (str): - The key for this facet. E.g., "colorFamilies" - or "price" or "attributes.attr1". - values (Sequence[google.cloud.retail_v2.types.SearchResponse.Facet.FacetValue]): - The facet values for this field. - dynamic_facet (bool): - Whether the facet is dynamically generated. - """ - - class FacetValue(proto.Message): - r"""A facet value which contains value names and their count. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Text value of a facet, such as "Black" for - facet "colorFamilies". - - This field is a member of `oneof`_ ``facet_value``. - interval (google.cloud.retail_v2.types.Interval): - Interval value for a facet, such as [10, 20) for facet - "price". - - This field is a member of `oneof`_ ``facet_value``. - count (int): - Number of items that have this facet value. - """ - - value = proto.Field( - proto.STRING, - number=1, - oneof='facet_value', - ) - interval = proto.Field( - proto.MESSAGE, - number=2, - oneof='facet_value', - message=common.Interval, - ) - count = proto.Field( - proto.INT64, - number=3, - ) - - key = proto.Field( - proto.STRING, - number=1, - ) - values = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SearchResponse.Facet.FacetValue', - ) - dynamic_facet = proto.Field( - proto.BOOL, - number=3, - ) - - class QueryExpansionInfo(proto.Message): - r"""Information describing query expansion including whether - expansion has occurred. - - Attributes: - expanded_query (bool): - Bool describing whether query expansion has - occurred. - pinned_result_count (int): - Number of pinned results. This field will only be set when - expansion happens and - [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] - is set to true. - """ - - expanded_query = proto.Field( - proto.BOOL, - number=1, - ) - pinned_result_count = proto.Field( - proto.INT64, - number=2, - ) - - @property - def raw_page(self): - return self - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=SearchResult, - ) - facets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Facet, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - corrected_query = proto.Field( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - next_page_token = proto.Field( - proto.STRING, - number=6, - ) - query_expansion_info = proto.Field( - proto.MESSAGE, - number=7, - message=QueryExpansionInfo, - ) - redirect_uri = proto.Field( - proto.STRING, - number=10, - ) - applied_controls = proto.RepeatedField( - proto.STRING, - number=12, - ) - invalid_condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py deleted file mode 100644 index 0d6b6823..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py +++ /dev/null @@ -1,508 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import product as gcr_product -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'UserEvent', - 'ProductDetail', - 'CompletionDetail', - 'PurchaseTransaction', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information Retail API needs - to know about how end users interact with customers' website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - - ``add-to-cart``: Products being added to cart. - - ``category-page-view``: Special pages such as sale or - promotion pages viewed. - - ``detail-page-view``: Products detail page viewed. - - ``home-page-view``: Homepage viewed. - - ``promotion-offered``: Promotion is offered to a user. - - ``promotion-not-offered``: Promotion is not offered to a - user. - - ``purchase-complete``: User finishing a purchase. - - ``search``: Product search. - - ``shopping-cart-page-view``: User viewing a shopping - cart. - visitor_id (str): - Required. A unique identifier for tracking visitors. - - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor log in/out of the website. - - Don't set the field to the same fixed ID for different - users. This mixes the event history of those users together, - which results in degraded model quality. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - The field should not contain PII or user-data. We recommend - to use Google Analytics `Client - ID `__ - for this field. - session_id (str): - A unique identifier for tracking a visitor session with a - length limit of 128 bytes. A session is an aggregation of an - end user behavior in a time span. - - A general guideline to populate the sesion_id: - - 1. If user has no activity for 30 min, a new session_id - should be assigned. - 2. The session_id should be unique across users, suggest use - uuid or add visitor_id as prefix. - event_time (google.protobuf.timestamp_pb2.Timestamp): - Only required for - [UserEventService.ImportUserEvents][google.cloud.retail.v2.UserEventService.ImportUserEvents] - method. Timestamp of when the user event happened. - experiment_ids (Sequence[str]): - A list of identifiers for the independent - experiment groups this user event belongs to. - This is used to distinguish between user events - associated with different experiment setups - (e.g. using Retail API, using different - recommendation models). - attribution_token (str): - Highly recommended for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]. - This field enables accurate attribution of recommendation - model performance. - - The value must be a valid - [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] - for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]. - The value must be a valid - [SearchResponse.attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] - for user events that are the result of - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - - This token enables us to accurately attribute page view or - purchase back to the event and the particular predict - response containing this clicked/purchased product. If user - clicks on product K in the recommendation results, pass - [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] - as a URL parameter to product K's page. When recording - events on product K's page, log the - [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] - to this field. - product_details (Sequence[google.cloud.retail_v2.types.ProductDetail]): - The main product details related to the event. - - This field is optional except for the following event types: - - - ``add-to-cart`` - - ``detail-page-view`` - - ``purchase-complete`` - - In a ``search`` event, this field represents the products - returned to the end user on the current page (the end user - may have not finished browsing the whole page yet). When a - new page is returned to the end user, after - pagination/filtering/ordering even for the same query, a new - ``search`` event with different - [product_details][google.cloud.retail.v2.UserEvent.product_details] - is desired. The end user may have not finished browsing the - whole page yet. - completion_detail (google.cloud.retail_v2.types.CompletionDetail): - The main auto-completion details related to the event. - - This field should be set for ``search`` event when - autocomplete function is enabled and the user clicks a - suggestion for search. - attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): - Extra user event features to include in the recommendation - model. - - If you provide custom attributes for ingested user events, - also include them in the user events that you associate with - prediction requests. Custom attribute formatting must be - consistent between imported events and events provided with - prediction requests. This lets the Retail API use those - custom attributes when training models and serving - predictions, which helps improve recommendation quality. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - The key must be a UTF-8 encoded string with a length - limit of 5,000 characters. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a UTF-8 - encoded string with a length limit of 256 characters. - - For number attributes, at most 400 values are allowed. - - For product recommendations, an example of extra user - information is traffic_channel, which is how a user arrives - at the site. Users can arrive at the site by coming to the - site directly, coming through Google search, or in other - ways. - cart_id (str): - The ID or name of the associated shopping cart. This ID is - used to associate multiple items added or present in the - cart before purchase. - - This can only be set for ``add-to-cart``, - ``purchase-complete``, or ``shopping-cart-page-view`` - events. - purchase_transaction (google.cloud.retail_v2.types.PurchaseTransaction): - A transaction represents the entire purchase transaction. - - Required for ``purchase-complete`` events. Other event types - should not set this field. Otherwise, an INVALID_ARGUMENT - error is returned. - search_query (str): - The user's search query. - - See - [SearchRequest.query][google.cloud.retail.v2.SearchRequest.query] - for definition. - - The value must be a UTF-8 encoded string with a length limit - of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - At least one of - [search_query][google.cloud.retail.v2.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. - - See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - order_by (str): - The order in which products are returned. - - See - [SearchRequest.order_by][google.cloud.retail.v2.SearchRequest.order_by] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - offset (int): - An integer that specifies the current offset for pagination - (the 0-indexed starting location, amongst the products - deemed by the API as relevant). - - See - [SearchRequest.offset][google.cloud.retail.v2.SearchRequest.offset] - for definition. - - If this field is negative, an INVALID_ARGUMENT is returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - - Required for ``category-page-view`` events. At least one of - [search_query][google.cloud.retail.v2.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2.types.UserInfo): - User information. - uri (str): - Complete URL (window.location.href) of the - user's current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. Maximum length - 5,000 characters. - referrer_uri (str): - The referrer URL of the current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. - page_view_id (str): - A unique ID of a web page view. - - This should be kept the same for all user events triggered - from the same pageview. For example, an item detail page - view could trigger multiple events as the user is browsing - the page. The ``pageViewId`` property should be kept the - same for all these events so that they can be grouped - together properly. - - When using the client side event reporting with JavaScript - pixel and Google Tag Manager, this value is filled in - automatically. - """ - - event_type = proto.Field( - proto.STRING, - number=1, - ) - visitor_id = proto.Field( - proto.STRING, - number=2, - ) - session_id = proto.Field( - proto.STRING, - number=21, - ) - event_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - experiment_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - product_details = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='ProductDetail', - ) - completion_detail = proto.Field( - proto.MESSAGE, - number=22, - message='CompletionDetail', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=common.CustomAttribute, - ) - cart_id = proto.Field( - proto.STRING, - number=8, - ) - purchase_transaction = proto.Field( - proto.MESSAGE, - number=9, - message='PurchaseTransaction', - ) - search_query = proto.Field( - proto.STRING, - number=10, - ) - filter = proto.Field( - proto.STRING, - number=16, - ) - order_by = proto.Field( - proto.STRING, - number=17, - ) - offset = proto.Field( - proto.INT32, - number=18, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=11, - ) - user_info = proto.Field( - proto.MESSAGE, - number=12, - message=common.UserInfo, - ) - uri = proto.Field( - proto.STRING, - number=13, - ) - referrer_uri = proto.Field( - proto.STRING, - number=14, - ) - page_view_id = proto.Field( - proto.STRING, - number=15, - ) - - -class ProductDetail(proto.Message): - r"""Detailed product information associated with a user event. - - Attributes: - product (google.cloud.retail_v2.types.Product): - Required. [Product][google.cloud.retail.v2.Product] - information. - - Required field(s): - - - [Product.id][google.cloud.retail.v2.Product.id] - - Optional override field(s): - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - If any supported optional fields are provided, we will treat - them as a full override when looking up product information - from the catalog. Thus, it is important to ensure that the - overriding fields are accurate and complete. - - All other product fields are ignored and instead populated - via catalog lookup after event ingestion. - quantity (google.protobuf.wrappers_pb2.Int32Value): - Quantity of the product associated with the user event. - - For example, this field will be 2 if two products are added - to the shopping cart for ``purchase-complete`` event. - Required for ``add-to-cart`` and ``purchase-complete`` event - types. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - quantity = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -class CompletionDetail(proto.Message): - r"""Detailed completion information including completion - attribution token and clicked completion info. - - Attributes: - completion_attribution_token (str): - Completion attribution token in - [CompleteQueryResponse.attribution_token][google.cloud.retail.v2.CompleteQueryResponse.attribution_token]. - selected_suggestion (str): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2.CompleteQueryResponse.CompletionResult.suggestion]. - selected_position (int): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2.CompleteQueryResponse.CompletionResult.suggestion] - position, starting from 0. - """ - - completion_attribution_token = proto.Field( - proto.STRING, - number=1, - ) - selected_suggestion = proto.Field( - proto.STRING, - number=2, - ) - selected_position = proto.Field( - proto.INT32, - number=3, - ) - - -class PurchaseTransaction(proto.Message): - r"""A transaction represents the entire purchase transaction. - - Attributes: - id (str): - The transaction ID with a length limit of 128 - characters. - revenue (float): - Required. Total non-zero revenue or grand - total associated with the transaction. This - value include shipping, tax, or other - adjustments to total revenue that you want to - include as part of your revenue calculations. - tax (float): - All the taxes associated with the - transaction. - cost (float): - All the costs associated with the products. These can be - manufacturing costs, shipping expenses not borne by the end - user, or any other costs, such that: - - - Profit = - [revenue][google.cloud.retail.v2.PurchaseTransaction.revenue] - - [tax][google.cloud.retail.v2.PurchaseTransaction.tax] - - [cost][google.cloud.retail.v2.PurchaseTransaction.cost] - currency_code (str): - Required. Currency code. Use three-character - ISO-4217 code. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - revenue = proto.Field( - proto.FLOAT, - number=2, - ) - tax = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - currency_code = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py deleted file mode 100644 index fcfc46d7..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import user_event as gcr_user_event - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'WriteUserEventRequest', - 'CollectUserEventRequest', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'RejoinUserEventsMetadata', - }, -) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (google.cloud.retail_v2.types.UserEvent): - Required. User event to write. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (str): - Required. URL encoded UserEvent proto with a - length limit of 2,000,000 characters. - uri (str): - The URL including cgi-parameters but - excluding the hash fragment with a length limit - of 5,000 characters. This is often more useful - than the referer URL, because many browsers only - send the domain for 3rd party requests. - ets (int): - The event timestamp in milliseconds. This - prevents browser caching of otherwise identical - get requests. The name is abbreviated to reduce - the payload bytes. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.STRING, - number=2, - ) - uri = proto.Field( - proto.STRING, - number=3, - ) - ets = proto.Field( - proto.INT64, - number=4, - ) - - -class RejoinUserEventsRequest(proto.Message): - r"""Request message for RejoinUserEvents method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event_rejoin_scope (google.cloud.retail_v2.types.RejoinUserEventsRequest.UserEventRejoinScope): - The type of the user event rejoin to define the scope and - range of the user events to be rejoined with the latest - product catalog. Defaults to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not - set, or set to an invalid integer value. - """ - class UserEventRejoinScope(proto.Enum): - r"""The scope of user events to be rejoined with the latest product - catalog. If the rejoining aims at reducing number of unjoined - events, set UserEventRejoinScope to UNJOINED_EVENTS. If the - rejoining aims at correcting product catalog information in joined - events, set UserEventRejoinScope to JOINED_EVENTS. If all events - needs to be rejoined, set UserEventRejoinScope to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. - """ - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 - JOINED_EVENTS = 1 - UNJOINED_EVENTS = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event_rejoin_scope = proto.Field( - proto.ENUM, - number=2, - enum=UserEventRejoinScope, - ) - - -class RejoinUserEventsResponse(proto.Message): - r"""Response message for RejoinUserEvents method. - - Attributes: - rejoined_user_events_count (int): - Number of user events that were joined with - latest product catalog. - """ - - rejoined_user_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -class RejoinUserEventsMetadata(proto.Message): - r"""Metadata for RejoinUserEvents method. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py deleted file mode 100644 index e7ab4118..00000000 --- a/owl-bot-staging/v2/noxfile.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.6", - "3.7", - "3.8", - "3.9", - "3.10", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==19.10b0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.9" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/retail_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py deleted file mode 100644 index fb30eae6..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_GetDefaultBranch_async] -from google.cloud import retail_v2 - - -async def sample_get_default_branch(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py deleted file mode 100644 index 0af0ece9..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_GetDefaultBranch_sync] -from google.cloud import retail_v2 - - -def sample_get_default_branch(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py deleted file mode 100644 index 2a0930de..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_ListCatalogs_async] -from google.cloud import retail_v2 - - -async def sample_list_catalogs(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py deleted file mode 100644 index 2671a121..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_ListCatalogs_sync] -from google.cloud import retail_v2 - - -def sample_list_catalogs(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py deleted file mode 100644 index f85e3ed8..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_SetDefaultBranch_async] -from google.cloud import retail_v2 - - -async def sample_set_default_branch(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - -# [END retail_v2_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py deleted file mode 100644 index 34371062..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_SetDefaultBranch_sync] -from google.cloud import retail_v2 - - -def sample_set_default_branch(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - -# [END retail_v2_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py deleted file mode 100644 index 2a2b3dde..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_UpdateCatalog_async] -from google.cloud import retail_v2 - - -async def sample_update_catalog(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py deleted file mode 100644 index bf721cba..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_UpdateCatalog_sync] -from google.cloud import retail_v2 - - -def sample_update_catalog(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py deleted file mode 100644 index c72ecfdf..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CompletionService_CompleteQuery_async] -from google.cloud import retail_v2 - - -async def sample_complete_query(): - # Create a client - client = retail_v2.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py deleted file mode 100644 index 30b10016..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CompletionService_CompleteQuery_sync] -from google.cloud import retail_v2 - - -def sample_complete_query(): - # Create a client - client = retail_v2.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py deleted file mode 100644 index 75f45f91..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CompletionService_ImportCompletionData_async] -from google.cloud import retail_v2 - - -async def sample_import_completion_data(): - # Create a client - client = retail_v2.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py deleted file mode 100644 index cc31057e..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CompletionService_ImportCompletionData_sync] -from google.cloud import retail_v2 - - -def sample_import_completion_data(): - # Create a client - client = retail_v2.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py deleted file mode 100644 index f46819c5..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_PredictionService_Predict_async] -from google.cloud import retail_v2 - - -async def sample_predict(): - # Create a client - client = retail_v2.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py deleted file mode 100644 index ad37063f..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_PredictionService_Predict_sync] -from google.cloud import retail_v2 - - -def sample_predict(): - # Create a client - client = retail_v2.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py deleted file mode 100644 index ceea2869..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_AddFulfillmentPlaces_async] -from google.cloud import retail_v2 - - -async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py deleted file mode 100644 index 1739ec91..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_AddFulfillmentPlaces_sync] -from google.cloud import retail_v2 - - -def sample_add_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py deleted file mode 100644 index 6155d5ce..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_AddLocalInventories_async] -from google.cloud import retail_v2 - - -async def sample_add_local_inventories(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py deleted file mode 100644 index b57dce2f..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_AddLocalInventories_sync] -from google.cloud import retail_v2 - - -def sample_add_local_inventories(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py deleted file mode 100644 index fe1cb991..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_CreateProduct_async] -from google.cloud import retail_v2 - - -async def sample_create_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py deleted file mode 100644 index 9cc154d9..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_CreateProduct_sync] -from google.cloud import retail_v2 - - -def sample_create_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py deleted file mode 100644 index 33318da7..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_DeleteProduct_async] -from google.cloud import retail_v2 - - -async def sample_delete_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - -# [END retail_v2_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py deleted file mode 100644 index 797690c6..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_DeleteProduct_sync] -from google.cloud import retail_v2 - - -def sample_delete_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - -# [END retail_v2_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py deleted file mode 100644 index 32ba279d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_GetProduct_async] -from google.cloud import retail_v2 - - -async def sample_get_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py deleted file mode 100644 index 62805768..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_GetProduct_sync] -from google.cloud import retail_v2 - - -def sample_get_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py deleted file mode 100644 index 390f0977..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_ImportProducts_async] -from google.cloud import retail_v2 - - -async def sample_import_products(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py deleted file mode 100644 index fcd8c82f..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_ImportProducts_sync] -from google.cloud import retail_v2 - - -def sample_import_products(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py deleted file mode 100644 index 5e85f948..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_ListProducts_async] -from google.cloud import retail_v2 - - -async def sample_list_products(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py deleted file mode 100644 index 30f7fd1f..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_ListProducts_sync] -from google.cloud import retail_v2 - - -def sample_list_products(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py deleted file mode 100644 index 08172bf4..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async] -from google.cloud import retail_v2 - - -async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py deleted file mode 100644 index 37f86ba9..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync] -from google.cloud import retail_v2 - - -def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py deleted file mode 100644 index 762dab6d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_RemoveLocalInventories_async] -from google.cloud import retail_v2 - - -async def sample_remove_local_inventories(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py deleted file mode 100644 index 7aa52d5d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_RemoveLocalInventories_sync] -from google.cloud import retail_v2 - - -def sample_remove_local_inventories(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py deleted file mode 100644 index 62a24100..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_SetInventory_async] -from google.cloud import retail_v2 - - -async def sample_set_inventory(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2.Product() - inventory.title = "title_value" - - request = retail_v2.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py deleted file mode 100644 index aa5a0539..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_SetInventory_sync] -from google.cloud import retail_v2 - - -def sample_set_inventory(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2.Product() - inventory.title = "title_value" - - request = retail_v2.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py deleted file mode 100644 index 9ea76295..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_UpdateProduct_async] -from google.cloud import retail_v2 - - -async def sample_update_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py deleted file mode 100644 index 866c7e7c..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_UpdateProduct_sync] -from google.cloud import retail_v2 - - -def sample_update_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py deleted file mode 100644 index ddebd9e8..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_SearchService_Search_async] -from google.cloud import retail_v2 - - -async def sample_search(): - # Create a client - client = retail_v2.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py deleted file mode 100644 index fc20bb3d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_SearchService_Search_sync] -from google.cloud import retail_v2 - - -def sample_search(): - # Create a client - client = retail_v2.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py deleted file mode 100644 index b8bb6a81..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_CollectUserEvent_async] -from google.cloud import retail_v2 - - -async def sample_collect_user_event(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py deleted file mode 100644 index 10b302e3..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_CollectUserEvent_sync] -from google.cloud import retail_v2 - - -def sample_collect_user_event(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py deleted file mode 100644 index 55ad399a..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_ImportUserEvents_async] -from google.cloud import retail_v2 - - -async def sample_import_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py deleted file mode 100644 index 835edec6..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_ImportUserEvents_sync] -from google.cloud import retail_v2 - - -def sample_import_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py deleted file mode 100644 index 1da1d39d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_PurgeUserEvents_async] -from google.cloud import retail_v2 - - -async def sample_purge_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py deleted file mode 100644 index 48814171..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_PurgeUserEvents_sync] -from google.cloud import retail_v2 - - -def sample_purge_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py deleted file mode 100644 index a2617cfe..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_RejoinUserEvents_async] -from google.cloud import retail_v2 - - -async def sample_rejoin_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py deleted file mode 100644 index eb8ed62c..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_RejoinUserEvents_sync] -from google.cloud import retail_v2 - - -def sample_rejoin_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py deleted file mode 100644 index 82afc25a..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_WriteUserEvent_async] -from google.cloud import retail_v2 - - -async def sample_write_user_event(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py deleted file mode 100644 index 62336b25..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_WriteUserEvent_sync] -from google.cloud import retail_v2 - - -def sample_write_user_event(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json deleted file mode 100644 index c6a55bd4..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json +++ /dev/null @@ -1,3826 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.retail.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-cloud-retail" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2_generated_catalog_service_get_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_GetDefaultBranch_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_get_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2_generated_catalog_service_get_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_GetDefaultBranch_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_get_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ListCatalogsRequest" - }, - { - "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.retail_v2.services.catalog_service.pagers.ListCatalogsAsyncPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2_generated_catalog_service_list_catalogs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_ListCatalogs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_list_catalogs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ListCatalogsRequest" - }, - { - "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.retail_v2.services.catalog_service.pagers.ListCatalogsPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2_generated_catalog_service_list_catalogs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_ListCatalogs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_list_catalogs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2_generated_catalog_service_set_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_SetDefaultBranch_async", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_set_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2_generated_catalog_service_set_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_SetDefaultBranch_sync", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_set_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2.types.Catalog" - }, - { - "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.retail_v2.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2_generated_catalog_service_update_catalog_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_UpdateCatalog_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_update_catalog_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2.types.Catalog" - }, - { - "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.retail_v2.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2_generated_catalog_service_update_catalog_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_UpdateCatalog_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_update_catalog_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2_generated_completion_service_complete_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CompletionService_CompleteQuery_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_completion_service_complete_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2.CompletionServiceClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2_generated_completion_service_complete_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CompletionService_CompleteQuery_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_completion_service_complete_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2_generated_completion_service_import_completion_data_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CompletionService_ImportCompletionData_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_completion_service_import_completion_data_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2.CompletionServiceClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2_generated_completion_service_import_completion_data_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CompletionService_ImportCompletionData_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_completion_service_import_completion_data_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.PredictionServiceAsyncClient", - "shortName": "PredictionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.PredictionServiceAsyncClient.predict", - "method": { - "fullName": "google.cloud.retail.v2.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2_generated_prediction_service_predict_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_PredictionService_Predict_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_prediction_service_predict_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.PredictionServiceClient", - "shortName": "PredictionServiceClient" - }, - "fullName": "google.cloud.retail_v2.PredictionServiceClient.predict", - "method": { - "fullName": "google.cloud.retail.v2.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2_generated_prediction_service_predict_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_PredictionService_Predict_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_prediction_service_predict_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2_generated_product_service_add_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_AddFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_add_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2_generated_product_service_add_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_AddFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_add_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2_generated_product_service_add_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_AddLocalInventories_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_add_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2_generated_product_service_add_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_AddLocalInventories_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_add_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "name": "product_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.retail_v2.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2_generated_product_service_create_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_CreateProduct_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_create_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "name": "product_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.retail_v2.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2_generated_product_service_create_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_CreateProduct_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_create_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2_generated_product_service_delete_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_DeleteProduct_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_delete_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2_generated_product_service_delete_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_DeleteProduct_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_delete_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.GetProductRequest" - }, - { - "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.retail_v2.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2_generated_product_service_get_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_GetProduct_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_get_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.GetProductRequest" - }, - { - "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.retail_v2.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2_generated_product_service_get_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_GetProduct_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_get_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2_generated_product_service_import_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_ImportProducts_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_import_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2_generated_product_service_import_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_ImportProducts_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_import_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ListProductsRequest" - }, - { - "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.retail_v2.services.product_service.pagers.ListProductsAsyncPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2_generated_product_service_list_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_ListProducts_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_list_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ListProductsRequest" - }, - { - "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.retail_v2.services.product_service.pagers.ListProductsPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2_generated_product_service_list_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_ListProducts_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_list_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2_generated_product_service_remove_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_remove_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2_generated_product_service_remove_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_remove_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2_generated_product_service_remove_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_RemoveLocalInventories_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_remove_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2_generated_product_service_remove_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_RemoveLocalInventories_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_remove_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2_generated_product_service_set_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_SetInventory_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_set_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2_generated_product_service_set_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_SetInventory_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_set_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "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.retail_v2.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2_generated_product_service_update_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_UpdateProduct_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_update_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "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.retail_v2.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2_generated_product_service_update_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_UpdateProduct_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_update_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.SearchServiceAsyncClient.search", - "method": { - "fullName": "google.cloud.retail.v2.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2_generated_search_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_SearchService_Search_async", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_search_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.SearchServiceClient", - "shortName": "SearchServiceClient" - }, - "fullName": "google.cloud.retail_v2.SearchServiceClient.search", - "method": { - "fullName": "google.cloud.retail.v2.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.services.search_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2_generated_search_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_SearchService_Search_sync", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_search_service_search_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2_generated_user_event_service_collect_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_CollectUserEvent_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_collect_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2_generated_user_event_service_collect_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_CollectUserEvent_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_collect_user_event_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2_generated_user_event_service_import_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_ImportUserEvents_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_import_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2_generated_user_event_service_import_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_ImportUserEvents_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_import_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2_generated_user_event_service_purge_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_PurgeUserEvents_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_purge_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2_generated_user_event_service_purge_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_PurgeUserEvents_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_purge_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2_generated_user_event_service_rejoin_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_RejoinUserEvents_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_rejoin_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2_generated_user_event_service_rejoin_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_RejoinUserEvents_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_rejoin_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2_generated_user_event_service_write_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_WriteUserEvent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_write_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2_generated_user_event_service_write_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_WriteUserEvent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_write_user_event_sync.py" - } - ] -} diff --git a/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py deleted file mode 100644 index 9ed9d278..00000000 --- a/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py +++ /dev/null @@ -1,199 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class retailCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), - 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), - 'create_product': ('parent', 'product', 'product_id', ), - 'delete_product': ('name', ), - 'get_default_branch': ('catalog', ), - 'get_product': ('name', ), - 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), - 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), - 'import_user_events': ('parent', 'input_config', 'errors_config', ), - 'list_catalogs': ('parent', 'page_size', 'page_token', ), - 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', ), - 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), - 'purge_user_events': ('parent', 'filter', 'force', ), - 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), - 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), - 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), - 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', 'labels', 'spell_correction_spec', ), - 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), - 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), - 'update_catalog': ('catalog', 'update_mask', ), - 'update_product': ('product', 'update_mask', 'allow_missing', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=retailCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the retail client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2/setup.py b/owl-bot-staging/v2/setup.py deleted file mode 100644 index 3d49d09f..00000000 --- a/owl-bot-staging/v2/setup.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-retail', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-retail", - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.31.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'googleapis-common-protos >= 1.55.0, <2.0.0dev', - 'proto-plus >= 1.19.7', - ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py deleted file mode 100644 index 23c5a2f7..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py +++ /dev/null @@ -1,2267 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.catalog_service import CatalogServiceAsyncClient -from google.cloud.retail_v2.services.catalog_service import CatalogServiceClient -from google.cloud.retail_v2.services.catalog_service import pagers -from google.cloud.retail_v2.services.catalog_service import transports -from google.cloud.retail_v2.types import catalog -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CatalogServiceClient._get_default_mtls_endpoint(None) is None - assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CatalogServiceGrpcTransport, "grpc"), - (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_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", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_catalog_service_client_get_transport_class(): - transport = CatalogServiceClient.get_transport_class() - available_transports = [ - transports.CatalogServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CatalogServiceClient.get_transport_class("grpc") - assert transport == transports.CatalogServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - CatalogServiceClient, CatalogServiceAsyncClient -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_catalog_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CatalogServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ListCatalogsRequest, - dict, -]) -def test_list_catalogs(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalogs), - '__call__') as call: - client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - -@pytest.mark.asyncio -async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_catalogs_async_from_dict(): - await test_list_catalogs_async(request_type=dict) - - -def test_list_catalogs_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = catalog_service.ListCatalogsResponse() - client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_catalogs( - 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_catalogs_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_catalogs_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_catalogs( - 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_catalogs_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - - -def test_list_catalogs_pager(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_catalogs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, catalog.Catalog) - for i in results) -def test_list_catalogs_pages(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = list(client.list_catalogs(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_catalogs_async_pager(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_catalogs(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, catalog.Catalog) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_catalogs_async_pages(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCatalogRequest, - dict, -]) -def test_update_catalog(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - ) - response = client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_catalog_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalog), - '__call__') as call: - client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - -@pytest.mark.asyncio -async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_catalog_async_from_dict(): - await test_update_catalog_async(request_type=dict) - - -def test_update_catalog_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = gcr_catalog.Catalog() - client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_catalog_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -def test_update_catalog_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_catalog_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.SetDefaultBranchRequest, - dict, -]) -def test_set_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_set_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_set_default_branch_async_from_dict(): - await test_set_default_branch_async(request_type=dict) - - -def test_set_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = None - client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_set_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_set_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetDefaultBranchRequest, - dict, -]) -def test_get_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - ) - response = client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -def test_get_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_default_branch), - '__call__') as call: - client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - )) - response = await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -@pytest.mark.asyncio -async def test_get_default_branch_async_from_dict(): - await test_get_default_branch_async(request_type=dict) - - -def test_get_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = catalog_service.GetDefaultBranchResponse() - client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_get_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_get_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CatalogServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.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 = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CatalogServiceGrpcTransport, - ) - -def test_catalog_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_catalog_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_catalogs', - 'update_catalog', - 'set_default_branch', - 'get_default_branch', - ) - 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_catalog_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.retail_v2.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport( - 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_catalog_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.retail_v2.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport() - adc.assert_called_once() - - -def test_catalog_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) - CatalogServiceClient() - 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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -def test_catalog_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,grpc_helpers", - [ - (transports.CatalogServiceGrpcTransport, grpc_helpers), - (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_catalog_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_no_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_with_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_catalog_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcTransport( - 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_catalog_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcAsyncIOTransport( - 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_branch_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = CatalogServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = CatalogServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_branch_path(path) - assert expected == actual - -def test_catalog_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - } - path = CatalogServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CatalogServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = CatalogServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = CatalogServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = CatalogServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CatalogServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = CatalogServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = CatalogServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = CatalogServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = CatalogServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CatalogServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py deleted file mode 100644 index 35085390..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py +++ /dev/null @@ -1,1451 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.completion_service import CompletionServiceAsyncClient -from google.cloud.retail_v2.services.completion_service import CompletionServiceClient -from google.cloud.retail_v2.services.completion_service import transports -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CompletionServiceClient._get_default_mtls_endpoint(None) is None - assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CompletionServiceGrpcTransport, "grpc"), - (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_completion_service_client_get_transport_class(): - transport = CompletionServiceClient.get_transport_class() - available_transports = [ - transports.CompletionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CompletionServiceClient.get_transport_class("grpc") - assert transport == transports.CompletionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - CompletionServiceClient, CompletionServiceAsyncClient -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_completion_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CompletionServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - ) - response = client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - -@pytest.mark.asyncio -async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - )) - response = await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -@pytest.mark.asyncio -async def test_complete_query_async_from_dict(): - await test_complete_query_async(request_type=dict) - - -def test_complete_query_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = completion_service.CompleteQueryResponse() - client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_complete_query_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) - await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportCompletionDataRequest, - dict, -]) -def test_import_completion_data(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_completion_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - -@pytest.mark.asyncio -async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_completion_data_async_from_dict(): - await test_import_completion_data_async(request_type=dict) - - -def test_import_completion_data_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # 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_completion_data_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CompletionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CompletionServiceGrpcTransport, - ) - -def test_completion_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_completion_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'complete_query', - 'import_completion_data', - ) - 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_completion_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_completion_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport() - adc.assert_called_once() - - -def test_completion_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CompletionServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionServiceGrpcTransport, grpc_helpers), - (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_completion_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_no_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_with_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_completion_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_completion_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_completion_service_grpc_lro_client(): - client = CompletionServiceClient( - 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_completion_service_grpc_lro_async_client(): - client = CompletionServiceAsyncClient( - 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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CompletionServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CompletionServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CompletionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CompletionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = CompletionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CompletionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CompletionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CompletionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = CompletionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CompletionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CompletionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CompletionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CompletionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py deleted file mode 100644 index 0e982c21..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py +++ /dev/null @@ -1,1279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.prediction_service import PredictionServiceAsyncClient -from google.cloud.retail_v2.services.prediction_service import PredictionServiceClient -from google.cloud.retail_v2.services.prediction_service import transports -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import prediction_service -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import promotion -from google.cloud.retail_v2.types import user_event -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PredictionServiceClient._get_default_mtls_endpoint(None) is None - assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PredictionServiceGrpcTransport, "grpc"), - (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_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", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_prediction_service_client_get_transport_class(): - transport = PredictionServiceClient.get_transport_class() - available_transports = [ - transports.PredictionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = PredictionServiceClient.get_transport_class("grpc") - assert transport == transports.PredictionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - PredictionServiceClient, PredictionServiceAsyncClient -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_prediction_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PredictionServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - prediction_service.PredictRequest, - dict, -]) -def test_predict(request_type, transport: str = 'grpc'): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - response = client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - -@pytest.mark.asyncio -async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - )) - response = await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -@pytest.mark.asyncio -async def test_predict_async_from_dict(): - await test_predict_async(request_type=dict) - - -def test_predict_field_headers(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = prediction_service.PredictResponse() - client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_predict_field_headers_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) - await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PredictionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PredictionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.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 = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, - ) - -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'predict', - ) - 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport( - 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport() - adc.assert_called_once() - - -def test_prediction_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) - PredictionServiceClient() - 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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -def test_prediction_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,grpc_helpers", - [ - (transports.PredictionServiceGrpcTransport, grpc_helpers), - (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_prediction_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_no_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_with_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_prediction_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcTransport( - 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_prediction_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcAsyncIOTransport( - 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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_product_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - product = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - "branch": "winkle", - "product": "nautilus", - } - path = PredictionServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PredictionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = PredictionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = PredictionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = PredictionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PredictionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = PredictionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = PredictionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = PredictionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = PredictionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PredictionServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py deleted file mode 100644 index 9d91f54b..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py +++ /dev/null @@ -1,4085 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.product_service import ProductServiceAsyncClient -from google.cloud.retail_v2.services.product_service import ProductServiceClient -from google.cloud.retail_v2.services.product_service import pagers -from google.cloud.retail_v2.services.product_service import transports -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.cloud.retail_v2.types import promotion -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ProductServiceClient._get_default_mtls_endpoint(None) is None - assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ProductServiceGrpcTransport, "grpc"), - (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_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", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_product_service_client_get_transport_class(): - transport = ProductServiceClient.get_transport_class() - available_transports = [ - transports.ProductServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ProductServiceClient.get_transport_class("grpc") - assert transport == transports.ProductServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_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(ProductServiceClient, '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(ProductServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - ProductServiceClient, ProductServiceAsyncClient -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_product_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProductServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.CreateProductRequest, - dict, -]) -def test_create_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_create_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - -@pytest.mark.asyncio -async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_create_product_async_from_dict(): - await test_create_product_async(request_type=dict) - - -def test_create_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - - -def test_create_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - -@pytest.mark.asyncio -async def test_create_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.GetProductRequest, - dict, -]) -def test_get_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_get_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - -@pytest.mark.asyncio -async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_get_product_async_from_dict(): - await test_get_product_async(request_type=dict) - - -def test_get_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = product.Product() - client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.GetProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.GetProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.ListProductsRequest, - dict, -]) -def test_list_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - -@pytest.mark.asyncio -async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_products_async_from_dict(): - await test_list_products_async(request_type=dict) - - -def test_list_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = product_service.ListProductsResponse() - client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_products( - 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_products_flattened_error(): - client = ProductServiceClient( - credentials=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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_products_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_products( - 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_products_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - - -def test_list_products_pager(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_products(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, product.Product) - for i in results) -def test_list_products_pages(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = list(client.list_products(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_products_async_pager(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_products(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, product.Product) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_products_async_pages(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_products(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - product_service.UpdateProductRequest, - dict, -]) -def test_update_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_update_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - -@pytest.mark.asyncio -async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_update_product_async_from_dict(): - await test_update_product_async(request_type=dict) - - -def test_update_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -def test_update_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.DeleteProductRequest, - dict, -]) -def test_delete_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - -@pytest.mark.asyncio -async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_product_async_from_dict(): - await test_delete_product_async(request_type=dict) - - -def test_delete_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = None - client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportProductsRequest, - dict, -]) -def test_import_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - -@pytest.mark.asyncio -async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__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_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_products_async_from_dict(): - await test_import_products_async(request_type=dict) - - -def test_import_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - product_service.SetInventoryRequest, - dict, -]) -def test_set_inventory(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_inventory_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - -@pytest.mark.asyncio -async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_inventory_async_from_dict(): - await test_set_inventory_async(request_type=dict) - - -def test_set_inventory_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_inventory_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -def test_set_inventory_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_set_inventory_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_set_inventory_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_inventory_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddFulfillmentPlacesRequest, - dict, -]) -def test_add_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async_from_dict(): - await test_add_fulfillment_places_async(request_type=dict) - - -def test_add_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveFulfillmentPlacesRequest, - dict, -]) -def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async_from_dict(): - await test_remove_fulfillment_places_async(request_type=dict) - - -def test_remove_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddLocalInventoriesRequest, - dict, -]) -def test_add_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_local_inventories_async_from_dict(): - await test_add_local_inventories_async(request_type=dict) - - -def test_add_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveLocalInventoriesRequest, - dict, -]) -def test_remove_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_local_inventories_async_from_dict(): - await test_remove_local_inventories_async(request_type=dict) - - -def test_remove_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProductServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ProductServiceClient.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 = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProductServiceGrpcTransport, - ) - -def test_product_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_product_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.product_service.transports.ProductServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_product', - 'get_product', - 'list_products', - 'update_product', - 'delete_product', - 'import_products', - 'set_inventory', - 'add_fulfillment_places', - 'remove_fulfillment_places', - 'add_local_inventories', - 'remove_local_inventories', - ) - 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_product_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.retail_v2.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport( - 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_product_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.retail_v2.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport() - adc.assert_called_once() - - -def test_product_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) - ProductServiceClient() - 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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - ], -) -def test_product_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,grpc_helpers", - [ - (transports.ProductServiceGrpcTransport, grpc_helpers), - (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_product_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_no_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_with_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_product_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcTransport( - 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_product_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcAsyncIOTransport( - 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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_product_service_grpc_lro_client(): - client = ProductServiceClient( - 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_product_service_grpc_lro_async_client(): - client = ProductServiceAsyncClient( - 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" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = ProductServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = ProductServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = ProductServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = ProductServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProductServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ProductServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProductServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ProductServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProductServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ProductServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ProductServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ProductServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ProductServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ProductServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ProductServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py deleted file mode 100644 index a9c77623..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py +++ /dev/null @@ -1,1496 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.search_service import SearchServiceAsyncClient -from google.cloud.retail_v2.services.search_service import SearchServiceClient -from google.cloud.retail_v2.services.search_service import pagers -from google.cloud.retail_v2.services.search_service import transports -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import search_service -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SearchServiceClient._get_default_mtls_endpoint(None) is None - assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SearchServiceGrpcTransport, "grpc"), - (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_search_service_client_get_transport_class(): - transport = SearchServiceClient.get_transport_class() - available_transports = [ - transports.SearchServiceGrpcTransport, - ] - assert transport in available_transports - - transport = SearchServiceClient.get_transport_class("grpc") - assert transport == transports.SearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - SearchServiceClient, SearchServiceAsyncClient -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SearchServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - search_service.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - - -def test_search_field_headers(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = search_service.SearchResponse() - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_field_headers_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_search_pager(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('placement', ''), - )), - ) - pager = client.search(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_async_pager(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, - ) - -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_search_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_search_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport() - adc.assert_called_once() - - -def test_search_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SearchServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SearchServiceGrpcTransport, grpc_helpers), - (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_search_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_no_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_with_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_branch_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = SearchServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = SearchServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = SearchServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = SearchServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py deleted file mode 100644 index 80f41751..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py +++ /dev/null @@ -1,1988 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.retail_v2.services.user_event_service import UserEventServiceClient -from google.cloud.retail_v2.services.user_event_service import transports -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import promotion -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, UserEventServiceAsyncClient -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - ) - response = client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = user_event.UserEvent() - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) - await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeUserEventsRequest, - dict, -]) -def test_purge_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - -@pytest.mark.asyncio -async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_user_events_async_from_dict(): - await test_purge_user_events_async(request_type=dict) - - -def test_purge_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_purge_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.RejoinUserEventsRequest, - dict, -]) -def test_rejoin_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_rejoin_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - -@pytest.mark.asyncio -async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_rejoin_user_events_async_from_dict(): - await test_rejoin_user_events_async(request_type=dict) - - -def test_rejoin_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_rejoin_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'purge_user_events', - 'import_user_events', - 'rejoin_user_events', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_user_event_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_user_event_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -def test_user_event_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - UserEventServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_no_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_with_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = UserEventServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = UserEventServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_product_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - product = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - "branch": "whelk", - "product": "octopus", - } - path = UserEventServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2alpha/.coveragerc b/owl-bot-staging/v2alpha/.coveragerc deleted file mode 100644 index a8b114f0..00000000 --- a/owl-bot-staging/v2alpha/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/retail/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2alpha/.flake8 b/owl-bot-staging/v2alpha/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v2alpha/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2alpha/MANIFEST.in b/owl-bot-staging/v2alpha/MANIFEST.in deleted file mode 100644 index 3ee710cc..00000000 --- a/owl-bot-staging/v2alpha/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/retail *.py -recursive-include google/cloud/retail_v2alpha *.py diff --git a/owl-bot-staging/v2alpha/README.rst b/owl-bot-staging/v2alpha/README.rst deleted file mode 100644 index cb039760..00000000 --- a/owl-bot-staging/v2alpha/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Retail API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Retail API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2alpha/docs/conf.py b/owl-bot-staging/v2alpha/docs/conf.py deleted file mode 100644 index 5be9eb4b..00000000 --- a/owl-bot-staging/v2alpha/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-retail documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-retail" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-retail-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-retail.tex", - u"google-cloud-retail Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-retail", - u"Google Cloud Retail Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-retail", - u"google-cloud-retail Documentation", - author, - "google-cloud-retail", - "GAPIC library for Google Cloud Retail API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2alpha/docs/index.rst b/owl-bot-staging/v2alpha/docs/index.rst deleted file mode 100644 index dc0a2096..00000000 --- a/owl-bot-staging/v2alpha/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - retail_v2alpha/services - retail_v2alpha/types diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst deleted file mode 100644 index 745d0cf4..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CatalogService --------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.catalog_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.catalog_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst deleted file mode 100644 index 3a276433..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CompletionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2alpha.services.completion_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst deleted file mode 100644 index 36aaf9b6..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ControlService --------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.control_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.control_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst deleted file mode 100644 index b659cf98..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -PredictionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2alpha.services.prediction_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst deleted file mode 100644 index acbb336e..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ProductService --------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.product_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.product_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst deleted file mode 100644 index ad4c486d..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SearchService -------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst deleted file mode 100644 index edeb8cfc..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst +++ /dev/null @@ -1,13 +0,0 @@ -Services for Google Cloud Retail v2alpha API -============================================ -.. toctree:: - :maxdepth: 2 - - catalog_service - completion_service - control_service - prediction_service - product_service - search_service - serving_config_service - user_event_service diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst deleted file mode 100644 index c1516860..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ServingConfigService --------------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.serving_config_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.serving_config_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst deleted file mode 100644 index c1445ad6..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Retail v2alpha API -========================================= - -.. automodule:: google.cloud.retail_v2alpha.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst deleted file mode 100644 index 8c56485c..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.user_event_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py deleted file mode 100644 index a17a283b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py +++ /dev/null @@ -1,281 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.retail_v2alpha.services.catalog_service.client import CatalogServiceClient -from google.cloud.retail_v2alpha.services.catalog_service.async_client import CatalogServiceAsyncClient -from google.cloud.retail_v2alpha.services.completion_service.client import CompletionServiceClient -from google.cloud.retail_v2alpha.services.completion_service.async_client import CompletionServiceAsyncClient -from google.cloud.retail_v2alpha.services.control_service.client import ControlServiceClient -from google.cloud.retail_v2alpha.services.control_service.async_client import ControlServiceAsyncClient -from google.cloud.retail_v2alpha.services.prediction_service.client import PredictionServiceClient -from google.cloud.retail_v2alpha.services.prediction_service.async_client import PredictionServiceAsyncClient -from google.cloud.retail_v2alpha.services.product_service.client import ProductServiceClient -from google.cloud.retail_v2alpha.services.product_service.async_client import ProductServiceAsyncClient -from google.cloud.retail_v2alpha.services.search_service.client import SearchServiceClient -from google.cloud.retail_v2alpha.services.search_service.async_client import SearchServiceAsyncClient -from google.cloud.retail_v2alpha.services.serving_config_service.client import ServingConfigServiceClient -from google.cloud.retail_v2alpha.services.serving_config_service.async_client import ServingConfigServiceAsyncClient -from google.cloud.retail_v2alpha.services.user_event_service.client import UserEventServiceClient -from google.cloud.retail_v2alpha.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.retail_v2alpha.types.catalog import AttributesConfig -from google.cloud.retail_v2alpha.types.catalog import Catalog -from google.cloud.retail_v2alpha.types.catalog import CatalogAttribute -from google.cloud.retail_v2alpha.types.catalog import CompletionConfig -from google.cloud.retail_v2alpha.types.catalog import MerchantCenterLink -from google.cloud.retail_v2alpha.types.catalog import MerchantCenterLinkingConfig -from google.cloud.retail_v2alpha.types.catalog import ProductLevelConfig -from google.cloud.retail_v2alpha.types.catalog_service import AddCatalogAttributeRequest -from google.cloud.retail_v2alpha.types.catalog_service import GetAttributesConfigRequest -from google.cloud.retail_v2alpha.types.catalog_service import GetCompletionConfigRequest -from google.cloud.retail_v2alpha.types.catalog_service import GetDefaultBranchRequest -from google.cloud.retail_v2alpha.types.catalog_service import GetDefaultBranchResponse -from google.cloud.retail_v2alpha.types.catalog_service import ListCatalogsRequest -from google.cloud.retail_v2alpha.types.catalog_service import ListCatalogsResponse -from google.cloud.retail_v2alpha.types.catalog_service import RemoveCatalogAttributeRequest -from google.cloud.retail_v2alpha.types.catalog_service import ReplaceCatalogAttributeRequest -from google.cloud.retail_v2alpha.types.catalog_service import SetDefaultBranchRequest -from google.cloud.retail_v2alpha.types.catalog_service import UpdateAttributesConfigRequest -from google.cloud.retail_v2alpha.types.catalog_service import UpdateCatalogRequest -from google.cloud.retail_v2alpha.types.catalog_service import UpdateCompletionConfigRequest -from google.cloud.retail_v2alpha.types.common import Audience -from google.cloud.retail_v2alpha.types.common import ColorInfo -from google.cloud.retail_v2alpha.types.common import Condition -from google.cloud.retail_v2alpha.types.common import CustomAttribute -from google.cloud.retail_v2alpha.types.common import FulfillmentInfo -from google.cloud.retail_v2alpha.types.common import Image -from google.cloud.retail_v2alpha.types.common import Interval -from google.cloud.retail_v2alpha.types.common import LocalInventory -from google.cloud.retail_v2alpha.types.common import PriceInfo -from google.cloud.retail_v2alpha.types.common import Rating -from google.cloud.retail_v2alpha.types.common import Rule -from google.cloud.retail_v2alpha.types.common import UserInfo -from google.cloud.retail_v2alpha.types.common import AttributeConfigLevel -from google.cloud.retail_v2alpha.types.common import SearchSolutionUseCase -from google.cloud.retail_v2alpha.types.common import SolutionType -from google.cloud.retail_v2alpha.types.completion_service import CompleteQueryRequest -from google.cloud.retail_v2alpha.types.completion_service import CompleteQueryResponse -from google.cloud.retail_v2alpha.types.control import Control -from google.cloud.retail_v2alpha.types.control_service import CreateControlRequest -from google.cloud.retail_v2alpha.types.control_service import DeleteControlRequest -from google.cloud.retail_v2alpha.types.control_service import GetControlRequest -from google.cloud.retail_v2alpha.types.control_service import ListControlsRequest -from google.cloud.retail_v2alpha.types.control_service import ListControlsResponse -from google.cloud.retail_v2alpha.types.control_service import UpdateControlRequest -from google.cloud.retail_v2alpha.types.export_config import ExportErrorsConfig -from google.cloud.retail_v2alpha.types.export_config import ExportMetadata -from google.cloud.retail_v2alpha.types.export_config import ExportProductsResponse -from google.cloud.retail_v2alpha.types.export_config import ExportUserEventsResponse -from google.cloud.retail_v2alpha.types.import_config import BigQuerySource -from google.cloud.retail_v2alpha.types.import_config import CompletionDataInputConfig -from google.cloud.retail_v2alpha.types.import_config import GcsSource -from google.cloud.retail_v2alpha.types.import_config import ImportCompletionDataRequest -from google.cloud.retail_v2alpha.types.import_config import ImportCompletionDataResponse -from google.cloud.retail_v2alpha.types.import_config import ImportErrorsConfig -from google.cloud.retail_v2alpha.types.import_config import ImportMetadata -from google.cloud.retail_v2alpha.types.import_config import ImportProductsRequest -from google.cloud.retail_v2alpha.types.import_config import ImportProductsResponse -from google.cloud.retail_v2alpha.types.import_config import ImportUserEventsRequest -from google.cloud.retail_v2alpha.types.import_config import ImportUserEventsResponse -from google.cloud.retail_v2alpha.types.import_config import ProductInlineSource -from google.cloud.retail_v2alpha.types.import_config import ProductInputConfig -from google.cloud.retail_v2alpha.types.import_config import UserEventImportSummary -from google.cloud.retail_v2alpha.types.import_config import UserEventInlineSource -from google.cloud.retail_v2alpha.types.import_config import UserEventInputConfig -from google.cloud.retail_v2alpha.types.prediction_service import PredictRequest -from google.cloud.retail_v2alpha.types.prediction_service import PredictResponse -from google.cloud.retail_v2alpha.types.product import Product -from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesMetadata -from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesRequest -from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesResponse -from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesMetadata -from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesRequest -from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesResponse -from google.cloud.retail_v2alpha.types.product_service import CreateProductRequest -from google.cloud.retail_v2alpha.types.product_service import DeleteProductRequest -from google.cloud.retail_v2alpha.types.product_service import GetProductRequest -from google.cloud.retail_v2alpha.types.product_service import ListProductsRequest -from google.cloud.retail_v2alpha.types.product_service import ListProductsResponse -from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesMetadata -from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesRequest -from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesResponse -from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesMetadata -from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesRequest -from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesResponse -from google.cloud.retail_v2alpha.types.product_service import SetInventoryMetadata -from google.cloud.retail_v2alpha.types.product_service import SetInventoryRequest -from google.cloud.retail_v2alpha.types.product_service import SetInventoryResponse -from google.cloud.retail_v2alpha.types.product_service import UpdateProductRequest -from google.cloud.retail_v2alpha.types.promotion import Promotion -from google.cloud.retail_v2alpha.types.purge_config import PurgeMetadata -from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsMetadata -from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsRequest -from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsResponse -from google.cloud.retail_v2alpha.types.purge_config import PurgeUserEventsRequest -from google.cloud.retail_v2alpha.types.purge_config import PurgeUserEventsResponse -from google.cloud.retail_v2alpha.types.search_service import SearchRequest -from google.cloud.retail_v2alpha.types.search_service import SearchResponse -from google.cloud.retail_v2alpha.types.serving_config import ServingConfig -from google.cloud.retail_v2alpha.types.serving_config_service import AddControlRequest -from google.cloud.retail_v2alpha.types.serving_config_service import CreateServingConfigRequest -from google.cloud.retail_v2alpha.types.serving_config_service import DeleteServingConfigRequest -from google.cloud.retail_v2alpha.types.serving_config_service import GetServingConfigRequest -from google.cloud.retail_v2alpha.types.serving_config_service import ListServingConfigsRequest -from google.cloud.retail_v2alpha.types.serving_config_service import ListServingConfigsResponse -from google.cloud.retail_v2alpha.types.serving_config_service import RemoveControlRequest -from google.cloud.retail_v2alpha.types.serving_config_service import UpdateServingConfigRequest -from google.cloud.retail_v2alpha.types.user_event import CompletionDetail -from google.cloud.retail_v2alpha.types.user_event import ProductDetail -from google.cloud.retail_v2alpha.types.user_event import PurchaseTransaction -from google.cloud.retail_v2alpha.types.user_event import UserEvent -from google.cloud.retail_v2alpha.types.user_event_service import CollectUserEventRequest -from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsMetadata -from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsRequest -from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsResponse -from google.cloud.retail_v2alpha.types.user_event_service import WriteUserEventRequest - -__all__ = ('CatalogServiceClient', - 'CatalogServiceAsyncClient', - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', - 'ControlServiceClient', - 'ControlServiceAsyncClient', - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', - 'ProductServiceClient', - 'ProductServiceAsyncClient', - 'SearchServiceClient', - 'SearchServiceAsyncClient', - 'ServingConfigServiceClient', - 'ServingConfigServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'AttributesConfig', - 'Catalog', - 'CatalogAttribute', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'ProductLevelConfig', - 'AddCatalogAttributeRequest', - 'GetAttributesConfigRequest', - 'GetCompletionConfigRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - 'SetDefaultBranchRequest', - 'UpdateAttributesConfigRequest', - 'UpdateCatalogRequest', - 'UpdateCompletionConfigRequest', - 'Audience', - 'ColorInfo', - 'Condition', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'Rule', - 'UserInfo', - 'AttributeConfigLevel', - 'SearchSolutionUseCase', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Control', - 'CreateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - 'UpdateControlRequest', - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeProductsMetadata', - 'PurgeProductsRequest', - 'PurgeProductsResponse', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'ServingConfig', - 'AddControlRequest', - 'CreateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'RemoveControlRequest', - 'UpdateServingConfigRequest', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail/py.typed b/owl-bot-staging/v2alpha/google/cloud/retail/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py deleted file mode 100644 index e515a173..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py +++ /dev/null @@ -1,282 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.catalog_service import CatalogServiceClient -from .services.catalog_service import CatalogServiceAsyncClient -from .services.completion_service import CompletionServiceClient -from .services.completion_service import CompletionServiceAsyncClient -from .services.control_service import ControlServiceClient -from .services.control_service import ControlServiceAsyncClient -from .services.prediction_service import PredictionServiceClient -from .services.prediction_service import PredictionServiceAsyncClient -from .services.product_service import ProductServiceClient -from .services.product_service import ProductServiceAsyncClient -from .services.search_service import SearchServiceClient -from .services.search_service import SearchServiceAsyncClient -from .services.serving_config_service import ServingConfigServiceClient -from .services.serving_config_service import ServingConfigServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.catalog import AttributesConfig -from .types.catalog import Catalog -from .types.catalog import CatalogAttribute -from .types.catalog import CompletionConfig -from .types.catalog import MerchantCenterLink -from .types.catalog import MerchantCenterLinkingConfig -from .types.catalog import ProductLevelConfig -from .types.catalog_service import AddCatalogAttributeRequest -from .types.catalog_service import GetAttributesConfigRequest -from .types.catalog_service import GetCompletionConfigRequest -from .types.catalog_service import GetDefaultBranchRequest -from .types.catalog_service import GetDefaultBranchResponse -from .types.catalog_service import ListCatalogsRequest -from .types.catalog_service import ListCatalogsResponse -from .types.catalog_service import RemoveCatalogAttributeRequest -from .types.catalog_service import ReplaceCatalogAttributeRequest -from .types.catalog_service import SetDefaultBranchRequest -from .types.catalog_service import UpdateAttributesConfigRequest -from .types.catalog_service import UpdateCatalogRequest -from .types.catalog_service import UpdateCompletionConfigRequest -from .types.common import Audience -from .types.common import ColorInfo -from .types.common import Condition -from .types.common import CustomAttribute -from .types.common import FulfillmentInfo -from .types.common import Image -from .types.common import Interval -from .types.common import LocalInventory -from .types.common import PriceInfo -from .types.common import Rating -from .types.common import Rule -from .types.common import UserInfo -from .types.common import AttributeConfigLevel -from .types.common import SearchSolutionUseCase -from .types.common import SolutionType -from .types.completion_service import CompleteQueryRequest -from .types.completion_service import CompleteQueryResponse -from .types.control import Control -from .types.control_service import CreateControlRequest -from .types.control_service import DeleteControlRequest -from .types.control_service import GetControlRequest -from .types.control_service import ListControlsRequest -from .types.control_service import ListControlsResponse -from .types.control_service import UpdateControlRequest -from .types.export_config import ExportErrorsConfig -from .types.export_config import ExportMetadata -from .types.export_config import ExportProductsResponse -from .types.export_config import ExportUserEventsResponse -from .types.import_config import BigQuerySource -from .types.import_config import CompletionDataInputConfig -from .types.import_config import GcsSource -from .types.import_config import ImportCompletionDataRequest -from .types.import_config import ImportCompletionDataResponse -from .types.import_config import ImportErrorsConfig -from .types.import_config import ImportMetadata -from .types.import_config import ImportProductsRequest -from .types.import_config import ImportProductsResponse -from .types.import_config import ImportUserEventsRequest -from .types.import_config import ImportUserEventsResponse -from .types.import_config import ProductInlineSource -from .types.import_config import ProductInputConfig -from .types.import_config import UserEventImportSummary -from .types.import_config import UserEventInlineSource -from .types.import_config import UserEventInputConfig -from .types.prediction_service import PredictRequest -from .types.prediction_service import PredictResponse -from .types.product import Product -from .types.product_service import AddFulfillmentPlacesMetadata -from .types.product_service import AddFulfillmentPlacesRequest -from .types.product_service import AddFulfillmentPlacesResponse -from .types.product_service import AddLocalInventoriesMetadata -from .types.product_service import AddLocalInventoriesRequest -from .types.product_service import AddLocalInventoriesResponse -from .types.product_service import CreateProductRequest -from .types.product_service import DeleteProductRequest -from .types.product_service import GetProductRequest -from .types.product_service import ListProductsRequest -from .types.product_service import ListProductsResponse -from .types.product_service import RemoveFulfillmentPlacesMetadata -from .types.product_service import RemoveFulfillmentPlacesRequest -from .types.product_service import RemoveFulfillmentPlacesResponse -from .types.product_service import RemoveLocalInventoriesMetadata -from .types.product_service import RemoveLocalInventoriesRequest -from .types.product_service import RemoveLocalInventoriesResponse -from .types.product_service import SetInventoryMetadata -from .types.product_service import SetInventoryRequest -from .types.product_service import SetInventoryResponse -from .types.product_service import UpdateProductRequest -from .types.promotion import Promotion -from .types.purge_config import PurgeMetadata -from .types.purge_config import PurgeProductsMetadata -from .types.purge_config import PurgeProductsRequest -from .types.purge_config import PurgeProductsResponse -from .types.purge_config import PurgeUserEventsRequest -from .types.purge_config import PurgeUserEventsResponse -from .types.search_service import SearchRequest -from .types.search_service import SearchResponse -from .types.serving_config import ServingConfig -from .types.serving_config_service import AddControlRequest -from .types.serving_config_service import CreateServingConfigRequest -from .types.serving_config_service import DeleteServingConfigRequest -from .types.serving_config_service import GetServingConfigRequest -from .types.serving_config_service import ListServingConfigsRequest -from .types.serving_config_service import ListServingConfigsResponse -from .types.serving_config_service import RemoveControlRequest -from .types.serving_config_service import UpdateServingConfigRequest -from .types.user_event import CompletionDetail -from .types.user_event import ProductDetail -from .types.user_event import PurchaseTransaction -from .types.user_event import UserEvent -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import RejoinUserEventsMetadata -from .types.user_event_service import RejoinUserEventsRequest -from .types.user_event_service import RejoinUserEventsResponse -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CatalogServiceAsyncClient', - 'CompletionServiceAsyncClient', - 'ControlServiceAsyncClient', - 'PredictionServiceAsyncClient', - 'ProductServiceAsyncClient', - 'SearchServiceAsyncClient', - 'ServingConfigServiceAsyncClient', - 'UserEventServiceAsyncClient', -'AddCatalogAttributeRequest', -'AddControlRequest', -'AddFulfillmentPlacesMetadata', -'AddFulfillmentPlacesRequest', -'AddFulfillmentPlacesResponse', -'AddLocalInventoriesMetadata', -'AddLocalInventoriesRequest', -'AddLocalInventoriesResponse', -'AttributeConfigLevel', -'AttributesConfig', -'Audience', -'BigQuerySource', -'Catalog', -'CatalogAttribute', -'CatalogServiceClient', -'CollectUserEventRequest', -'ColorInfo', -'CompleteQueryRequest', -'CompleteQueryResponse', -'CompletionConfig', -'CompletionDataInputConfig', -'CompletionDetail', -'CompletionServiceClient', -'Condition', -'Control', -'ControlServiceClient', -'CreateControlRequest', -'CreateProductRequest', -'CreateServingConfigRequest', -'CustomAttribute', -'DeleteControlRequest', -'DeleteProductRequest', -'DeleteServingConfigRequest', -'ExportErrorsConfig', -'ExportMetadata', -'ExportProductsResponse', -'ExportUserEventsResponse', -'FulfillmentInfo', -'GcsSource', -'GetAttributesConfigRequest', -'GetCompletionConfigRequest', -'GetControlRequest', -'GetDefaultBranchRequest', -'GetDefaultBranchResponse', -'GetProductRequest', -'GetServingConfigRequest', -'Image', -'ImportCompletionDataRequest', -'ImportCompletionDataResponse', -'ImportErrorsConfig', -'ImportMetadata', -'ImportProductsRequest', -'ImportProductsResponse', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'Interval', -'ListCatalogsRequest', -'ListCatalogsResponse', -'ListControlsRequest', -'ListControlsResponse', -'ListProductsRequest', -'ListProductsResponse', -'ListServingConfigsRequest', -'ListServingConfigsResponse', -'LocalInventory', -'MerchantCenterLink', -'MerchantCenterLinkingConfig', -'PredictRequest', -'PredictResponse', -'PredictionServiceClient', -'PriceInfo', -'Product', -'ProductDetail', -'ProductInlineSource', -'ProductInputConfig', -'ProductLevelConfig', -'ProductServiceClient', -'Promotion', -'PurchaseTransaction', -'PurgeMetadata', -'PurgeProductsMetadata', -'PurgeProductsRequest', -'PurgeProductsResponse', -'PurgeUserEventsRequest', -'PurgeUserEventsResponse', -'Rating', -'RejoinUserEventsMetadata', -'RejoinUserEventsRequest', -'RejoinUserEventsResponse', -'RemoveCatalogAttributeRequest', -'RemoveControlRequest', -'RemoveFulfillmentPlacesMetadata', -'RemoveFulfillmentPlacesRequest', -'RemoveFulfillmentPlacesResponse', -'RemoveLocalInventoriesMetadata', -'RemoveLocalInventoriesRequest', -'RemoveLocalInventoriesResponse', -'ReplaceCatalogAttributeRequest', -'Rule', -'SearchRequest', -'SearchResponse', -'SearchServiceClient', -'SearchSolutionUseCase', -'ServingConfig', -'ServingConfigServiceClient', -'SetDefaultBranchRequest', -'SetInventoryMetadata', -'SetInventoryRequest', -'SetInventoryResponse', -'SolutionType', -'UpdateAttributesConfigRequest', -'UpdateCatalogRequest', -'UpdateCompletionConfigRequest', -'UpdateControlRequest', -'UpdateProductRequest', -'UpdateServingConfigRequest', -'UserEvent', -'UserEventImportSummary', -'UserEventInlineSource', -'UserEventInputConfig', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json deleted file mode 100644 index 543e36d6..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json +++ /dev/null @@ -1,561 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.retail_v2alpha", - "protoPackage": "google.cloud.retail.v2alpha", - "schema": "1.0", - "services": { - "CatalogService": { - "clients": { - "grpc": { - "libraryClient": "CatalogServiceClient", - "rpcs": { - "AddCatalogAttribute": { - "methods": [ - "add_catalog_attribute" - ] - }, - "GetAttributesConfig": { - "methods": [ - "get_attributes_config" - ] - }, - "GetCompletionConfig": { - "methods": [ - "get_completion_config" - ] - }, - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "RemoveCatalogAttribute": { - "methods": [ - "remove_catalog_attribute" - ] - }, - "ReplaceCatalogAttribute": { - "methods": [ - "replace_catalog_attribute" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateAttributesConfig": { - "methods": [ - "update_attributes_config" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - }, - "UpdateCompletionConfig": { - "methods": [ - "update_completion_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CatalogServiceAsyncClient", - "rpcs": { - "AddCatalogAttribute": { - "methods": [ - "add_catalog_attribute" - ] - }, - "GetAttributesConfig": { - "methods": [ - "get_attributes_config" - ] - }, - "GetCompletionConfig": { - "methods": [ - "get_completion_config" - ] - }, - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "RemoveCatalogAttribute": { - "methods": [ - "remove_catalog_attribute" - ] - }, - "ReplaceCatalogAttribute": { - "methods": [ - "replace_catalog_attribute" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateAttributesConfig": { - "methods": [ - "update_attributes_config" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - }, - "UpdateCompletionConfig": { - "methods": [ - "update_completion_config" - ] - } - } - } - } - }, - "CompletionService": { - "clients": { - "grpc": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CompletionServiceAsyncClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - } - } - }, - "ControlService": { - "clients": { - "grpc": { - "libraryClient": "ControlServiceClient", - "rpcs": { - "CreateControl": { - "methods": [ - "create_control" - ] - }, - "DeleteControl": { - "methods": [ - "delete_control" - ] - }, - "GetControl": { - "methods": [ - "get_control" - ] - }, - "ListControls": { - "methods": [ - "list_controls" - ] - }, - "UpdateControl": { - "methods": [ - "update_control" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ControlServiceAsyncClient", - "rpcs": { - "CreateControl": { - "methods": [ - "create_control" - ] - }, - "DeleteControl": { - "methods": [ - "delete_control" - ] - }, - "GetControl": { - "methods": [ - "get_control" - ] - }, - "ListControls": { - "methods": [ - "list_controls" - ] - }, - "UpdateControl": { - "methods": [ - "update_control" - ] - } - } - } - } - }, - "PredictionService": { - "clients": { - "grpc": { - "libraryClient": "PredictionServiceClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PredictionServiceAsyncClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - } - } - }, - "ProductService": { - "clients": { - "grpc": { - "libraryClient": "ProductServiceClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "PurgeProducts": { - "methods": [ - "purge_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProductServiceAsyncClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "PurgeProducts": { - "methods": [ - "purge_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - } - } - }, - "SearchService": { - "clients": { - "grpc": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SearchServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - }, - "ServingConfigService": { - "clients": { - "grpc": { - "libraryClient": "ServingConfigServiceClient", - "rpcs": { - "AddControl": { - "methods": [ - "add_control" - ] - }, - "CreateServingConfig": { - "methods": [ - "create_serving_config" - ] - }, - "DeleteServingConfig": { - "methods": [ - "delete_serving_config" - ] - }, - "GetServingConfig": { - "methods": [ - "get_serving_config" - ] - }, - "ListServingConfigs": { - "methods": [ - "list_serving_configs" - ] - }, - "RemoveControl": { - "methods": [ - "remove_control" - ] - }, - "UpdateServingConfig": { - "methods": [ - "update_serving_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ServingConfigServiceAsyncClient", - "rpcs": { - "AddControl": { - "methods": [ - "add_control" - ] - }, - "CreateServingConfig": { - "methods": [ - "create_serving_config" - ] - }, - "DeleteServingConfig": { - "methods": [ - "delete_serving_config" - ] - }, - "GetServingConfig": { - "methods": [ - "get_serving_config" - ] - }, - "ListServingConfigs": { - "methods": [ - "list_serving_configs" - ] - }, - "RemoveControl": { - "methods": [ - "remove_control" - ] - }, - "UpdateServingConfig": { - "methods": [ - "update_serving_config" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py deleted file mode 100644 index d276b897..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CatalogServiceClient -from .async_client import CatalogServiceAsyncClient - -__all__ = ( - 'CatalogServiceClient', - 'CatalogServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py deleted file mode 100644 index e828ae6f..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py +++ /dev/null @@ -1,1352 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.catalog_service import pagers -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport -from .client import CatalogServiceClient - - -class CatalogServiceAsyncClient: - """Service for managing catalog configuration.""" - - _client: CatalogServiceClient - - DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT - - attributes_config_path = staticmethod(CatalogServiceClient.attributes_config_path) - parse_attributes_config_path = staticmethod(CatalogServiceClient.parse_attributes_config_path) - branch_path = staticmethod(CatalogServiceClient.branch_path) - parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) - catalog_path = staticmethod(CatalogServiceClient.catalog_path) - parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) - completion_config_path = staticmethod(CatalogServiceClient.completion_config_path) - parse_completion_config_path = staticmethod(CatalogServiceClient.parse_completion_config_path) - common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CatalogServiceClient.common_project_path) - parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) - common_location_path = staticmethod(CatalogServiceClient.common_location_path) - parse_common_location_path = staticmethod(CatalogServiceClient.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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CatalogServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsAsyncPager: - r"""Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_list_catalogs(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - parent (:class:`str`): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2alpha.Catalog]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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsAsyncPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.ListCatalogsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_catalogs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCatalogsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_catalog(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2alpha.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2alpha.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] - method. - catalog (:class:`google.cloud.retail_v2alpha.types.Catalog`): - Required. The - [Catalog][google.cloud.retail.v2alpha.Catalog] to - update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2alpha.Catalog], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Catalog][google.cloud.retail.v2alpha.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2alpha.Catalog] to - update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCatalogRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_catalog, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_set_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (:class:`str`): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.SetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (:class:`str`): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # 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_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_completion_config(self, - request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Gets a - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] - method. - name (:class:`str`): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - - 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.retail_v2alpha.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetCompletionConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_completion_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_completion_config(self, - request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, - *, - completion_config: catalog.CompletionConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Updates the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - completion_config = retail_v2alpha.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2alpha.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = await client.update_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] - method. - completion_config (:class:`google.cloud.retail_v2alpha.types.CompletionConfig`): - Required. The - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``completion_config`` 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 - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([completion_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCompletionConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if completion_config is not None: - request.completion_config = completion_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_completion_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("completion_config.name", request.completion_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_attributes_config(self, - request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Gets an - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] - method. - name (:class:`str`): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - - 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.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetAttributesConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_attributes_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_attributes_config(self, - request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, - *, - attributes_config: catalog.AttributesConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Updates the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - attributes_config = retail_v2alpha.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2alpha.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = await client.update_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] - method. - attributes_config (:class:`google.cloud.retail_v2alpha.types.AttributesConfig`): - Required. The - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. - - This corresponds to the ``attributes_config`` 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 - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([attributes_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateAttributesConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attributes_config is not None: - request.attributes_config = attributes_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_attributes_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config.name", request.attributes_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def add_catalog_attribute(self, - request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Adds the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_add_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.AddCatalogAttributeRequest(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.add_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def remove_catalog_attribute(self, - request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Removes the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = await client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.RemoveCatalogAttributeRequest(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.remove_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def replace_catalog_attribute(self, - request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Replaces the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.ReplaceCatalogAttributeRequest(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.replace_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py deleted file mode 100644 index 19946bec..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py +++ /dev/null @@ -1,1581 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.catalog_service import pagers -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CatalogServiceGrpcTransport -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -class CatalogServiceClientMeta(type): - """Metaclass for the CatalogService 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[CatalogServiceTransport]] - _transport_registry["grpc"] = CatalogServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CatalogServiceTransport]: - """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): - """Service for managing catalog configuration.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CatalogServiceClient: 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: - CatalogServiceClient: 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) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def attributes_config_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified attributes_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_attributes_config_path(path: str) -> Dict[str,str]: - """Parses a attributes_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/attributesConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def completion_config_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified completion_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_completion_config_path(path: str) -> Dict[str,str]: - """Parses a completion_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/completionConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CatalogServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CatalogServiceTransport): - # transport is a CatalogServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsPager: - r"""Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_list_catalogs(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2alpha.Catalog]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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ListCatalogsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ListCatalogsRequest): - request = catalog_service.ListCatalogsRequest(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_catalogs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCatalogsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_catalog(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2alpha.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2alpha.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] - method. - catalog (google.cloud.retail_v2alpha.types.Catalog): - Required. The - [Catalog][google.cloud.retail.v2alpha.Catalog] to - update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2alpha.Catalog], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Catalog][google.cloud.retail.v2alpha.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2alpha.Catalog] to - update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCatalogRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCatalogRequest): - request = catalog_service.UpdateCatalogRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - 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_catalog] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_set_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.SetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.SetDefaultBranchRequest): - request = catalog_service.SetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetDefaultBranchRequest): - request = catalog_service.GetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_completion_config(self, - request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Gets a - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] - method. - name (str): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - - 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.retail_v2alpha.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetCompletionConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetCompletionConfigRequest): - request = catalog_service.GetCompletionConfigRequest(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_completion_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_completion_config(self, - request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, - *, - completion_config: catalog.CompletionConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Updates the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - completion_config = retail_v2alpha.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2alpha.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = client.update_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] - method. - completion_config (google.cloud.retail_v2alpha.types.CompletionConfig): - Required. The - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``completion_config`` 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 - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([completion_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCompletionConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCompletionConfigRequest): - request = catalog_service.UpdateCompletionConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if completion_config is not None: - request.completion_config = completion_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_completion_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("completion_config.name", request.completion_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_attributes_config(self, - request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Gets an - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] - method. - name (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - - 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.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetAttributesConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetAttributesConfigRequest): - request = catalog_service.GetAttributesConfigRequest(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_attributes_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_attributes_config(self, - request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, - *, - attributes_config: catalog.AttributesConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Updates the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - attributes_config = retail_v2alpha.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2alpha.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = client.update_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] - method. - attributes_config (google.cloud.retail_v2alpha.types.AttributesConfig): - Required. The - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. - - This corresponds to the ``attributes_config`` 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 - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([attributes_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateAttributesConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateAttributesConfigRequest): - request = catalog_service.UpdateAttributesConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attributes_config is not None: - request.attributes_config = attributes_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_attributes_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config.name", request.attributes_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def add_catalog_attribute(self, - request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Adds the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_add_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.AddCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.AddCatalogAttributeRequest): - request = catalog_service.AddCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def remove_catalog_attribute(self, - request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Removes the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.RemoveCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.RemoveCatalogAttributeRequest): - request = catalog_service.RemoveCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def replace_catalog_attribute(self, - request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Replaces the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ReplaceCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ReplaceCatalogAttributeRequest): - request = catalog_service.ReplaceCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.replace_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py deleted file mode 100644 index f78d4bfa..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog_service - - -class ListCatalogsPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` - 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[..., catalog_service.ListCatalogsResponse], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2alpha.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - for page in self.pages: - yield from page.catalogs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCatalogsAsyncPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` - 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[catalog_service.ListCatalogsResponse]], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2alpha.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - async def async_generator(): - async for page in self.pages: - for response in page.catalogs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py deleted file mode 100644 index 0cffa336..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CatalogServiceTransport -from .grpc import CatalogServiceGrpcTransport -from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] -_transport_registry['grpc'] = CatalogServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport - -__all__ = ( - 'CatalogServiceTransport', - 'CatalogServiceGrpcTransport', - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py deleted file mode 100644 index f64dcf11..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py +++ /dev/null @@ -1,293 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CatalogServiceTransport(abc.ABC): - """Abstract transport class for CatalogService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_catalogs: gapic_v1.method.wrap_method( - self.list_catalogs, - default_timeout=None, - client_info=client_info, - ), - self.update_catalog: gapic_v1.method.wrap_method( - self.update_catalog, - default_timeout=None, - client_info=client_info, - ), - self.set_default_branch: gapic_v1.method.wrap_method( - self.set_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_default_branch: gapic_v1.method.wrap_method( - self.get_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_completion_config: gapic_v1.method.wrap_method( - self.get_completion_config, - default_timeout=None, - client_info=client_info, - ), - self.update_completion_config: gapic_v1.method.wrap_method( - self.update_completion_config, - default_timeout=None, - client_info=client_info, - ), - self.get_attributes_config: gapic_v1.method.wrap_method( - self.get_attributes_config, - default_timeout=None, - client_info=client_info, - ), - self.update_attributes_config: gapic_v1.method.wrap_method( - self.update_attributes_config, - default_timeout=None, - client_info=client_info, - ), - self.add_catalog_attribute: gapic_v1.method.wrap_method( - self.add_catalog_attribute, - default_timeout=None, - client_info=client_info, - ), - self.remove_catalog_attribute: gapic_v1.method.wrap_method( - self.remove_catalog_attribute, - default_timeout=None, - client_info=client_info, - ), - self.replace_catalog_attribute: gapic_v1.method.wrap_method( - self.replace_catalog_attribute, - 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Union[ - catalog_service.ListCatalogsResponse, - Awaitable[catalog_service.ListCatalogsResponse] - ]]: - raise NotImplementedError() - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Union[ - gcr_catalog.Catalog, - Awaitable[gcr_catalog.Catalog] - ]]: - raise NotImplementedError() - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Union[ - catalog_service.GetDefaultBranchResponse, - Awaitable[catalog_service.GetDefaultBranchResponse] - ]]: - raise NotImplementedError() - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - Union[ - catalog.CompletionConfig, - Awaitable[catalog.CompletionConfig] - ]]: - raise NotImplementedError() - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - Union[ - catalog.CompletionConfig, - Awaitable[catalog.CompletionConfig] - ]]: - raise NotImplementedError() - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CatalogServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py deleted file mode 100644 index 29c4a6cd..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py +++ /dev/null @@ -1,598 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO - - -class CatalogServiceGrpcTransport(CatalogServiceTransport): - """gRPC backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - catalog_service.ListCatalogsResponse]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - ~.ListCatalogsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - gcr_catalog.Catalog]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - ~.Catalog]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - empty_pb2.Empty]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - ~.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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - catalog_service.GetDefaultBranchResponse]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - ~.GetDefaultBranchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - catalog.CompletionConfig]: - r"""Return a callable for the get completion config method over gRPC. - - Gets a - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. - - Returns: - Callable[[~.GetCompletionConfigRequest], - ~.CompletionConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetCompletionConfig', - request_serializer=catalog_service.GetCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['get_completion_config'] - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - catalog.CompletionConfig]: - r"""Return a callable for the update completion config method over gRPC. - - Updates the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. - - Returns: - Callable[[~.UpdateCompletionConfigRequest], - ~.CompletionConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateCompletionConfig', - request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['update_completion_config'] - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - catalog.AttributesConfig]: - r"""Return a callable for the get attributes config method over gRPC. - - Gets an - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - Returns: - Callable[[~.GetAttributesConfigRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetAttributesConfig', - request_serializer=catalog_service.GetAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['get_attributes_config'] - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - catalog.AttributesConfig]: - r"""Return a callable for the update attributes config method over gRPC. - - Updates the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - Returns: - Callable[[~.UpdateAttributesConfigRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateAttributesConfig', - request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['update_attributes_config'] - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the add catalog attribute method over gRPC. - - Adds the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.AddCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_catalog_attribute' not in self._stubs: - self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/AddCatalogAttribute', - request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['add_catalog_attribute'] - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the remove catalog attribute method over gRPC. - - Removes the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.RemoveCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_catalog_attribute' not in self._stubs: - self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/RemoveCatalogAttribute', - request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['remove_catalog_attribute'] - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the replace catalog attribute method over gRPC. - - Replaces the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.ReplaceCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_catalog_attribute' not in self._stubs: - self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/ReplaceCatalogAttribute', - request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['replace_catalog_attribute'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CatalogServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py deleted file mode 100644 index 980169e6..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,597 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CatalogServiceGrpcTransport - - -class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): - """gRPC AsyncIO backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Awaitable[catalog_service.ListCatalogsResponse]]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - Awaitable[~.ListCatalogsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Awaitable[gcr_catalog.Catalog]]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - Awaitable[~.Catalog]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - 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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Awaitable[catalog_service.GetDefaultBranchResponse]]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - Awaitable[~.GetDefaultBranchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - Awaitable[catalog.CompletionConfig]]: - r"""Return a callable for the get completion config method over gRPC. - - Gets a - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. - - Returns: - Callable[[~.GetCompletionConfigRequest], - Awaitable[~.CompletionConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetCompletionConfig', - request_serializer=catalog_service.GetCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['get_completion_config'] - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - Awaitable[catalog.CompletionConfig]]: - r"""Return a callable for the update completion config method over gRPC. - - Updates the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. - - Returns: - Callable[[~.UpdateCompletionConfigRequest], - Awaitable[~.CompletionConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateCompletionConfig', - request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['update_completion_config'] - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the get attributes config method over gRPC. - - Gets an - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - Returns: - Callable[[~.GetAttributesConfigRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetAttributesConfig', - request_serializer=catalog_service.GetAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['get_attributes_config'] - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the update attributes config method over gRPC. - - Updates the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - Returns: - Callable[[~.UpdateAttributesConfigRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateAttributesConfig', - request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['update_attributes_config'] - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the add catalog attribute method over gRPC. - - Adds the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.AddCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_catalog_attribute' not in self._stubs: - self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/AddCatalogAttribute', - request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['add_catalog_attribute'] - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the remove catalog attribute method over gRPC. - - Removes the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.RemoveCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_catalog_attribute' not in self._stubs: - self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/RemoveCatalogAttribute', - request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['remove_catalog_attribute'] - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the replace catalog attribute method over gRPC. - - Replaces the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.ReplaceCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_catalog_attribute' not in self._stubs: - self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/ReplaceCatalogAttribute', - request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['replace_catalog_attribute'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py deleted file mode 100644 index b8af95bd..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CompletionServiceClient -from .async_client import CompletionServiceAsyncClient - -__all__ = ( - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py deleted file mode 100644 index 74888568..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py +++ /dev/null @@ -1,391 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .client import CompletionServiceClient - - -class CompletionServiceAsyncClient: - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: CompletionServiceClient - - DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(CompletionServiceClient.catalog_path) - parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) - common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CompletionServiceClient.common_project_path) - parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) - common_location_path = staticmethod(CompletionServiceClient.common_location_path) - parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CompletionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_complete_query(): - # Create a client - client = retail_v2alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.complete_query, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_import_completion_data(): - # Create a client - client = retail_v2alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2alpha.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. - 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. - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_completion_data, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py deleted file mode 100644 index e6906cf6..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py +++ /dev/null @@ -1,592 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CompletionServiceGrpcTransport -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -class CompletionServiceClientMeta(type): - """Metaclass for the CompletionService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] - _transport_registry["grpc"] = CompletionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CompletionServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class CompletionServiceClient(metaclass=CompletionServiceClientMeta): - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CompletionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CompletionServiceTransport): - # transport is a CompletionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_complete_query(): - # Create a client - client = retail_v2alpha.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a completion_service.CompleteQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, completion_service.CompleteQueryRequest): - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_import_completion_data(): - # Create a client - client = retail_v2alpha.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2alpha.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. - 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. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportCompletionDataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportCompletionDataRequest): - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_completion_data] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py deleted file mode 100644 index a0c9542f..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CompletionServiceTransport -from .grpc import CompletionServiceGrpcTransport -from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] -_transport_registry['grpc'] = CompletionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport - -__all__ = ( - 'CompletionServiceTransport', - 'CompletionServiceGrpcTransport', - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py deleted file mode 100644 index e7d6bf06..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py +++ /dev/null @@ -1,172 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CompletionServiceTransport(abc.ABC): - """Abstract transport class for CompletionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.complete_query: gapic_v1.method.wrap_method( - self.complete_query, - default_timeout=None, - client_info=client_info, - ), - self.import_completion_data: gapic_v1.method.wrap_method( - self.import_completion_data, - 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Union[ - completion_service.CompleteQueryResponse, - Awaitable[completion_service.CompleteQueryResponse] - ]]: - raise NotImplementedError() - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CompletionServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py deleted file mode 100644 index 6cab5b09..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py +++ /dev/null @@ -1,323 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO - - -class CompletionServiceGrpcTransport(CompletionServiceTransport): - """gRPC backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - ~.CompleteQueryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - operations_pb2.Operation]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CompletionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py deleted file mode 100644 index 62e55fcb..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,322 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CompletionServiceGrpcTransport - - -class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): - """gRPC AsyncIO backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Awaitable[completion_service.CompleteQueryResponse]]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - Awaitable[~.CompleteQueryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - 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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py deleted file mode 100644 index e9a7be2f..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ControlServiceClient -from .async_client import ControlServiceAsyncClient - -__all__ = ( - 'ControlServiceClient', - 'ControlServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py deleted file mode 100644 index e32d838b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py +++ /dev/null @@ -1,744 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.control_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.cloud.retail_v2alpha.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport -from .client import ControlServiceClient - - -class ControlServiceAsyncClient: - """Service for modifying Control.""" - - _client: ControlServiceClient - - DEFAULT_ENDPOINT = ControlServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ControlServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(ControlServiceClient.catalog_path) - parse_catalog_path = staticmethod(ControlServiceClient.parse_catalog_path) - control_path = staticmethod(ControlServiceClient.control_path) - parse_control_path = staticmethod(ControlServiceClient.parse_control_path) - common_billing_account_path = staticmethod(ControlServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ControlServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ControlServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ControlServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ControlServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ControlServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ControlServiceClient.common_project_path) - parse_common_project_path = staticmethod(ControlServiceClient.parse_common_project_path) - common_location_path = staticmethod(ControlServiceClient.common_location_path) - parse_common_location_path = staticmethod(ControlServiceClient.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: - ControlServiceAsyncClient: The constructed client. - """ - return ControlServiceClient.from_service_account_info.__func__(ControlServiceAsyncClient, 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: - ControlServiceAsyncClient: The constructed client. - """ - return ControlServiceClient.from_service_account_file.__func__(ControlServiceAsyncClient, 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 variabel 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 ControlServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ControlServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ControlServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ControlServiceClient).get_transport_class, type(ControlServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ControlServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the control service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ControlServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ControlServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_control(self, - request: Union[control_service.CreateControlRequest, dict] = None, - *, - parent: str = None, - control: gcr_control.Control = None, - control_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Creates a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_create_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = await client.create_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateControlRequest, dict]): - The request object. Request for CreateControl method. - parent (:class:`str`): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control (:class:`google.cloud.retail_v2alpha.types.Control`): - Required. The Control to create. - This corresponds to the ``control`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control_id (:class:`str`): - Required. The ID to use for the Control, which will - become the final component of the Control's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``control_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.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, control, control_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.CreateControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if control is not None: - request.control = control - if control_id is not None: - request.control_id = control_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_control(self, - request: Union[control_service.DeleteControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_delete_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteControlRequest( - name="name_value", - ) - - # Make the request - await client.delete_control(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteControlRequest, dict]): - The request object. Request for DeleteControl method. - name (:class:`str`): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.DeleteControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_control(self, - request: Union[control_service.UpdateControlRequest, dict] = None, - *, - control: gcr_control.Control = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Updates a Control. - - [Control][google.cloud.retail.v2alpha.Control] cannot be set to - a different oneof field, if so an INVALID_ARGUMENT is returned. - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.UpdateControlRequest( - control=control, - ) - - # Make the request - response = await client.update_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateControlRequest, dict]): - The request object. Request for UpdateControl method. - control (:class:`google.cloud.retail_v2alpha.types.Control`): - Required. The Control to update. - This corresponds to the ``control`` 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 - [Control][google.cloud.retail.v2alpha.Control] to - update. The following are NOT supported: - - - [Control.name][google.cloud.retail.v2alpha.Control.name] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([control, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.UpdateControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if control is not None: - request.control = control - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("control.name", request.control.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_control(self, - request: Union[control_service.GetControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> control.Control: - r"""Gets a Control. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetControlRequest( - name="name_value", - ) - - # Make the request - response = await client.get_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetControlRequest, dict]): - The request object. Request for GetControl method. - name (:class:`str`): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.GetControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_controls(self, - request: Union[control_service.ListControlsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListControlsAsyncPager: - r"""Lists all Controls linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_list_controls(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListControlsRequest, dict]): - The request object. Request for ListControls method. - parent (:class:`str`): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.control_service.pagers.ListControlsAsyncPager: - Response for ListControls method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.ListControlsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_controls, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListControlsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ControlServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py deleted file mode 100644 index 8b58ebd1..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py +++ /dev/null @@ -1,952 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.control_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.cloud.retail_v2alpha.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ControlServiceGrpcTransport -from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport - - -class ControlServiceClientMeta(type): - """Metaclass for the ControlService 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[ControlServiceTransport]] - _transport_registry["grpc"] = ControlServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ControlServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ControlServiceTransport]: - """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 ControlServiceClient(metaclass=ControlServiceClientMeta): - """Service for modifying Control.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ControlServiceClient: 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: - ControlServiceClient: 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) -> ControlServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ControlServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def control_path(project: str,location: str,catalog: str,control: str,) -> str: - """Returns a fully-qualified control string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) - - @staticmethod - def parse_control_path(path: str) -> Dict[str,str]: - """Parses a control path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/controls/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ControlServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the control service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ControlServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ControlServiceTransport): - # transport is a ControlServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_control(self, - request: Union[control_service.CreateControlRequest, dict] = None, - *, - parent: str = None, - control: gcr_control.Control = None, - control_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Creates a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_create_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = client.create_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateControlRequest, dict]): - The request object. Request for CreateControl method. - parent (str): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control (google.cloud.retail_v2alpha.types.Control): - Required. The Control to create. - This corresponds to the ``control`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control_id (str): - Required. The ID to use for the Control, which will - become the final component of the Control's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``control_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.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, control, control_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.CreateControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.CreateControlRequest): - request = control_service.CreateControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if control is not None: - request.control = control - if control_id is not None: - request.control_id = control_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_control(self, - request: Union[control_service.DeleteControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_delete_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteControlRequest( - name="name_value", - ) - - # Make the request - client.delete_control(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteControlRequest, dict]): - The request object. Request for DeleteControl method. - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.DeleteControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.DeleteControlRequest): - request = control_service.DeleteControlRequest(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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_control(self, - request: Union[control_service.UpdateControlRequest, dict] = None, - *, - control: gcr_control.Control = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Updates a Control. - - [Control][google.cloud.retail.v2alpha.Control] cannot be set to - a different oneof field, if so an INVALID_ARGUMENT is returned. - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.UpdateControlRequest( - control=control, - ) - - # Make the request - response = client.update_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateControlRequest, dict]): - The request object. Request for UpdateControl method. - control (google.cloud.retail_v2alpha.types.Control): - Required. The Control to update. - This corresponds to the ``control`` 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 - [Control][google.cloud.retail.v2alpha.Control] to - update. The following are NOT supported: - - - [Control.name][google.cloud.retail.v2alpha.Control.name] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([control, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.UpdateControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.UpdateControlRequest): - request = control_service.UpdateControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if control is not None: - request.control = control - 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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("control.name", request.control.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_control(self, - request: Union[control_service.GetControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> control.Control: - r"""Gets a Control. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetControlRequest( - name="name_value", - ) - - # Make the request - response = client.get_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetControlRequest, dict]): - The request object. Request for GetControl method. - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.GetControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.GetControlRequest): - request = control_service.GetControlRequest(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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_controls(self, - request: Union[control_service.ListControlsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListControlsPager: - r"""Lists all Controls linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_list_controls(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListControlsRequest, dict]): - The request object. Request for ListControls method. - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.control_service.pagers.ListControlsPager: - Response for ListControls method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.ListControlsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.ListControlsRequest): - request = control_service.ListControlsRequest(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_controls] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListControlsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ControlServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py deleted file mode 100644 index d1c28748..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control_service - - -class ListControlsPager: - """A pager for iterating through ``list_controls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``controls`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListControls`` requests and continue to iterate - through the ``controls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` - 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[..., control_service.ListControlsResponse], - request: control_service.ListControlsRequest, - response: control_service.ListControlsResponse, - *, - 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.retail_v2alpha.types.ListControlsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListControlsResponse): - 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 = control_service.ListControlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[control_service.ListControlsResponse]: - 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[control.Control]: - for page in self.pages: - yield from page.controls - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListControlsAsyncPager: - """A pager for iterating through ``list_controls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``controls`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListControls`` requests and continue to iterate - through the ``controls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` - 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[control_service.ListControlsResponse]], - request: control_service.ListControlsRequest, - response: control_service.ListControlsResponse, - *, - 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.retail_v2alpha.types.ListControlsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListControlsResponse): - 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 = control_service.ListControlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[control_service.ListControlsResponse]: - 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[control.Control]: - async def async_generator(): - async for page in self.pages: - for response in page.controls: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py deleted file mode 100644 index 3622876b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ControlServiceTransport -from .grpc import ControlServiceGrpcTransport -from .grpc_asyncio import ControlServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ControlServiceTransport]] -_transport_registry['grpc'] = ControlServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ControlServiceGrpcAsyncIOTransport - -__all__ = ( - 'ControlServiceTransport', - 'ControlServiceGrpcTransport', - 'ControlServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py deleted file mode 100644 index e6390673..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py +++ /dev/null @@ -1,209 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ControlServiceTransport(abc.ABC): - """Abstract transport class for ControlService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_control: gapic_v1.method.wrap_method( - self.create_control, - default_timeout=None, - client_info=client_info, - ), - self.delete_control: gapic_v1.method.wrap_method( - self.delete_control, - default_timeout=None, - client_info=client_info, - ), - self.update_control: gapic_v1.method.wrap_method( - self.update_control, - default_timeout=None, - client_info=client_info, - ), - self.get_control: gapic_v1.method.wrap_method( - self.get_control, - default_timeout=None, - client_info=client_info, - ), - self.list_controls: gapic_v1.method.wrap_method( - self.list_controls, - 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 create_control(self) -> Callable[ - [control_service.CreateControlRequest], - Union[ - gcr_control.Control, - Awaitable[gcr_control.Control] - ]]: - raise NotImplementedError() - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - Union[ - gcr_control.Control, - Awaitable[gcr_control.Control] - ]]: - raise NotImplementedError() - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - Union[ - control.Control, - Awaitable[control.Control] - ]]: - raise NotImplementedError() - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - Union[ - control_service.ListControlsResponse, - Awaitable[control_service.ListControlsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ControlServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py deleted file mode 100644 index e2e2a244..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py +++ /dev/null @@ -1,380 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO - - -class ControlServiceGrpcTransport(ControlServiceTransport): - """gRPC backend transport for ControlService. - - Service for modifying Control. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_control(self) -> Callable[ - [control_service.CreateControlRequest], - gcr_control.Control]: - r"""Return a callable for the create control method over gRPC. - - Creates a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['create_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/CreateControl', - request_serializer=control_service.CreateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['create_control'] - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete control method over gRPC. - - Deletes a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteControlRequest], - ~.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_control' not in self._stubs: - self._stubs['delete_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/DeleteControl', - request_serializer=control_service.DeleteControlRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_control'] - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - gcr_control.Control]: - r"""Return a callable for the update control method over gRPC. - - Updates a Control. - - [Control][google.cloud.retail.v2alpha.Control] cannot be set to - a different oneof field, if so an INVALID_ARGUMENT is returned. - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.UpdateControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['update_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/UpdateControl', - request_serializer=control_service.UpdateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['update_control'] - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - control.Control]: - r"""Return a callable for the get control method over gRPC. - - Gets a Control. - - Returns: - Callable[[~.GetControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['get_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/GetControl', - request_serializer=control_service.GetControlRequest.serialize, - response_deserializer=control.Control.deserialize, - ) - return self._stubs['get_control'] - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - control_service.ListControlsResponse]: - r"""Return a callable for the list controls method over gRPC. - - Lists all Controls linked to this catalog. - - Returns: - Callable[[~.ListControlsRequest], - ~.ListControlsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_controls' not in self._stubs: - self._stubs['list_controls'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/ListControls', - request_serializer=control_service.ListControlsRequest.serialize, - response_deserializer=control_service.ListControlsResponse.deserialize, - ) - return self._stubs['list_controls'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ControlServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py deleted file mode 100644 index c4edc3e1..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,379 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ControlServiceGrpcTransport - - -class ControlServiceGrpcAsyncIOTransport(ControlServiceTransport): - """gRPC AsyncIO backend transport for ControlService. - - Service for modifying Control. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_control(self) -> Callable[ - [control_service.CreateControlRequest], - Awaitable[gcr_control.Control]]: - r"""Return a callable for the create control method over gRPC. - - Creates a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['create_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/CreateControl', - request_serializer=control_service.CreateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['create_control'] - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete control method over gRPC. - - Deletes a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteControlRequest], - 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_control' not in self._stubs: - self._stubs['delete_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/DeleteControl', - request_serializer=control_service.DeleteControlRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_control'] - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - Awaitable[gcr_control.Control]]: - r"""Return a callable for the update control method over gRPC. - - Updates a Control. - - [Control][google.cloud.retail.v2alpha.Control] cannot be set to - a different oneof field, if so an INVALID_ARGUMENT is returned. - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.UpdateControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['update_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/UpdateControl', - request_serializer=control_service.UpdateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['update_control'] - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - Awaitable[control.Control]]: - r"""Return a callable for the get control method over gRPC. - - Gets a Control. - - Returns: - Callable[[~.GetControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['get_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/GetControl', - request_serializer=control_service.GetControlRequest.serialize, - response_deserializer=control.Control.deserialize, - ) - return self._stubs['get_control'] - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - Awaitable[control_service.ListControlsResponse]]: - r"""Return a callable for the list controls method over gRPC. - - Lists all Controls linked to this catalog. - - Returns: - Callable[[~.ListControlsRequest], - Awaitable[~.ListControlsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_controls' not in self._stubs: - self._stubs['list_controls'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/ListControls', - request_serializer=control_service.ListControlsRequest.serialize, - response_deserializer=control_service.ListControlsResponse.deserialize, - ) - return self._stubs['list_controls'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ControlServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py deleted file mode 100644 index 7c079c80..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import PredictionServiceClient -from .async_client import PredictionServiceAsyncClient - -__all__ = ( - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py deleted file mode 100644 index b9255f77..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py +++ /dev/null @@ -1,279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport -from .client import PredictionServiceClient - - -class PredictionServiceAsyncClient: - """Service for making recommendation prediction.""" - - _client: PredictionServiceClient - - DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT - - product_path = staticmethod(PredictionServiceClient.product_path) - parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) - common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(PredictionServiceClient.common_project_path) - parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) - common_location_path = staticmethod(PredictionServiceClient.common_location_path) - parse_common_location_path = staticmethod(PredictionServiceClient.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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PredictionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_predict(): - # Create a client - client = retail_v2alpha.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - request = prediction_service.PredictRequest(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.predict, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py deleted file mode 100644 index 331c14ce..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py +++ /dev/null @@ -1,479 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PredictionServiceGrpcTransport -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -class PredictionServiceClientMeta(type): - """Metaclass for the PredictionService 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[PredictionServiceTransport]] - _transport_registry["grpc"] = PredictionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PredictionServiceTransport]: - """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): - """Service for making recommendation prediction.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PredictionServiceClient: 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: - PredictionServiceClient: 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) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, PredictionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, PredictionServiceTransport): - # transport is a PredictionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_predict(): - # Create a client - client = retail_v2alpha.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a prediction_service.PredictRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_service.PredictRequest): - request = prediction_service.PredictRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.predict] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py deleted file mode 100644 index bb65c664..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PredictionServiceTransport -from .grpc import PredictionServiceGrpcTransport -from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] -_transport_registry['grpc'] = PredictionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport - -__all__ = ( - 'PredictionServiceTransport', - 'PredictionServiceGrpcTransport', - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py deleted file mode 100644 index d46ddac0..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PredictionServiceTransport(abc.ABC): - """Abstract transport class for PredictionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.predict: gapic_v1.method.wrap_method( - self.predict, - 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - Union[ - prediction_service.PredictResponse, - Awaitable[prediction_service.PredictResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PredictionServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py deleted file mode 100644 index a527b5d9..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py +++ /dev/null @@ -1,262 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO - - -class PredictionServiceGrpcTransport(PredictionServiceTransport): - """gRPC backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - prediction_service.PredictResponse]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - ~.PredictResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PredictionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py deleted file mode 100644 index 34b77b90..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,261 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import PredictionServiceGrpcTransport - - -class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): - """gRPC AsyncIO backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def predict(self) -> Callable[ - [prediction_service.PredictRequest], - Awaitable[prediction_service.PredictResponse]]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - Awaitable[~.PredictResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py deleted file mode 100644 index 0fa6330a..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ProductServiceClient -from .async_client import ProductServiceAsyncClient - -__all__ = ( - 'ProductServiceClient', - 'ProductServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py deleted file mode 100644 index 2933dcb8..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py +++ /dev/null @@ -1,1804 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.services.product_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import purge_config -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport -from .client import ProductServiceClient - - -class ProductServiceAsyncClient: - """Service for ingesting [Product][google.cloud.retail.v2alpha.Product] - information of the customer's website. - """ - - _client: ProductServiceClient - - DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(ProductServiceClient.branch_path) - parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) - product_path = staticmethod(ProductServiceClient.product_path) - parse_product_path = staticmethod(ProductServiceClient.parse_product_path) - common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProductServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProductServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ProductServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) - common_location_path = staticmethod(ProductServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProductServiceClient.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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ProductServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ProductServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_create_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (:class:`str`): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (:class:`google.cloud.retail_v2alpha.types.Product`): - Required. The - [Product][google.cloud.retail.v2alpha.Product] to - create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (:class:`str`): - Required. The ID to use for the - [Product][google.cloud.retail.v2alpha.Product], which - will become the final component of the - [Product.name][google.cloud.retail.v2alpha.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This field must be unique among all - [Product][google.cloud.retail.v2alpha.Product]s with the - same - [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.CreateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the requested - [Product][google.cloud.retail.v2alpha.Product] 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.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.GetProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsAsyncPager: - r"""Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_list_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - parent (:class:`str`): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2alpha.Product]s under - this branch, regardless of whether or not this branch - exists, a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.product_service.pagers.ListProductsAsyncPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.ListProductsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_products, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProductsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (:class:`google.cloud.retail_v2alpha.types.Product`): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2alpha.Product] to - update. The immutable and output only fields are NOT - supported. If not set, all supported fields (the fields - that are neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.UpdateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_delete_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2alpha.Product] to - delete can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product] member - nor a - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] with more - than one - [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2alpha.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.DeleteProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def purge_products(self, - request: Union[purge_config.PurgeProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Permanently deletes all selected - [Product][google.cloud.retail.v2alpha.Product]s under a branch. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed offline. Depending on the - number of [Product][google.cloud.retail.v2alpha.Product]s, this - operation could take hours to complete. Before the operation - completes, some [Product][google.cloud.retail.v2alpha.Product]s - may still be returned by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Depending on the number of - [Product][google.cloud.retail.v2alpha.Product]s, this operation - could take hours to complete. To get a sample of - [Product][google.cloud.retail.v2alpha.Product]s that would be - deleted, set - [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] - to false. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_purge_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeProductsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PurgeProductsRequest, dict]): - The request object. Request message for PurgeProducts - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.PurgeProductsResponse` Response of the PurgeProductsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_products, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeProductsResponse, - metadata_type=purge_config.PurgeProductsMetadata, - ) - - # Done; return the response. - return response - - async def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2alpha.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2alpha.Product]s to be - successfully updated. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_import_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2alpha.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2alpha.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_set_inventory(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2alpha.Product() - inventory.title = "title_value" - - request = retail_v2alpha.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (:class:`google.cloud.retail_v2alpha.types.Product`): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product] named in - [Product.name][google.cloud.retail.v2alpha.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2alpha.Product] to - update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.SetInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_inventory, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - async def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [AddFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_add_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [AddLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_remove_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py deleted file mode 100644 index fa5e5d85..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py +++ /dev/null @@ -1,2007 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.services.product_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import purge_config -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProductServiceGrpcTransport -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -class ProductServiceClientMeta(type): - """Metaclass for the ProductService 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[ProductServiceTransport]] - _transport_registry["grpc"] = ProductServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ProductServiceTransport]: - """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 ProductServiceClient(metaclass=ProductServiceClientMeta): - """Service for ingesting [Product][google.cloud.retail.v2alpha.Product] - information of the customer's website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProductServiceClient: 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: - ProductServiceClient: 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) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProductServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ProductServiceTransport): - # transport is a ProductServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_create_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (google.cloud.retail_v2alpha.types.Product): - Required. The - [Product][google.cloud.retail.v2alpha.Product] to - create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2alpha.Product], which - will become the final component of the - [Product.name][google.cloud.retail.v2alpha.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This field must be unique among all - [Product][google.cloud.retail.v2alpha.Product]s with the - same - [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.CreateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.CreateProductRequest): - request = product_service.CreateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the requested - [Product][google.cloud.retail.v2alpha.Product] 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.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.GetProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.GetProductRequest): - request = product_service.GetProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsPager: - r"""Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_list_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2alpha.Product]s under - this branch, regardless of whether or not this branch - exists, a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.product_service.pagers.ListProductsPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.ListProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.ListProductsRequest): - request = product_service.ListProductsRequest(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_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProductsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (google.cloud.retail_v2alpha.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2alpha.Product] to - update. The immutable and output only fields are NOT - supported. If not set, all supported fields (the fields - that are neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.UpdateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.UpdateProductRequest): - request = product_service.UpdateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - 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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_delete_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2alpha.Product] to - delete can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product] member - nor a - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] with more - than one - [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2alpha.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.DeleteProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.DeleteProductRequest): - request = product_service.DeleteProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def purge_products(self, - request: Union[purge_config.PurgeProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Permanently deletes all selected - [Product][google.cloud.retail.v2alpha.Product]s under a branch. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed offline. Depending on the - number of [Product][google.cloud.retail.v2alpha.Product]s, this - operation could take hours to complete. Before the operation - completes, some [Product][google.cloud.retail.v2alpha.Product]s - may still be returned by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Depending on the number of - [Product][google.cloud.retail.v2alpha.Product]s, this operation - could take hours to complete. To get a sample of - [Product][google.cloud.retail.v2alpha.Product]s that would be - deleted, set - [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] - to false. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_purge_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeProductsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PurgeProductsRequest, dict]): - The request object. Request message for PurgeProducts - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.PurgeProductsResponse` Response of the PurgeProductsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeProductsRequest): - request = purge_config.PurgeProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeProductsResponse, - metadata_type=purge_config.PurgeProductsMetadata, - ) - - # Done; return the response. - return response - - def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2alpha.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2alpha.Product]s to be - successfully updated. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_import_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2alpha.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportProductsRequest): - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2alpha.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_set_inventory(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2alpha.Product() - inventory.title = "title_value" - - request = retail_v2alpha.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (google.cloud.retail_v2alpha.types.Product): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product] named in - [Product.name][google.cloud.retail.v2alpha.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2alpha.Product] to - update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.SetInventoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.SetInventoryRequest): - request = product_service.SetInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_add_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [AddFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddFulfillmentPlacesRequest): - request = product_service.AddFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): - request = product_service.RemoveFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_add_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [AddLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddLocalInventoriesRequest): - request = product_service.AddLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_remove_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveLocalInventoriesRequest): - request = product_service.RemoveLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py deleted file mode 100644 index 5e235009..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product_service - - -class ListProductsPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` - 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[..., product_service.ListProductsResponse], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2alpha.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[product_service.ListProductsResponse]: - 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[product.Product]: - for page in self.pages: - yield from page.products - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProductsAsyncPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` - 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[product_service.ListProductsResponse]], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2alpha.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: - 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[product.Product]: - async def async_generator(): - async for page in self.pages: - for response in page.products: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py deleted file mode 100644 index db824dec..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ProductServiceTransport -from .grpc import ProductServiceGrpcTransport -from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] -_transport_registry['grpc'] = ProductServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport - -__all__ = ( - 'ProductServiceTransport', - 'ProductServiceGrpcTransport', - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py deleted file mode 100644 index 25f3f28f..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py +++ /dev/null @@ -1,323 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import purge_config -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ProductServiceTransport(abc.ABC): - """Abstract transport class for ProductService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_product: gapic_v1.method.wrap_method( - self.create_product, - default_timeout=None, - client_info=client_info, - ), - self.get_product: gapic_v1.method.wrap_method( - self.get_product, - default_timeout=None, - client_info=client_info, - ), - self.list_products: gapic_v1.method.wrap_method( - self.list_products, - default_timeout=None, - client_info=client_info, - ), - self.update_product: gapic_v1.method.wrap_method( - self.update_product, - default_timeout=None, - client_info=client_info, - ), - self.delete_product: gapic_v1.method.wrap_method( - self.delete_product, - default_timeout=None, - client_info=client_info, - ), - self.purge_products: gapic_v1.method.wrap_method( - self.purge_products, - default_timeout=None, - client_info=client_info, - ), - self.import_products: gapic_v1.method.wrap_method( - self.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.set_inventory: gapic_v1.method.wrap_method( - self.set_inventory, - default_timeout=None, - client_info=client_info, - ), - self.add_fulfillment_places: gapic_v1.method.wrap_method( - self.add_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.remove_fulfillment_places: gapic_v1.method.wrap_method( - self.remove_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.add_local_inventories: gapic_v1.method.wrap_method( - self.add_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.remove_local_inventories: gapic_v1.method.wrap_method( - self.remove_local_inventories, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Union[ - product.Product, - Awaitable[product.Product] - ]]: - raise NotImplementedError() - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Union[ - product_service.ListProductsResponse, - Awaitable[product_service.ListProductsResponse] - ]]: - raise NotImplementedError() - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def purge_products(self) -> Callable[ - [purge_config.PurgeProductsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ProductServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py deleted file mode 100644 index 2457b578..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py +++ /dev/null @@ -1,724 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import purge_config -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO - - -class ProductServiceGrpcTransport(ProductServiceTransport): - """gRPC backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2alpha.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - gcr_product.Product]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.CreateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - product.Product]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.GetProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - product_service.ListProductsResponse]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - ~.ListProductsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - gcr_product.Product]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - ~.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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def purge_products(self) -> Callable[ - [purge_config.PurgeProductsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge products method over gRPC. - - Permanently deletes all selected - [Product][google.cloud.retail.v2alpha.Product]s under a branch. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed offline. Depending on the - number of [Product][google.cloud.retail.v2alpha.Product]s, this - operation could take hours to complete. Before the operation - completes, some [Product][google.cloud.retail.v2alpha.Product]s - may still be returned by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Depending on the number of - [Product][google.cloud.retail.v2alpha.Product]s, this operation - could take hours to complete. To get a sample of - [Product][google.cloud.retail.v2alpha.Product]s that would be - deleted, set - [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] - to false. - - Returns: - Callable[[~.PurgeProductsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_products' not in self._stubs: - self._stubs['purge_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/PurgeProducts', - request_serializer=purge_config.PurgeProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_products'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2alpha.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2alpha.Product]s to be - successfully updated. - - Returns: - Callable[[~.ImportProductsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - operations_pb2.Operation]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2alpha.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProductServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py deleted file mode 100644 index 4b04ce78..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,723 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import purge_config -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ProductServiceGrpcTransport - - -class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): - """gRPC AsyncIO backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2alpha.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.CreateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Awaitable[product.Product]]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.GetProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Awaitable[product_service.ListProductsResponse]]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - Awaitable[~.ListProductsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - 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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def purge_products(self) -> Callable[ - [purge_config.PurgeProductsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge products method over gRPC. - - Permanently deletes all selected - [Product][google.cloud.retail.v2alpha.Product]s under a branch. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed offline. Depending on the - number of [Product][google.cloud.retail.v2alpha.Product]s, this - operation could take hours to complete. Before the operation - completes, some [Product][google.cloud.retail.v2alpha.Product]s - may still be returned by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Depending on the number of - [Product][google.cloud.retail.v2alpha.Product]s, this operation - could take hours to complete. To get a sample of - [Product][google.cloud.retail.v2alpha.Product]s that would be - deleted, set - [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] - to false. - - Returns: - Callable[[~.PurgeProductsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_products' not in self._stubs: - self._stubs['purge_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/PurgeProducts', - request_serializer=purge_config.PurgeProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_products'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2alpha.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2alpha.Product]s to be - successfully updated. - - Returns: - Callable[[~.ImportProductsRequest], - 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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2alpha.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - 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 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - 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 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - 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 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - 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 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py deleted file mode 100644 index 2f63fc22..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SearchServiceClient -from .async_client import SearchServiceAsyncClient - -__all__ = ( - 'SearchServiceClient', - 'SearchServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py deleted file mode 100644 index d39b3203..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.search_service import pagers -from google.cloud.retail_v2alpha.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .client import SearchServiceClient - - -class SearchServiceAsyncClient: - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: SearchServiceClient - - DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(SearchServiceClient.branch_path) - parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) - product_path = staticmethod(SearchServiceClient.product_path) - parse_product_path = staticmethod(SearchServiceClient.parse_product_path) - common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(SearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SearchServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAsyncPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_search(): - # Create a client - client = retail_v2alpha.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.search_service.pagers.SearchAsyncPager: - Response message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py deleted file mode 100644 index c732b39b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py +++ /dev/null @@ -1,512 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.search_service import pagers -from google.cloud.retail_v2alpha.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SearchServiceGrpcTransport -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -class SearchServiceClientMeta(type): - """Metaclass for the SearchService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] - _transport_registry["grpc"] = SearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SearchServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SearchServiceClient(metaclass=SearchServiceClientMeta): - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SearchServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SearchServiceTransport): - # transport is a SearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_search(): - # Create a client - client = retail_v2alpha.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.search_service.pagers.SearchPager: - Response message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a search_service.SearchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, search_service.SearchRequest): - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py deleted file mode 100644 index 7487beee..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import search_service - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., search_service.SearchResponse], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2alpha.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[search_service.SearchResponse]], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2alpha.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py deleted file mode 100644 index 7917cd1d..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SearchServiceTransport -from .grpc import SearchServiceGrpcTransport -from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] -_transport_registry['grpc'] = SearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport - -__all__ = ( - 'SearchServiceTransport', - 'SearchServiceGrpcTransport', - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py deleted file mode 100644 index 8713b735..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import search_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class SearchServiceTransport(abc.ABC): - """Abstract transport class for SearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search: gapic_v1.method.wrap_method( - self.search, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Union[ - search_service.SearchResponse, - Awaitable[search_service.SearchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SearchServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py deleted file mode 100644 index 1bdd51d4..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py +++ /dev/null @@ -1,268 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO - - -class SearchServiceGrpcTransport(SearchServiceTransport): - """gRPC backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py deleted file mode 100644 index 12a83cc7..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,267 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SearchServiceGrpcTransport - - -class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): - """gRPC AsyncIO backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Awaitable[search_service.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py deleted file mode 100644 index d1a0a023..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ServingConfigServiceClient -from .async_client import ServingConfigServiceAsyncClient - -__all__ = ( - 'ServingConfigServiceClient', - 'ServingConfigServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py deleted file mode 100644 index 4f047853..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py +++ /dev/null @@ -1,954 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.serving_config_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport -from .client import ServingConfigServiceClient - - -class ServingConfigServiceAsyncClient: - """Service for modifying ServingConfig.""" - - _client: ServingConfigServiceClient - - DEFAULT_ENDPOINT = ServingConfigServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ServingConfigServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(ServingConfigServiceClient.catalog_path) - parse_catalog_path = staticmethod(ServingConfigServiceClient.parse_catalog_path) - serving_config_path = staticmethod(ServingConfigServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(ServingConfigServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(ServingConfigServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ServingConfigServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ServingConfigServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ServingConfigServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ServingConfigServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ServingConfigServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ServingConfigServiceClient.common_project_path) - parse_common_project_path = staticmethod(ServingConfigServiceClient.parse_common_project_path) - common_location_path = staticmethod(ServingConfigServiceClient.common_location_path) - parse_common_location_path = staticmethod(ServingConfigServiceClient.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: - ServingConfigServiceAsyncClient: The constructed client. - """ - return ServingConfigServiceClient.from_service_account_info.__func__(ServingConfigServiceAsyncClient, 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: - ServingConfigServiceAsyncClient: The constructed client. - """ - return ServingConfigServiceClient.from_service_account_file.__func__(ServingConfigServiceAsyncClient, 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 variabel 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 ServingConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ServingConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ServingConfigServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ServingConfigServiceClient).get_transport_class, type(ServingConfigServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ServingConfigServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the serving config service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ServingConfigServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ServingConfigServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_serving_config(self, - request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, - *, - parent: str = None, - serving_config: gcr_serving_config.ServingConfig = None, - serving_config_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_create_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = await client.create_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateServingConfigRequest, dict]): - The request object. Request for CreateServingConfig - method. - parent (:class:`str`): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config (:class:`google.cloud.retail_v2alpha.types.ServingConfig`): - Required. The ServingConfig to - create. - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config_id (:class:`str`): - Required. The ID to use for the ServingConfig, which - will become the final component of the ServingConfig's - resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``serving_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, serving_config, serving_config_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.CreateServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if serving_config is not None: - request.serving_config = serving_config - if serving_config_id is not None: - request.serving_config_id = serving_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_serving_config(self, - request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_delete_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_serving_config(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteServingConfigRequest, dict]): - The request object. Request for DeleteServingConfig - method. - name (:class:`str`): - Required. The resource name of the ServingConfig to - delete. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.DeleteServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_serving_config(self, - request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, - *, - serving_config: gcr_serving_config.ServingConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Updates a ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = await client.update_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateServingConfigRequest, dict]): - The request object. Request for UpdateServingConfig - method. - serving_config (:class:`google.cloud.retail_v2alpha.types.ServingConfig`): - Required. The ServingConfig to - update. - - This corresponds to the ``serving_config`` 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 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.UpdateServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config.name", request.serving_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_serving_config(self, - request: Union[serving_config_service.GetServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> serving_config.ServingConfig: - r"""Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetServingConfigRequest, dict]): - The request object. Request for GetServingConfig method. - name (:class:`str`): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.GetServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_serving_configs(self, - request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServingConfigsAsyncPager: - r"""Lists all ServingConfigs linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_list_serving_configs(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListServingConfigsRequest, dict]): - The request object. Request for ListServingConfigs - method. - parent (:class:`str`): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsAsyncPager: - Response for ListServingConfigs - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.ListServingConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_serving_configs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListServingConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def add_control(self, - request: Union[serving_config_service.AddControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_add_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.add_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddControlRequest, dict]): - The request object. Request for AddControl method. - serving_config (:class:`str`): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.AddControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def remove_control(self, - request: Union[serving_config_service.RemoveControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_remove_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.remove_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveControlRequest, dict]): - The request object. Request for RemoveControl method. - serving_config (:class:`str`): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.RemoveControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServingConfigServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py deleted file mode 100644 index 26637bf0..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py +++ /dev/null @@ -1,1162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.serving_config_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ServingConfigServiceGrpcTransport -from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport - - -class ServingConfigServiceClientMeta(type): - """Metaclass for the ServingConfigService 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[ServingConfigServiceTransport]] - _transport_registry["grpc"] = ServingConfigServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ServingConfigServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ServingConfigServiceTransport]: - """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 ServingConfigServiceClient(metaclass=ServingConfigServiceClientMeta): - """Service for modifying ServingConfig.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServingConfigServiceClient: 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: - ServingConfigServiceClient: 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) -> ServingConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ServingConfigServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,catalog: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ServingConfigServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the serving config service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ServingConfigServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ServingConfigServiceTransport): - # transport is a ServingConfigServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_serving_config(self, - request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, - *, - parent: str = None, - serving_config: gcr_serving_config.ServingConfig = None, - serving_config_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_create_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = client.create_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateServingConfigRequest, dict]): - The request object. Request for CreateServingConfig - method. - parent (str): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config (google.cloud.retail_v2alpha.types.ServingConfig): - Required. The ServingConfig to - create. - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config_id (str): - Required. The ID to use for the ServingConfig, which - will become the final component of the ServingConfig's - resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``serving_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, serving_config, serving_config_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.CreateServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.CreateServingConfigRequest): - request = serving_config_service.CreateServingConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if serving_config is not None: - request.serving_config = serving_config - if serving_config_id is not None: - request.serving_config_id = serving_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_serving_config(self, - request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_delete_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_serving_config(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteServingConfigRequest, dict]): - The request object. Request for DeleteServingConfig - method. - name (str): - Required. The resource name of the ServingConfig to - delete. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.DeleteServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.DeleteServingConfigRequest): - request = serving_config_service.DeleteServingConfigRequest(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_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_serving_config(self, - request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, - *, - serving_config: gcr_serving_config.ServingConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Updates a ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = client.update_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateServingConfigRequest, dict]): - The request object. Request for UpdateServingConfig - method. - serving_config (google.cloud.retail_v2alpha.types.ServingConfig): - Required. The ServingConfig to - update. - - This corresponds to the ``serving_config`` 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 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.UpdateServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.UpdateServingConfigRequest): - request = serving_config_service.UpdateServingConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config.name", request.serving_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_serving_config(self, - request: Union[serving_config_service.GetServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> serving_config.ServingConfig: - r"""Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetServingConfigRequest, dict]): - The request object. Request for GetServingConfig method. - name (str): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.GetServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.GetServingConfigRequest): - request = serving_config_service.GetServingConfigRequest(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_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_serving_configs(self, - request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServingConfigsPager: - r"""Lists all ServingConfigs linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_list_serving_configs(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListServingConfigsRequest, dict]): - The request object. Request for ListServingConfigs - method. - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsPager: - Response for ListServingConfigs - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.ListServingConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.ListServingConfigsRequest): - request = serving_config_service.ListServingConfigsRequest(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_serving_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListServingConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def add_control(self, - request: Union[serving_config_service.AddControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_add_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.add_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddControlRequest, dict]): - The request object. Request for AddControl method. - serving_config (str): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.AddControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.AddControlRequest): - request = serving_config_service.AddControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def remove_control(self, - request: Union[serving_config_service.RemoveControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_remove_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.remove_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveControlRequest, dict]): - The request object. Request for RemoveControl method. - serving_config (str): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.RemoveControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.RemoveControlRequest): - request = serving_config_service.RemoveControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServingConfigServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py deleted file mode 100644 index 8c4975b7..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config_service - - -class ListServingConfigsPager: - """A pager for iterating through ``list_serving_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``serving_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServingConfigs`` requests and continue to iterate - through the ``serving_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` - 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[..., serving_config_service.ListServingConfigsResponse], - request: serving_config_service.ListServingConfigsRequest, - response: serving_config_service.ListServingConfigsResponse, - *, - 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.retail_v2alpha.types.ListServingConfigsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListServingConfigsResponse): - 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 = serving_config_service.ListServingConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[serving_config_service.ListServingConfigsResponse]: - 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[serving_config.ServingConfig]: - for page in self.pages: - yield from page.serving_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServingConfigsAsyncPager: - """A pager for iterating through ``list_serving_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``serving_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServingConfigs`` requests and continue to iterate - through the ``serving_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` - 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[serving_config_service.ListServingConfigsResponse]], - request: serving_config_service.ListServingConfigsRequest, - response: serving_config_service.ListServingConfigsResponse, - *, - 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.retail_v2alpha.types.ListServingConfigsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListServingConfigsResponse): - 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 = serving_config_service.ListServingConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[serving_config_service.ListServingConfigsResponse]: - 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[serving_config.ServingConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.serving_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py deleted file mode 100644 index 3726ac83..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ServingConfigServiceTransport -from .grpc import ServingConfigServiceGrpcTransport -from .grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ServingConfigServiceTransport]] -_transport_registry['grpc'] = ServingConfigServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ServingConfigServiceGrpcAsyncIOTransport - -__all__ = ( - 'ServingConfigServiceTransport', - 'ServingConfigServiceGrpcTransport', - 'ServingConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py deleted file mode 100644 index 23a39b6d..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py +++ /dev/null @@ -1,237 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ServingConfigServiceTransport(abc.ABC): - """Abstract transport class for ServingConfigService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_serving_config: gapic_v1.method.wrap_method( - self.create_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_serving_config: gapic_v1.method.wrap_method( - self.delete_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.update_serving_config: gapic_v1.method.wrap_method( - self.update_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.get_serving_config: gapic_v1.method.wrap_method( - self.get_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.list_serving_configs: gapic_v1.method.wrap_method( - self.list_serving_configs, - default_timeout=None, - client_info=client_info, - ), - self.add_control: gapic_v1.method.wrap_method( - self.add_control, - default_timeout=None, - client_info=client_info, - ), - self.remove_control: gapic_v1.method.wrap_method( - self.remove_control, - 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 create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - Union[ - serving_config.ServingConfig, - Awaitable[serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - Union[ - serving_config_service.ListServingConfigsResponse, - Awaitable[serving_config_service.ListServingConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ServingConfigServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py deleted file mode 100644 index 5ba2c69c..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py +++ /dev/null @@ -1,438 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO - - -class ServingConfigServiceGrpcTransport(ServingConfigServiceTransport): - """gRPC backend transport for ServingConfigService. - - Service for modifying ServingConfig. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the create serving config method over gRPC. - - Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - Returns: - Callable[[~.CreateServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/CreateServingConfig', - request_serializer=serving_config_service.CreateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['create_serving_config'] - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete serving config method over gRPC. - - Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.DeleteServingConfigRequest], - ~.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_serving_config' not in self._stubs: - self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/DeleteServingConfig', - request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_serving_config'] - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the update serving config method over gRPC. - - Updates a ServingConfig. - - Returns: - Callable[[~.UpdateServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/UpdateServingConfig', - request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['update_serving_config'] - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - serving_config.ServingConfig]: - r"""Return a callable for the get serving config method over gRPC. - - Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.GetServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/GetServingConfig', - request_serializer=serving_config_service.GetServingConfigRequest.serialize, - response_deserializer=serving_config.ServingConfig.deserialize, - ) - return self._stubs['get_serving_config'] - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - serving_config_service.ListServingConfigsResponse]: - r"""Return a callable for the list serving configs method over gRPC. - - Lists all ServingConfigs linked to this catalog. - - Returns: - Callable[[~.ListServingConfigsRequest], - ~.ListServingConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: - self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/ListServingConfigs', - request_serializer=serving_config_service.ListServingConfigsRequest.serialize, - response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, - ) - return self._stubs['list_serving_configs'] - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the add control method over gRPC. - - Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - Returns: - Callable[[~.AddControlRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_control' not in self._stubs: - self._stubs['add_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/AddControl', - request_serializer=serving_config_service.AddControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['add_control'] - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the remove control method over gRPC. - - Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - Returns: - Callable[[~.RemoveControlRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_control' not in self._stubs: - self._stubs['remove_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/RemoveControl', - request_serializer=serving_config_service.RemoveControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['remove_control'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ServingConfigServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py deleted file mode 100644 index b2524461..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,437 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ServingConfigServiceGrpcTransport - - -class ServingConfigServiceGrpcAsyncIOTransport(ServingConfigServiceTransport): - """gRPC AsyncIO backend transport for ServingConfigService. - - Service for modifying ServingConfig. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the create serving config method over gRPC. - - Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - Returns: - Callable[[~.CreateServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/CreateServingConfig', - request_serializer=serving_config_service.CreateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['create_serving_config'] - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete serving config method over gRPC. - - Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.DeleteServingConfigRequest], - 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_serving_config' not in self._stubs: - self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/DeleteServingConfig', - request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_serving_config'] - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the update serving config method over gRPC. - - Updates a ServingConfig. - - Returns: - Callable[[~.UpdateServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/UpdateServingConfig', - request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['update_serving_config'] - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - Awaitable[serving_config.ServingConfig]]: - r"""Return a callable for the get serving config method over gRPC. - - Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.GetServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/GetServingConfig', - request_serializer=serving_config_service.GetServingConfigRequest.serialize, - response_deserializer=serving_config.ServingConfig.deserialize, - ) - return self._stubs['get_serving_config'] - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - Awaitable[serving_config_service.ListServingConfigsResponse]]: - r"""Return a callable for the list serving configs method over gRPC. - - Lists all ServingConfigs linked to this catalog. - - Returns: - Callable[[~.ListServingConfigsRequest], - Awaitable[~.ListServingConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: - self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/ListServingConfigs', - request_serializer=serving_config_service.ListServingConfigsRequest.serialize, - response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, - ) - return self._stubs['list_serving_configs'] - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the add control method over gRPC. - - Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - Returns: - Callable[[~.AddControlRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_control' not in self._stubs: - self._stubs['add_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/AddControl', - request_serializer=serving_config_service.AddControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['add_control'] - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the remove control method over gRPC. - - Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - Returns: - Callable[[~.RemoveControlRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_control' not in self._stubs: - self._stubs['remove_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/RemoveControl', - request_serializer=serving_config_service.RemoveControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['remove_control'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ServingConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py deleted file mode 100644 index 5f5171c1..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py deleted file mode 100644 index 1f08ee18..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py +++ /dev/null @@ -1,730 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on the customer - website. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(UserEventServiceClient.catalog_path) - parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) - product_path = staticmethod(UserEventServiceClient.product_path) - parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_write_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_collect_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_purge_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_import_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2alpha.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_rejoin_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py deleted file mode 100644 index f1dbd152..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py +++ /dev/null @@ -1,929 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[UserEventServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on the customer - website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_write_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_collect_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_purge_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeUserEventsRequest): - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_import_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2alpha.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportUserEventsRequest): - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_rejoin_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.RejoinUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.RejoinUserEventsRequest): - request = user_event_service.RejoinUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py deleted file mode 100644 index f53ee5d7..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py deleted file mode 100644 index 7a6f8e53..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py +++ /dev/null @@ -1,231 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_timeout=None, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_timeout=None, - client_info=client_info, - ), - self.purge_user_events: gapic_v1.method.wrap_method( - self.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.rejoin_user_events: gapic_v1.method.wrap_method( - self.rejoin_user_events, - 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 write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - user_event.UserEvent, - Awaitable[user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py deleted file mode 100644 index d51a4e1a..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,415 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index 0a70cf03..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,414 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - 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 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py deleted file mode 100644 index aa87618d..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py +++ /dev/null @@ -1,284 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .catalog import ( - AttributesConfig, - Catalog, - CatalogAttribute, - CompletionConfig, - MerchantCenterLink, - MerchantCenterLinkingConfig, - ProductLevelConfig, -) -from .catalog_service import ( - AddCatalogAttributeRequest, - GetAttributesConfigRequest, - GetCompletionConfigRequest, - GetDefaultBranchRequest, - GetDefaultBranchResponse, - ListCatalogsRequest, - ListCatalogsResponse, - RemoveCatalogAttributeRequest, - ReplaceCatalogAttributeRequest, - SetDefaultBranchRequest, - UpdateAttributesConfigRequest, - UpdateCatalogRequest, - UpdateCompletionConfigRequest, -) -from .common import ( - Audience, - ColorInfo, - Condition, - CustomAttribute, - FulfillmentInfo, - Image, - Interval, - LocalInventory, - PriceInfo, - Rating, - Rule, - UserInfo, - AttributeConfigLevel, - SearchSolutionUseCase, - SolutionType, -) -from .completion_service import ( - CompleteQueryRequest, - CompleteQueryResponse, -) -from .control import ( - Control, -) -from .control_service import ( - CreateControlRequest, - DeleteControlRequest, - GetControlRequest, - ListControlsRequest, - ListControlsResponse, - UpdateControlRequest, -) -from .export_config import ( - ExportErrorsConfig, - ExportMetadata, - ExportProductsResponse, - ExportUserEventsResponse, -) -from .import_config import ( - BigQuerySource, - CompletionDataInputConfig, - GcsSource, - ImportCompletionDataRequest, - ImportCompletionDataResponse, - ImportErrorsConfig, - ImportMetadata, - ImportProductsRequest, - ImportProductsResponse, - ImportUserEventsRequest, - ImportUserEventsResponse, - ProductInlineSource, - ProductInputConfig, - UserEventImportSummary, - UserEventInlineSource, - UserEventInputConfig, -) -from .prediction_service import ( - PredictRequest, - PredictResponse, -) -from .product import ( - Product, -) -from .product_service import ( - AddFulfillmentPlacesMetadata, - AddFulfillmentPlacesRequest, - AddFulfillmentPlacesResponse, - AddLocalInventoriesMetadata, - AddLocalInventoriesRequest, - AddLocalInventoriesResponse, - CreateProductRequest, - DeleteProductRequest, - GetProductRequest, - ListProductsRequest, - ListProductsResponse, - RemoveFulfillmentPlacesMetadata, - RemoveFulfillmentPlacesRequest, - RemoveFulfillmentPlacesResponse, - RemoveLocalInventoriesMetadata, - RemoveLocalInventoriesRequest, - RemoveLocalInventoriesResponse, - SetInventoryMetadata, - SetInventoryRequest, - SetInventoryResponse, - UpdateProductRequest, -) -from .promotion import ( - Promotion, -) -from .purge_config import ( - PurgeMetadata, - PurgeProductsMetadata, - PurgeProductsRequest, - PurgeProductsResponse, - PurgeUserEventsRequest, - PurgeUserEventsResponse, -) -from .search_service import ( - SearchRequest, - SearchResponse, -) -from .serving_config import ( - ServingConfig, -) -from .serving_config_service import ( - AddControlRequest, - CreateServingConfigRequest, - DeleteServingConfigRequest, - GetServingConfigRequest, - ListServingConfigsRequest, - ListServingConfigsResponse, - RemoveControlRequest, - UpdateServingConfigRequest, -) -from .user_event import ( - CompletionDetail, - ProductDetail, - PurchaseTransaction, - UserEvent, -) -from .user_event_service import ( - CollectUserEventRequest, - RejoinUserEventsMetadata, - RejoinUserEventsRequest, - RejoinUserEventsResponse, - WriteUserEventRequest, -) - -__all__ = ( - 'AttributesConfig', - 'Catalog', - 'CatalogAttribute', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'ProductLevelConfig', - 'AddCatalogAttributeRequest', - 'GetAttributesConfigRequest', - 'GetCompletionConfigRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - 'SetDefaultBranchRequest', - 'UpdateAttributesConfigRequest', - 'UpdateCatalogRequest', - 'UpdateCompletionConfigRequest', - 'Audience', - 'ColorInfo', - 'Condition', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'Rule', - 'UserInfo', - 'AttributeConfigLevel', - 'SearchSolutionUseCase', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Control', - 'CreateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - 'UpdateControlRequest', - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeProductsMetadata', - 'PurgeProductsRequest', - 'PurgeProductsResponse', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'ServingConfig', - 'AddControlRequest', - 'CreateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'RemoveControlRequest', - 'UpdateServingConfigRequest', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py deleted file mode 100644 index 1e4a7ab5..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py +++ /dev/null @@ -1,528 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'ProductLevelConfig', - 'CatalogAttribute', - 'AttributesConfig', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'Catalog', - }, -) - - -class ProductLevelConfig(proto.Message): - r"""Configures what level the product should be uploaded with - regards to how users will be send events and how predictions - will be made. - - Attributes: - ingestion_product_type (str): - The type of [Product][google.cloud.retail.v2alpha.Product]s - allowed to be ingested into the catalog. Acceptable values - are: - - - ``primary`` (default): You can ingest - [Product][google.cloud.retail.v2alpha.Product]s of all - types. When ingesting a - [Product][google.cloud.retail.v2alpha.Product], its type - will default to - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - if unset. - - ``variant``: You can only ingest - [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s. This - means - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] - cannot be empty. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``variant`` and - [merchant_center_product_id_field][google.cloud.retail.v2alpha.ProductLevelConfig.merchant_center_product_id_field] - is ``itemGroupId``, an INVALID_ARGUMENT error is returned. - - See `Using product - levels `__ - for more details. - merchant_center_product_id_field (str): - Which field of `Merchant Center - Product `__ - should be imported as - [Product.id][google.cloud.retail.v2alpha.Product.id]. - Acceptable values are: - - - ``offerId`` (default): Import ``offerId`` as the product - ID. - - ``itemGroupId``: Import ``itemGroupId`` as the product - ID. Notice that Retail API will choose one item from the - ones with the same ``itemGroupId``, and use it to - represent the item group. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``itemGroupId`` and - [ingestion_product_type][google.cloud.retail.v2alpha.ProductLevelConfig.ingestion_product_type] - is ``variant``, an INVALID_ARGUMENT error is returned. - - See `Using product - levels `__ - for more details. - """ - - ingestion_product_type = proto.Field( - proto.STRING, - number=1, - ) - merchant_center_product_id_field = proto.Field( - proto.STRING, - number=2, - ) - - -class CatalogAttribute(proto.Message): - r"""Catalog level attribute config for an attribute. For example, - if customers want to enable/disable facet for a specific - attribute. - - Attributes: - key (str): - Required. Attribute name. For example: ``color``, - ``brands``, ``attributes.custom_attribute``, such as - ``attributes.xyz``. - in_use (bool): - Output only. Indicates whether this attribute has been used - by any products. ``True`` if at least one - [Product][google.cloud.retail.v2alpha.Product] is using this - attribute in - [Product.attributes][google.cloud.retail.v2alpha.Product.attributes]. - Otherwise, this field is ``False``. - - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - can be pre-loaded by using [AddCatalogAttribute][], - [ImportCatalogAttributes][], or [UpdateAttributesConfig][] - APIs. This field is ``False`` for pre-loaded - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s. - - Only - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s - that are not in use by products can be deleted. - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s - that are in use by products cannot be deleted; however, - their configuration properties will reset to default values - upon removal request. - - After catalog changes, it takes about 10 minutes for this - field to update. - type_ (google.cloud.retail_v2alpha.types.CatalogAttribute.AttributeType): - Output only. The type of this attribute. This is derived - from the attribute in - [Product.attributes][google.cloud.retail.v2alpha.Product.attributes]. - indexable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.IndexableOption): - When - [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] - is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if INDEXABLE_ENABLED - attribute values are indexed so that it can be filtered, - faceted, or boosted in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - dynamic_facetable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.DynamicFacetableOption): - If DYNAMIC_FACETABLE_ENABLED, attribute values are available - for dynamic facet. Could only be DYNAMIC_FACETABLE_DISABLED - if - [CatalogAttribute.indexable_option][google.cloud.retail.v2alpha.CatalogAttribute.indexable_option] - is INDEXABLE_DISABLED. Otherwise, an INVALID_ARGUMENT error - is returned. - searchable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.SearchableOption): - When - [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] - is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if SEARCHABLE_ENABLED, - attribute values are searchable by text queries in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - If SEARCHABLE_ENABLED but attribute type is numerical, - attribute values will not be searchable by text queries in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - as there are no text values associated to numerical - attributes. - """ - class AttributeType(proto.Enum): - r"""The type of an attribute.""" - UNKNOWN = 0 - TEXTUAL = 1 - NUMERICAL = 2 - - class IndexableOption(proto.Enum): - r"""The status of the indexable option of a catalog attribute.""" - INDEXABLE_OPTION_UNSPECIFIED = 0 - INDEXABLE_ENABLED = 1 - INDEXABLE_DISABLED = 2 - - class DynamicFacetableOption(proto.Enum): - r"""The status of the dynamic facetable option of a catalog - attribute. - """ - DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 - DYNAMIC_FACETABLE_ENABLED = 1 - DYNAMIC_FACETABLE_DISABLED = 2 - - class SearchableOption(proto.Enum): - r"""The status of the searchable option of a catalog attribute.""" - SEARCHABLE_OPTION_UNSPECIFIED = 0 - SEARCHABLE_ENABLED = 1 - SEARCHABLE_DISABLED = 2 - - key = proto.Field( - proto.STRING, - number=1, - ) - in_use = proto.Field( - proto.BOOL, - number=9, - ) - type_ = proto.Field( - proto.ENUM, - number=10, - enum=AttributeType, - ) - indexable_option = proto.Field( - proto.ENUM, - number=5, - enum=IndexableOption, - ) - dynamic_facetable_option = proto.Field( - proto.ENUM, - number=6, - enum=DynamicFacetableOption, - ) - searchable_option = proto.Field( - proto.ENUM, - number=7, - enum=SearchableOption, - ) - - -class AttributesConfig(proto.Message): - r"""Catalog level attribute config. - - Attributes: - name (str): - Required. Immutable. The fully qualified resource name of - the attribute config. Format: - ``projects/*/locations/*/catalogs/*/attributesConfig`` - catalog_attributes (Mapping[str, google.cloud.retail_v2alpha.types.CatalogAttribute]): - Enable attribute(s) config at catalog level. For example, - indexable, dynamic_facetable, or searchable for each - attribute. - - The key is catalog attribute's name. For example: ``color``, - ``brands``, ``attributes.custom_attribute``, such as - ``attributes.xyz``. - - The maximum number of catalog attributes allowed in a - request is 1000. - attribute_config_level (google.cloud.retail_v2alpha.types.AttributeConfigLevel): - Output only. The - [AttributeConfigLevel][google.cloud.retail.v2alpha.AttributeConfigLevel] - used for this catalog. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - catalog_attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='CatalogAttribute', - ) - attribute_config_level = proto.Field( - proto.ENUM, - number=3, - enum=common.AttributeConfigLevel, - ) - - -class CompletionConfig(proto.Message): - r"""Catalog level autocomplete config for customers to customize - autocomplete feature's settings. - - Attributes: - name (str): - Required. Immutable. Fully qualified name - ``projects/*/locations/*/catalogs/*/completionConfig`` - matching_order (str): - Specifies the matching order for autocomplete suggestions, - e.g., a query consisting of 'sh' with 'out-of-order' - specified would suggest "women's shoes", whereas a query of - 'red s' with 'exact-prefix' specified would suggest "red - shoes". Currently supported values: - - - 'out-of-order' - - 'exact-prefix' - - Default value: 'exact-prefix'. - max_suggestions (int): - The maximum number of autocomplete - suggestions returned per term. The maximum - allowed max suggestions is 20. Default value is - 20. If left unset or set to 0, then will - fallback to default value. - min_prefix_length (int): - The minimum number of characters needed to be - typed in order to get suggestions. Default value - is 2. If left unset or set to 0, then will - fallback to default value. - auto_learning (bool): - If set to true, the auto learning function is enabled. Auto - learning uses user data to generate suggestions using ML - techniques. Default value is false. Only after enabling auto - learning can users use ``cloud-retail`` data in - [CompleteQueryRequest][google.cloud.retail.v2alpha.CompleteQueryRequest]. - suggestions_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the - autocomplete phrases uploaded by the customer. - last_suggestions_import_operation (str): - Output only. Name of the LRO corresponding to the latest - suggestion terms list import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - denylist_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the / - autocomplete denylist phrases uploaded by the - customer. - last_denylist_import_operation (str): - Output only. LRO corresponding to the latest denylist - import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - allowlist_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the - autocomplete allowlist phrases uploaded by the - customer. - last_allowlist_import_operation (str): - Output only. LRO corresponding to the latest allowlist - import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - matching_order = proto.Field( - proto.STRING, - number=2, - ) - max_suggestions = proto.Field( - proto.INT32, - number=3, - ) - min_prefix_length = proto.Field( - proto.INT32, - number=4, - ) - auto_learning = proto.Field( - proto.BOOL, - number=11, - ) - suggestions_input_config = proto.Field( - proto.MESSAGE, - number=5, - message=import_config.CompletionDataInputConfig, - ) - last_suggestions_import_operation = proto.Field( - proto.STRING, - number=6, - ) - denylist_input_config = proto.Field( - proto.MESSAGE, - number=7, - message=import_config.CompletionDataInputConfig, - ) - last_denylist_import_operation = proto.Field( - proto.STRING, - number=8, - ) - allowlist_input_config = proto.Field( - proto.MESSAGE, - number=9, - message=import_config.CompletionDataInputConfig, - ) - last_allowlist_import_operation = proto.Field( - proto.STRING, - number=10, - ) - - -class MerchantCenterLink(proto.Message): - r"""Represents a link between a Merchant Center account and a - branch. Once a link is established, products from the linked - merchant center account will be streamed to the linked branch. - - Attributes: - merchant_center_account_id (int): - Required. The linked `Merchant center account - id `__. - The account must be a standalone account or a sub-account of - a MCA. - branch_id (str): - The branch id (e.g. 0/1/2) within this catalog that products - from merchant_center_account_id are streamed to. When - updating this field, an empty value will use the currently - configured default branch. However, changing the default - branch later on won't change the linked branch here. - - A single branch id can only have one linked merchant center - account id. - destinations (Sequence[str]): - String representing the destination to import for, all if - left empty. List of possible values can be found here. - [https://support.google.com/merchants/answer/7501026] List - of allowed string values: "Shopping_ads", - "Buy_on_google_listings", "Display_ads", "Local_inventory - \_ads", "Free_listings", "Free_local_listings" NOTE: The - string values are case sensitive. - region_code (str): - Region code of offers to accept. 2-letter Uppercase ISO - 3166-1 alpha-2 code. List of values can be found - `here `__ - under the ``region`` tag. If left blank no region filtering - will be performed. - - Example value: ``US``. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. ISO - 639-1. - - This specifies the language of offers in Merchant Center - that will be accepted. If empty no language filtering will - be performed. - - Example value: ``en``. - """ - - merchant_center_account_id = proto.Field( - proto.INT64, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - destinations = proto.RepeatedField( - proto.STRING, - number=3, - ) - region_code = proto.Field( - proto.STRING, - number=4, - ) - language_code = proto.Field( - proto.STRING, - number=5, - ) - - -class MerchantCenterLinkingConfig(proto.Message): - r"""Configures Merchant Center linking. - Links contained in the config will be used to sync data from a - Merchant Center account to a Cloud Retail branch. - - Attributes: - links (Sequence[google.cloud.retail_v2alpha.types.MerchantCenterLink]): - Links between Merchant Center accounts and - branches. - """ - - links = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='MerchantCenterLink', - ) - - -class Catalog(proto.Message): - r"""The catalog configuration. - - Attributes: - name (str): - Required. Immutable. The fully qualified - resource name of the catalog. - display_name (str): - Required. Immutable. The catalog display name. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - product_level_config (google.cloud.retail_v2alpha.types.ProductLevelConfig): - Required. The product level configuration. - merchant_center_linking_config (google.cloud.retail_v2alpha.types.MerchantCenterLinkingConfig): - The Merchant Center linking configuration. - Once a link is added, the data stream from - Merchant Center to Cloud Retail will be enabled - automatically. The requester must have access to - the merchant center account in order to make - changes to this field. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - product_level_config = proto.Field( - proto.MESSAGE, - number=4, - message='ProductLevelConfig', - ) - merchant_center_linking_config = proto.Field( - proto.MESSAGE, - number=6, - message='MerchantCenterLinkingConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py deleted file mode 100644 index 21d9b1c2..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py +++ /dev/null @@ -1,453 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'UpdateCatalogRequest', - 'SetDefaultBranchRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'GetCompletionConfigRequest', - 'UpdateCompletionConfigRequest', - 'GetAttributesConfigRequest', - 'UpdateAttributesConfigRequest', - 'AddCatalogAttributeRequest', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - }, -) - - -class ListCatalogsRequest(proto.Message): - r"""Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - - Attributes: - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2alpha.Catalog]s under this - location, regardless of whether or not this location exists, - a PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of - [Catalog][google.cloud.retail.v2alpha.Catalog]s to return. - If unspecified, defaults to 50. The maximum allowed value is - 1000. Values above 1000 will be coerced to 1000. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [ListCatalogsResponse.next_page_token][google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token], - received from a previous - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListCatalogsResponse(proto.Message): - r"""Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - - Attributes: - catalogs (Sequence[google.cloud.retail_v2alpha.types.Catalog]): - All the customer's - [Catalog][google.cloud.retail.v2alpha.Catalog]s. - next_page_token (str): - A token that can be sent as - [ListCatalogsRequest.page_token][google.cloud.retail.v2alpha.ListCatalogsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - catalogs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateCatalogRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] - method. - - Attributes: - catalog (google.cloud.retail_v2alpha.types.Catalog): - Required. The [Catalog][google.cloud.retail.v2alpha.Catalog] - to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2alpha.Catalog], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2alpha.Catalog] 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 - [Catalog][google.cloud.retail.v2alpha.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - catalog = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class SetDefaultBranchRequest(proto.Message): - r"""Request message to set a specified branch as new default_branch. - - Attributes: - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - branch_id (str): - The final component of the resource name of a branch. - - This field must be one of "0", "1" or "2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If there are no sufficient active products in the targeted - branch and - [force][google.cloud.retail.v2alpha.SetDefaultBranchRequest.force] - is not set, a FAILED_PRECONDITION error is returned. - note (str): - Some note on this request, this can be retrieved by - [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch] - before next valid default branch set occurs. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - force (bool): - If set to true, it permits switching to a branch with - [branch_id][google.cloud.retail.v2alpha.SetDefaultBranchRequest.branch_id] - even if it has no sufficient active products. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - force = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetDefaultBranchRequest(proto.Message): - r"""Request message to show which branch is currently the default - branch. - - Attributes: - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - - -class GetDefaultBranchResponse(proto.Message): - r"""Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. - - Attributes: - branch (str): - Full resource name of the branch id currently - set as default branch. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when this branch is set to default. - note (str): - This corresponds to - [SetDefaultBranchRequest.note][google.cloud.retail.v2alpha.SetDefaultBranchRequest.note] - field, when this branch was set as default. - """ - - branch = proto.Field( - proto.STRING, - number=1, - ) - set_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - - -class GetCompletionConfigRequest(proto.Message): - r"""Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] - method. - - Attributes: - name (str): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateCompletionConfigRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] - method. - - Attributes: - completion_config (google.cloud.retail_v2alpha.types.CompletionConfig): - Required. The - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - 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 - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - """ - - completion_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.CompletionConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetAttributesConfigRequest(proto.Message): - r"""Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] - method. - - Attributes: - name (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateAttributesConfigRequest(proto.Message): - r"""Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] - method. - - Attributes: - attributes_config (google.cloud.retail_v2alpha.types.AttributesConfig): - Required. The - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - """ - - attributes_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.AttributesConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class AddCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - catalog_attribute (google.cloud.retail_v2alpha.types.CatalogAttribute): - Required. The - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - catalog_attribute = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_catalog.CatalogAttribute, - ) - - -class RemoveCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - key (str): - Required. The attribute name key of the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - key = proto.Field( - proto.STRING, - number=2, - ) - - -class ReplaceCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - catalog_attribute (google.cloud.retail_v2alpha.types.CatalogAttribute): - Required. The updated - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to update. The following are NOT supported: - - - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key] - - If not set, all supported fields are updated. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - catalog_attribute = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_catalog.CatalogAttribute, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py deleted file mode 100644 index 25fa2861..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py +++ /dev/null @@ -1,1179 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'AttributeConfigLevel', - 'SolutionType', - 'SearchSolutionUseCase', - 'Condition', - 'Rule', - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'LocalInventory', - }, -) - - -class AttributeConfigLevel(proto.Enum): - r"""At which level we offer configuration for attributes.""" - ATTRIBUTE_CONFIG_LEVEL_UNSPECIFIED = 0 - PRODUCT_LEVEL_ATTRIBUTE_CONFIG = 1 - CATALOG_LEVEL_ATTRIBUTE_CONFIG = 2 - - -class SolutionType(proto.Enum): - r"""The type of solution.""" - SOLUTION_TYPE_UNSPECIFIED = 0 - SOLUTION_TYPE_RECOMMENDATION = 1 - SOLUTION_TYPE_SEARCH = 2 - - -class SearchSolutionUseCase(proto.Enum): - r"""The use case of Cloud Retail Search.""" - SEARCH_SOLUTION_USE_CASE_UNSPECIFIED = 0 - SEARCH_SOLUTION_USE_CASE_SEARCH = 1 - SEARCH_SOLUTION_USE_CASE_BROWSE = 2 - - -class Condition(proto.Message): - r"""Metadata that is used to define a condition that triggers an action. - A valid condition must specify at least one of 'query_terms' or - 'products_filter'. If multiple fields are specified, the condition - is met if all the fields are satisfied e.g. if a set of query terms - and product_filter are set, then only items matching the - product_filter for requests with a query matching the query terms - wil get boosted. - - Attributes: - query_terms (Sequence[google.cloud.retail_v2alpha.types.Condition.QueryTerm]): - A list (up to 10 entries) of terms to match - the query on. If not specified, match all - queries. If many query terms are specified, the - condition is matched if any of the terms is a - match (i.e. using the OR operator). - active_time_range (Sequence[google.cloud.retail_v2alpha.types.Condition.TimeRange]): - Range of time(s) specifying when Condition is - active. Condition true if any time range - matches. - """ - - class QueryTerm(proto.Message): - r"""Query terms that we want to match on. - - Attributes: - value (str): - The value of the term to match on. - Value cannot be empty. - Value can have at most 3 terms if specified as a - partial match. Each space separated string is - considered as one term. Example) "a b c" is 3 - terms and allowed, " a b c d" is 4 terms and not - allowed for partial match. - full_match (bool): - Whether this is supposed to be a full or - partial match. - """ - - value = proto.Field( - proto.STRING, - number=1, - ) - full_match = proto.Field( - proto.BOOL, - number=2, - ) - - class TimeRange(proto.Message): - r"""Used for time-dependent conditions. - Example: Want to have rule applied for week long sale. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start of time range. Range is inclusive. - end_time (google.protobuf.timestamp_pb2.Timestamp): - End of time range. Range is inclusive. - """ - - start_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - query_terms = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=QueryTerm, - ) - active_time_range = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=TimeRange, - ) - - -class Rule(proto.Message): - r"""A rule is a condition-action pair - - - A condition defines when a rule is to be triggered. - - An action specifies what occurs on that trigger. Currently only - boost rules are supported. Currently only supported by the search - endpoint. - - 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: - boost_action (google.cloud.retail_v2alpha.types.Rule.BoostAction): - A boost action. - - This field is a member of `oneof`_ ``action``. - redirect_action (google.cloud.retail_v2alpha.types.Rule.RedirectAction): - Redirects a shopper to a specific page. - - This field is a member of `oneof`_ ``action``. - oneway_synonyms_action (google.cloud.retail_v2alpha.types.Rule.OnewaySynonymsAction): - Treats specific term as a synonym with a - group of terms. Group of terms will not be - treated as synonyms with the specific term. - - This field is a member of `oneof`_ ``action``. - do_not_associate_action (google.cloud.retail_v2alpha.types.Rule.DoNotAssociateAction): - Prevents term from being associated with - other terms. - - This field is a member of `oneof`_ ``action``. - replacement_action (google.cloud.retail_v2alpha.types.Rule.ReplacementAction): - Replaces specific terms in the query. - - This field is a member of `oneof`_ ``action``. - ignore_action (google.cloud.retail_v2alpha.types.Rule.IgnoreAction): - Ignores specific terms from query during - search. - - This field is a member of `oneof`_ ``action``. - filter_action (google.cloud.retail_v2alpha.types.Rule.FilterAction): - Filters results. - - This field is a member of `oneof`_ ``action``. - twoway_synonyms_action (google.cloud.retail_v2alpha.types.Rule.TwowaySynonymsAction): - Treats a set of terms as synonyms of one - another. - - This field is a member of `oneof`_ ``action``. - condition (google.cloud.retail_v2alpha.types.Condition): - Required. The condition that triggers the - rule. If the condition is empty, the rule will - always apply. - """ - - class BoostAction(proto.Message): - r"""A boost action to apply to results matching condition - specified above. - - Attributes: - boost (float): - Strength of the condition boost, which must be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - products_filter (str): - The filter can have a max size of 5000 characters. An - expression which specifies which products to apply an action - to. The syntax and supported fields are the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": *(id: - ANY("product_1", "product_2"))* *AND* *(colorFamilies: - ANY("Red", "Blue"))* - """ - - boost = proto.Field( - proto.FLOAT, - number=1, - ) - products_filter = proto.Field( - proto.STRING, - number=2, - ) - - class FilterAction(proto.Message): - r"""- Rule Condition: - - - No [Condition][query_terms] provided is a global match. - - 1 or more [Condition][query_terms] provided is combined with - OR operator. - - - Action Input: The request query and filter that will be applied - to the retrieved products, in addition to any filters already - provided with the SearchRequest. The AND operator is used to - combine the query's existing filters with the filter rule(s). - NOTE: May result in 0 results when filters conflict. - - Action Result: Filters the returned objects to be ONLY those that - passed the filter. - - Attributes: - filter (str): - A filter to apply on the matching condition results. - Supported features: - - - [filter][google.cloud.retail.v2alpha.Rule.FilterAction.filter] - must be set. - - Filter syntax is identical to - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter]. - See more details at the Retail Search `user - guide `__. - - To filter products with product ID "product_1" or - "product_2", and color "Red" or "Blue": *(id: - ANY("product_1", "product_2"))* *AND* *(colorFamilies: - ANY("Red", "Blue"))* - """ - - filter = proto.Field( - proto.STRING, - number=1, - ) - - class RedirectAction(proto.Message): - r"""Redirects a shopper to a specific page. - - - Rule Condition: - - - Must specify [Condition][query_terms]. - - - Action Input: Request Query - - Action Result: Redirects shopper to provided uri. - - Attributes: - redirect_uri (str): - URL must have length equal or less than 2000 - characters. - """ - - redirect_uri = proto.Field( - proto.STRING, - number=1, - ) - - class TwowaySynonymsAction(proto.Message): - r"""Creates a set of terms that will be treated as synonyms of each - other. Example: synonyms of "sneakers" and "shoes". - - - "sneakers" will use a synonym of "shoes". - - "shoes" will use a synonym of "sneakers". - - Attributes: - synonyms (Sequence[str]): - Defines a set of synonyms. - Can specify up to 100 synonyms. - Must specify at least 2 synonyms. - """ - - synonyms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class OnewaySynonymsAction(proto.Message): - r"""Maps a set of terms to a set of synonyms. Set of synonyms will be - treated as synonyms of each query term only. ``query_terms`` will - not be treated as synonyms of each other. Example: "sneakers" will - use a synonym of "shoes". "shoes" will not use a synonym of - "sneakers". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. - Will treat synonyms as their synonyms. - Not themselves synonyms of the synonyms. - Can specify up to 100 terms. - synonyms (Sequence[str]): - Defines a set of synonyms. - Cannot contain duplicates. - Can specify up to 100 synonyms. - oneway_terms (Sequence[str]): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=3, - ) - synonyms = proto.RepeatedField( - proto.STRING, - number=4, - ) - oneway_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class DoNotAssociateAction(proto.Message): - r"""Prevents ``query_term`` from being associated with specified terms - during search. Example: Don't associate "gShoe" and "cheap". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. Will not consider - do_not_associate_terms for search if in search query. Can - specify up to 100 terms. - do_not_associate_terms (Sequence[str]): - Cannot contain duplicates or the query term. - Can specify up to 100 terms. - terms (Sequence[str]): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - do_not_associate_terms = proto.RepeatedField( - proto.STRING, - number=3, - ) - terms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class ReplacementAction(proto.Message): - r"""Replaces a term in the query. Multiple replacement candidates can be - specified. All ``query_terms`` will be replaced with the replacement - term. Example: Replace "gShoe" with "google shoe". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. - Will be replaced by replacement term. - Can specify up to 100 terms. - replacement_term (str): - Term that will be used for replacement. - term (str): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - replacement_term = proto.Field( - proto.STRING, - number=3, - ) - term = proto.Field( - proto.STRING, - number=1, - ) - - class IgnoreAction(proto.Message): - r"""Prevents a term in the query from being used in search. - Example: Don't search for "shoddy". - - Attributes: - ignore_terms (Sequence[str]): - Terms to ignore in the search query. - """ - - ignore_terms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - boost_action = proto.Field( - proto.MESSAGE, - number=2, - oneof='action', - message=BoostAction, - ) - redirect_action = proto.Field( - proto.MESSAGE, - number=3, - oneof='action', - message=RedirectAction, - ) - oneway_synonyms_action = proto.Field( - proto.MESSAGE, - number=6, - oneof='action', - message=OnewaySynonymsAction, - ) - do_not_associate_action = proto.Field( - proto.MESSAGE, - number=7, - oneof='action', - message=DoNotAssociateAction, - ) - replacement_action = proto.Field( - proto.MESSAGE, - number=8, - oneof='action', - message=ReplacementAction, - ) - ignore_action = proto.Field( - proto.MESSAGE, - number=9, - oneof='action', - message=IgnoreAction, - ) - filter_action = proto.Field( - proto.MESSAGE, - number=10, - oneof='action', - message=FilterAction, - ) - twoway_synonyms_action = proto.Field( - proto.MESSAGE, - number=11, - oneof='action', - message=TwowaySynonymsAction, - ) - condition = proto.Field( - proto.MESSAGE, - number=1, - message='Condition', - ) - - -class Audience(proto.Message): - r"""An intended audience of the - [Product][google.cloud.retail.v2alpha.Product] for whom it's sold. - - Attributes: - genders (Sequence[str]): - The genders of the audience. Strongly encouraged to use the - standard values: "male", "female", "unisex". - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `gender `__. - Schema.org property - `Product.audience.suggestedGender `__. - age_groups (Sequence[str]): - The age groups of the audience. Strongly encouraged to use - the standard values: "newborn" (up to 3 months old), - "infant" (3–12 months old), "toddler" (1–5 years old), - "kids" (5–13 years old), "adult" (typically teens or older). - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `age_group `__. - Schema.org property - `Product.audience.suggestedMinAge `__ - and - `Product.audience.suggestedMaxAge `__. - """ - - genders = proto.RepeatedField( - proto.STRING, - number=1, - ) - age_groups = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class ColorInfo(proto.Message): - r"""The color information of a - [Product][google.cloud.retail.v2alpha.Product]. - - Attributes: - color_families (Sequence[str]): - The standard color families. Strongly recommended to use the - following standard color groups: "Red", "Pink", "Orange", - "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", - "White", "Gray", "Black" and "Mixed". Normally it is - expected to have only 1 color family. May consider using - single "Mixed" instead of multiple values. - - A maximum of 5 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - colors (Sequence[str]): - The color display names, which may be different from - standard color family names, such as the color aliases used - in the website frontend. Normally it is expected to have - only 1 color. May consider using single "Mixed" instead of - multiple values. - - A maximum of 25 colors are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - """ - - color_families = proto.RepeatedField( - proto.STRING, - number=1, - ) - colors = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class CustomAttribute(proto.Message): - r"""A custom attribute that is not explicitly modeled in - [Product][google.cloud.retail.v2alpha.Product]. - - Attributes: - text (Sequence[str]): - The textual values of this custom attribute. For example, - ``["yellow", "green"]`` when the key is "color". - - Empty string is not allowed. Otherwise, an INVALID_ARGUMENT - error is returned. - - Exactly one of - [text][google.cloud.retail.v2alpha.CustomAttribute.text] or - [numbers][google.cloud.retail.v2alpha.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - numbers (Sequence[float]): - The numerical values of this custom attribute. For example, - ``[2.3, 15.4]`` when the key is "lengths_cm". - - Exactly one of - [text][google.cloud.retail.v2alpha.CustomAttribute.text] or - [numbers][google.cloud.retail.v2alpha.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - searchable (bool): - This field will only be used when - [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] - of the [Catalog][google.cloud.retail.v2alpha.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are searchable by text queries in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2alpha.UserEvent]. - - Only set if type - [text][google.cloud.retail.v2alpha.CustomAttribute.text] is - set. Otherwise, a INVALID_ARGUMENT error is returned. - - This field is a member of `oneof`_ ``_searchable``. - indexable (bool): - This field will only be used when - [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] - of the [Catalog][google.cloud.retail.v2alpha.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are indexed, so that it can be filtered, faceted or - boosted in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2alpha.UserEvent]. - - See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter], - [SearchRequest.facet_specs][google.cloud.retail.v2alpha.SearchRequest.facet_specs] - and - [SearchRequest.boost_spec][google.cloud.retail.v2alpha.SearchRequest.boost_spec] - for more details. - - This field is a member of `oneof`_ ``_indexable``. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - numbers = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - searchable = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - indexable = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - -class FulfillmentInfo(proto.Message): - r"""Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - Attributes: - type_ (str): - The fulfillment type, including commonly used types (such as - pickup in store and same day delivery), and custom types. - Customers have to map custom types to their display names - before rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - place_ids (Sequence[str]): - The IDs for this - [type][google.cloud.retail.v2alpha.FulfillmentInfo.type], - such as the store IDs for - [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2alpha.FulfillmentInfo.type] - or the region IDs for - [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2alpha.FulfillmentInfo.type]. - - A maximum of 3000 values are allowed. Each value must be a - string with a length limit of 30 characters, matching the - pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". - Otherwise, an INVALID_ARGUMENT error is returned. - """ - - type_ = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class Image(proto.Message): - r"""[Product][google.cloud.retail.v2alpha.Product] image. - Recommendations AI and Retail Search do not use product images to - improve prediction and search results. However, product images can - be returned in results, and are shown in prediction or search - previews in the console. - - Attributes: - uri (str): - Required. URI of the image. - - This field must be a valid UTF-8 encoded URI with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - height (int): - Height of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - width (int): - Width of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - height = proto.Field( - proto.INT32, - number=2, - ) - width = proto.Field( - proto.INT32, - number=3, - ) - - -class Interval(proto.Message): - r"""A floating point interval. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - minimum (float): - Inclusive lower bound. - - This field is a member of `oneof`_ ``min``. - exclusive_minimum (float): - Exclusive lower bound. - - This field is a member of `oneof`_ ``min``. - maximum (float): - Inclusive upper bound. - - This field is a member of `oneof`_ ``max``. - exclusive_maximum (float): - Exclusive upper bound. - - This field is a member of `oneof`_ ``max``. - """ - - minimum = proto.Field( - proto.DOUBLE, - number=1, - oneof='min', - ) - exclusive_minimum = proto.Field( - proto.DOUBLE, - number=2, - oneof='min', - ) - maximum = proto.Field( - proto.DOUBLE, - number=3, - oneof='max', - ) - exclusive_maximum = proto.Field( - proto.DOUBLE, - number=4, - oneof='max', - ) - - -class PriceInfo(proto.Message): - r"""The price information of a - [Product][google.cloud.retail.v2alpha.Product]. - - Attributes: - currency_code (str): - The 3-letter currency code defined in `ISO - 4217 `__. - - If this field is an unrecognizable currency code, an - INVALID_ARGUMENT error is returned. - - The - [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s with the - same - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] - must share the same - [currency_code][google.cloud.retail.v2alpha.PriceInfo.currency_code]. - Otherwise, a FAILED_PRECONDITION error is returned. - price (float): - Price of the product. - - Google Merchant Center property - `price `__. - Schema.org property - `Offer.price `__. - original_price (float): - Price of the product without any discount. If zero, by - default set to be the - [price][google.cloud.retail.v2alpha.PriceInfo.price]. - cost (float): - The costs associated with the sale of a particular product. - Used for gross profit reporting. - - - Profit = - [price][google.cloud.retail.v2alpha.PriceInfo.price] - - [cost][google.cloud.retail.v2alpha.PriceInfo.cost] - - Google Merchant Center property - `cost_of_goods_sold `__. - price_effective_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2alpha.PriceInfo.price] starts - to be effective. This can be set as a future timestamp, and - the [price][google.cloud.retail.v2alpha.PriceInfo.price] is - only used for search after - [price_effective_time][google.cloud.retail.v2alpha.PriceInfo.price_effective_time]. - If so, the - [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - is used before - [price_effective_time][google.cloud.retail.v2alpha.PriceInfo.price_effective_time]. - - Do not set if - [price][google.cloud.retail.v2alpha.PriceInfo.price] is - always effective because it will cause additional latency - during search. - price_expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2alpha.PriceInfo.price] stops - to be effective. The - [price][google.cloud.retail.v2alpha.PriceInfo.price] is used - for search before - [price_expire_time][google.cloud.retail.v2alpha.PriceInfo.price_expire_time]. - If this field is set, the - [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - is used after - [price_expire_time][google.cloud.retail.v2alpha.PriceInfo.price_expire_time]. - - Do not set if - [price][google.cloud.retail.v2alpha.PriceInfo.price] is - always effective because it will cause additional latency - during search. - price_range (google.cloud.retail_v2alpha.types.PriceInfo.PriceRange): - Output only. The price range of all the child - [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s grouped - together on the - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]. Only - populated for - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct]. - Do not set this field in API requests. - """ - - class PriceRange(proto.Message): - r"""The price range of all - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. - - Attributes: - price (google.cloud.retail_v2alpha.types.Interval): - The inclusive - [Product.pricing_info.price][google.cloud.retail.v2alpha.PriceInfo.price] - interval of all - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] having the - same - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. - original_price (google.cloud.retail_v2alpha.types.Interval): - The inclusive - [Product.pricing_info.original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - internal of all - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] having the - same - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. - """ - - price = proto.Field( - proto.MESSAGE, - number=1, - message='Interval', - ) - original_price = proto.Field( - proto.MESSAGE, - number=2, - message='Interval', - ) - - currency_code = proto.Field( - proto.STRING, - number=1, - ) - price = proto.Field( - proto.FLOAT, - number=2, - ) - original_price = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - price_effective_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - price_expire_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - price_range = proto.Field( - proto.MESSAGE, - number=7, - message=PriceRange, - ) - - -class Rating(proto.Message): - r"""The rating of a [Product][google.cloud.retail.v2alpha.Product]. - - Attributes: - rating_count (int): - The total number of ratings. This value is independent of - the value of - [rating_histogram][google.cloud.retail.v2alpha.Rating.rating_histogram]. - - This value must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - average_rating (float): - The average rating of the - [Product][google.cloud.retail.v2alpha.Product]. - - The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT - error is returned. - rating_histogram (Sequence[int]): - List of rating counts per rating value (index = rating - 1). - The list is empty if there is no rating. If the list is - non-empty, its size is always 5. Otherwise, an - INVALID_ARGUMENT error is returned. - - For example, [41, 14, 13, 47, 303]. It means that the - [Product][google.cloud.retail.v2alpha.Product] got 41 - ratings with 1 star, 14 ratings with 2 star, and so on. - """ - - rating_count = proto.Field( - proto.INT32, - number=1, - ) - average_rating = proto.Field( - proto.FLOAT, - number=2, - ) - rating_histogram = proto.RepeatedField( - proto.INT32, - number=3, - ) - - -class UserInfo(proto.Message): - r"""Information of an end user. - - Attributes: - user_id (str): - Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. - - Always use a hashed value for this ID. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - ip_address (str): - The end user's IP address. This field is used to extract - location information for personalization. - - This field must be either an IPv4 address (e.g. - "104.133.9.80") or an IPv6 address (e.g. - "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an - INVALID_ARGUMENT error is returned. - - This should not be set when: - - - setting - [SearchRequest.user_info][google.cloud.retail.v2alpha.SearchRequest.user_info]. - - using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2alpha.UserInfo.direct_user_request] - is set. - user_agent (str): - User agent as included in the HTTP header. Required for - getting - [SearchResponse.sponsored_results][google.cloud.retail.v2alpha.SearchResponse.sponsored_results]. - - The field must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This should not be set when using the client side event - reporting with GTM or JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2alpha.UserInfo.direct_user_request] - is set. - direct_user_request (bool): - True if the request is made directly from the end user, in - which case the - [ip_address][google.cloud.retail.v2alpha.UserInfo.ip_address] - and - [user_agent][google.cloud.retail.v2alpha.UserInfo.user_agent] - can be populated from the HTTP request. This flag should be - set only if the API request is made directly from the end - user such as a mobile app (and not if a gateway or a server - is processing and pushing the user events). - - This should not be set when using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent]. - """ - - user_id = proto.Field( - proto.STRING, - number=1, - ) - ip_address = proto.Field( - proto.STRING, - number=2, - ) - user_agent = proto.Field( - proto.STRING, - number=3, - ) - direct_user_request = proto.Field( - proto.BOOL, - number=4, - ) - - -class LocalInventory(proto.Message): - r"""The inventory information at a place (e.g. a store) - identified by a place ID. - - Attributes: - place_id (str): - The place ID for the current set of inventory - information. - price_info (google.cloud.retail_v2alpha.types.PriceInfo): - Product price and cost information. - - Google Merchant Center property - `price `__. - attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): - Additional local inventory attributes, for example, store - name, promotion tags, etc. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - At most 30 attributes are allowed. - - The key must be a UTF-8 encoded string with a length - limit of 32 characters. - - The key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis - or KEY_1_LIKE_THIS. - - The attribute values must be of the same type (text or - number). - - Only 1 value is allowed for each attribute. - - For text values, the length limit is 256 UTF-8 - characters. - - The attribute does not support search. The ``searchable`` - field should be unset or set to false. - - The max summed total bytes of custom attribute keys and - values per product is 5MiB. - fulfillment_types (Sequence[str]): - Input only. Supported fulfillment types. Valid fulfillment - type values include commonly used types (such as pickup in - store and same day delivery), and custom types. Customers - have to map custom types to their display names before - rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - All the elements must be distinct. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - place_id = proto.Field( - proto.STRING, - number=1, - ) - price_info = proto.Field( - proto.MESSAGE, - number=2, - message='PriceInfo', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='CustomAttribute', - ) - fulfillment_types = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py deleted file mode 100644 index f3bb27b3..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'CompleteQueryRequest', - 'CompleteQueryResponse', - }, -) - - -class CompleteQueryRequest(proto.Message): - r"""Auto-complete parameters. - - Attributes: - catalog (str): - Required. Catalog for which the completion is performed. - - Full resource name of catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - query (str): - Required. The query used to generate - suggestions. - The maximum number of allowed characters is 255. - visitor_id (str): - Required field. A unique identifier for tracking visitors. - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - language_codes (Sequence[str]): - The language filters applied to the output suggestions. If - set, it should contain the language of the query. If not - set, suggestions are returned without considering language - restrictions. This is the BCP-47 language code, such as - "en-US" or "sr-Latn". For more information, see `Tags for - Identifying - Languages `__. The - maximum number of language codes is 3. - device_type (str): - The device type context for completion suggestions. It is - useful to apply different suggestions on different device - types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the - suggestions are across all device types. - - Supported formats: - - - ``UNKNOWN_DEVICE_TYPE`` - - - ``DESKTOP`` - - - ``MOBILE`` - - - A customized string starts with ``OTHER_``, e.g. - ``OTHER_IPHONE``. - dataset (str): - Determines which dataset to use for fetching completion. - "user-data" will use the imported dataset through - [CompletionService.ImportCompletionData][google.cloud.retail.v2alpha.CompletionService.ImportCompletionData]. - "cloud-retail" will use the dataset generated by cloud - retail based on user events. If leave empty, it will use the - "user-data". - - Current supported values: - - - user-data - - - cloud-retail This option requires additional - allowlisting. Before using cloud-retail, contact Cloud - Retail support team first. - max_suggestions (int): - Completion max suggestions. If left unset or set to 0, then - will fallback to the configured value - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions]. - - The maximum allowed max suggestions is 20. If it is set - higher, it will be capped by 20. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - visitor_id = proto.Field( - proto.STRING, - number=7, - ) - language_codes = proto.RepeatedField( - proto.STRING, - number=3, - ) - device_type = proto.Field( - proto.STRING, - number=4, - ) - dataset = proto.Field( - proto.STRING, - number=6, - ) - max_suggestions = proto.Field( - proto.INT32, - number=5, - ) - - -class CompleteQueryResponse(proto.Message): - r"""Response of the auto-complete query. - - Attributes: - completion_results (Sequence[google.cloud.retail_v2alpha.types.CompleteQueryResponse.CompletionResult]): - Results of the matching suggestions. The - result list is ordered and the first result is - top suggestion. - attribution_token (str): - A unique complete token. This should be included in the - [UserEvent.completion_detail][google.cloud.retail.v2alpha.UserEvent.completion_detail] - for search events resulting from this completion, which - enables accurate attribution of complete model performance. - recent_search_results (Sequence[google.cloud.retail_v2alpha.types.CompleteQueryResponse.RecentSearchResult]): - Matched recent searches of this user. The maximum number of - recent searches is 10. This field is a restricted feature. - Contact Retail Search support team if you are interested in - enabling it. - - This feature is only available when - [CompleteQueryRequest.visitor_id][google.cloud.retail.v2alpha.CompleteQueryRequest.visitor_id] - field is set and - [UserEvent][google.cloud.retail.v2alpha.UserEvent] is - imported. The recent searches satisfy the follow rules: - - - They are ordered from latest to oldest. - - They are matched with - [CompleteQueryRequest.query][google.cloud.retail.v2alpha.CompleteQueryRequest.query] - case insensitively. - - They are transformed to lower cases. - - They are UTF-8 safe. - - Recent searches are deduplicated. More recent searches will - be reserved when duplication happens. - """ - - class CompletionResult(proto.Message): - r"""Resource that represents completion results. - - Attributes: - suggestion (str): - The suggestion for the query. - attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): - Custom attributes for the suggestion term. - - - For "user-data", the attributes are additional custom - attributes ingested through BigQuery. - - For "cloud-retail", the attributes are product attributes - generated by Cloud Retail. - """ - - suggestion = proto.Field( - proto.STRING, - number=1, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=common.CustomAttribute, - ) - - class RecentSearchResult(proto.Message): - r"""Recent search of this user. - - Attributes: - recent_search (str): - The recent search query. - """ - - recent_search = proto.Field( - proto.STRING, - number=1, - ) - - completion_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=CompletionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - recent_search_results = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=RecentSearchResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py deleted file mode 100644 index 93e84d08..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py +++ /dev/null @@ -1,123 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'Control', - }, -) - - -class Control(proto.Message): - r"""Configures dynamic serving time metadata that is used to pre - and post process search/recommendation model results. - - 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: - facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec): - A facet specification to perform faceted - search. - - This field is a member of `oneof`_ ``control``. - rule (google.cloud.retail_v2alpha.types.Rule): - A rule control - a condition-action pair. - Enacts a set action when the condition is - triggered. For example: Boost "gShoe" when query - full matches "Running Shoes". - - This field is a member of `oneof`_ ``control``. - name (str): - Immutable. Fully qualified name - projects/\ */locations/global/catalogs/*/controls/\* - display_name (str): - Required. The human readable control display name. Used in - Retail UI. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is thrown. - associated_serving_config_ids (Sequence[str]): - Output only. List of serving configuration - ids that that are associated with this control. - Note the association is managed via the - ServingConfig, this is an output only - denormalizeed view. Assumed to be in the same - catalog. - solution_types (Sequence[google.cloud.retail_v2alpha.types.SolutionType]): - Required. Immutable. The solution types that the serving - config is used for. Currently we support setting only one - type of solution at creation time. - - Only ``SOLUTION_TYPE_SEARCH`` value is supported at the - moment. If no solution type is provided at creation time, - will default to SOLUTION_TYPE_SEARCH. - search_solution_use_case (Sequence[google.cloud.retail_v2alpha.types.SearchSolutionUseCase]): - Required. Specifies the use case for the control. Affects - what condition fields can be set. Only settable by search - controls. Will default to SEARCH_SOLUTION_USE_CASE_SEARCH if - not specified. Currently only allow one - search_solution_use_case per control. - """ - - facet_spec = proto.Field( - proto.MESSAGE, - number=3, - oneof='control', - message=search_service.SearchRequest.FacetSpec, - ) - rule = proto.Field( - proto.MESSAGE, - number=4, - oneof='control', - message=common.Rule, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - associated_serving_config_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - solution_types = proto.RepeatedField( - proto.ENUM, - number=6, - enum=common.SolutionType, - ) - search_solution_use_case = proto.RepeatedField( - proto.ENUM, - number=7, - enum=common.SearchSolutionUseCase, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py deleted file mode 100644 index da0c4915..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py +++ /dev/null @@ -1,197 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'CreateControlRequest', - 'UpdateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - }, -) - - -class CreateControlRequest(proto.Message): - r"""Request for CreateControl method. - - Attributes: - parent (str): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - control (google.cloud.retail_v2alpha.types.Control): - Required. The Control to create. - control_id (str): - Required. The ID to use for the Control, which will become - the final component of the Control's resource name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-_/. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - control = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_control.Control, - ) - control_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateControlRequest(proto.Message): - r"""Request for UpdateControl method. - - Attributes: - control (google.cloud.retail_v2alpha.types.Control): - Required. The Control to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Control][google.cloud.retail.v2alpha.Control] to update. - The following are NOT supported: - - - [Control.name][google.cloud.retail.v2alpha.Control.name] - - If not set or empty, all supported fields are updated. - """ - - control = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_control.Control, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteControlRequest(proto.Message): - r"""Request for DeleteControl method. - - Attributes: - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetControlRequest(proto.Message): - r"""Request for GetControl method. - - Attributes: - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListControlsRequest(proto.Message): - r"""Request for ListControls method. - - Attributes: - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - page_size (int): - Optional. Maximum number of results to - return. If unspecified, defaults to 50. Max - allowed value is 1000. - page_token (str): - Optional. A page token, received from a previous - ``ListControls`` call. Provide this to retrieve the - subsequent page. - filter (str): - Optional. A filter to apply on the list results. Supported - features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2alpha.ListControlsRequest.filter] - is unset. - - List controls that are used in a single ServingConfig: - 'serving_config = "boosted_home_page_cvr"' - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListControlsResponse(proto.Message): - r"""Response for ListControls method. - - Attributes: - controls (Sequence[google.cloud.retail_v2alpha.types.Control]): - All the Controls for a given catalog. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - controls = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_control.Control, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py deleted file mode 100644 index ffb42fde..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py +++ /dev/null @@ -1,134 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - }, -) - - -class ExportErrorsConfig(proto.Message): - r"""Configuration of destination for Export related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage path for import errors. This must be an - empty, existing Cloud Storage bucket. Export errors will be - written to a file in this bucket, one per line, as a - JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ExportMetadata(proto.Message): - r"""Metadata related to the progress of the Export operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class ExportProductsResponse(proto.Message): - r"""Response of the ExportProductsRequest. If the long running - operation is done, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2alpha.types.ExportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExportErrorsConfig', - ) - - -class ExportUserEventsResponse(proto.Message): - r"""Response of the ExportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2alpha.types.ExportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExportErrorsConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py deleted file mode 100644 index b6260358..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py +++ /dev/null @@ -1,691 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import user_event -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'GcsSource', - 'BigQuerySource', - 'ProductInlineSource', - 'UserEventInlineSource', - 'ImportErrorsConfig', - 'ImportProductsRequest', - 'ImportUserEventsRequest', - 'ImportCompletionDataRequest', - 'ProductInputConfig', - 'UserEventInputConfig', - 'CompletionDataInputConfig', - 'ImportMetadata', - 'ImportProductsResponse', - 'ImportUserEventsResponse', - 'UserEventImportSummary', - 'ImportCompletionDataResponse', - }, -) - - -class GcsSource(proto.Message): - r"""Google Cloud Storage location for input content. - format. - - Attributes: - input_uris (Sequence[str]): - Required. Google Cloud Storage URIs to input files. URI can - be up to 2000 characters long. URIs can match the full - object path (for example, - ``gs://bucket/directory/object.json``) or a pattern matching - one or more files, such as ``gs://bucket/directory/*.json``. - A request can contain at most 100 files, and each file can - be up to 2 GB. See `Importing product - information `__ - for the expected file format and setup instructions. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2alpha.Product] per line. - Each product must have a valid - [Product.id][google.cloud.retail.v2alpha.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2alpha.UserEvent] per - line. - - ``user_event_ga360``: Using - https://support.google.com/analytics/answer/3437719. - - Supported values for control imports: - - - 'control' (default): One JSON - [Control][google.cloud.retail.v2alpha.Control] per line. - - Supported values for catalog attribute imports: - - - 'catalog_attribute' (default): One CSV - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - per line. - """ - - input_uris = proto.RepeatedField( - proto.STRING, - number=1, - ) - data_schema = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""BigQuery source import data from. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - partition_date (google.type.date_pb2.Date): - BigQuery time partitioned table's \_PARTITIONDATE in - YYYY-MM-DD format. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - - This field is a member of `oneof`_ ``partition``. - project_id (str): - The project ID (can be project # or ID) that - the BigQuery source is in with a length limit of - 128 characters. If not specified, inherits the - project ID from the parent request. - dataset_id (str): - Required. The BigQuery data set to copy the - data from with a length limit of 1,024 - characters. - table_id (str): - Required. The BigQuery table to copy the data - from with a length limit of 1,024 characters. - gcs_staging_dir (str): - Intermediate Cloud Storage directory used for - the import with a length limit of 2,000 - characters. Can be specified if one wants to - have the BigQuery export to a specific Cloud - Storage directory. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2alpha.Product] per line. - Each product must have a valid - [Product.id][google.cloud.retail.v2alpha.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2alpha.UserEvent] per - line. - - ``user_event_ga360``: The schema is available here: - https://support.google.com/analytics/answer/3437719. - - ``user_event_ga4``: This feature is in private preview. - Please contact the support team for importing Google - Analytics 4 events. The schema is available here: - https://support.google.com/analytics/answer/7029846. - - Supported values for auto-completion imports: - - - ``suggestions`` (default): One JSON completion suggestion - per line. - - ``denylist``: One JSON deny suggestion per line. - - ``allowlist``: One JSON allow suggestion per line. - """ - - partition_date = proto.Field( - proto.MESSAGE, - number=6, - oneof='partition', - message=date_pb2.Date, - ) - project_id = proto.Field( - proto.STRING, - number=5, - ) - dataset_id = proto.Field( - proto.STRING, - number=1, - ) - table_id = proto.Field( - proto.STRING, - number=2, - ) - gcs_staging_dir = proto.Field( - proto.STRING, - number=3, - ) - data_schema = proto.Field( - proto.STRING, - number=4, - ) - - -class ProductInlineSource(proto.Message): - r"""The inline source for the input config for ImportProducts - method. - - Attributes: - products (Sequence[google.cloud.retail_v2alpha.types.Product]): - Required. A list of products to update/create. Each product - must have a valid - [Product.id][google.cloud.retail.v2alpha.Product.id]. - Recommended max of 100 items. - """ - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=product.Product, - ) - - -class UserEventInlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (Sequence[google.cloud.retail_v2alpha.types.UserEvent]): - Required. A list of user events to import. - Recommended max of 10k items. - """ - - user_events = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - -class ImportErrorsConfig(proto.Message): - r"""Configuration of destination for Import related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage prefix for import errors. This must be - an empty, existing Cloud Storage directory. Import errors - will be written to sharded files in this directory, one per - line, as a JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportProductsRequest(proto.Message): - r"""Request message for Import methods. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` - - If no updateMask is specified, requires products.create - permission. If updateMask is specified, requires - products.update permission. - request_id (str): - Deprecated. This field has no effect. - input_config (google.cloud.retail_v2alpha.types.ProductInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - imported 'products' to update. If not set, will - by default update all fields. - reconciliation_mode (google.cloud.retail_v2alpha.types.ImportProductsRequest.ReconciliationMode): - The mode of reconciliation between existing products and the - products to be imported. Defaults to - [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - """ - class ReconciliationMode(proto.Enum): - r"""Indicates how imported products are reconciled with the - existing products created or imported before. - """ - RECONCILIATION_MODE_UNSPECIFIED = 0 - INCREMENTAL = 1 - FULL = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - request_id = proto.Field( - proto.STRING, - number=6, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='ProductInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - reconciliation_mode = proto.Field( - proto.ENUM, - number=5, - enum=ReconciliationMode, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=7, - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog`` - input_config (google.cloud.retail_v2alpha.types.UserEventInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. Cannot be set for inline user - event imports. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='UserEventInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - - -class ImportCompletionDataRequest(proto.Message): - r"""Request message for ImportCompletionData methods. - - Attributes: - parent (str): - Required. The catalog which the suggestions dataset belongs - to. - - Format: - ``projects/1234/locations/global/catalogs/default_catalog``. - input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): - Required. The desired input location of the - data. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='CompletionDataInputConfig', - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=3, - ) - - -class ProductInputConfig(proto.Message): - r"""The input config source for products. - - 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: - product_inline_source (google.cloud.retail_v2alpha.types.ProductInlineSource): - The Inline source for the input content for - products. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2alpha.types.GcsSource): - Google Cloud Storage location for the input - content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - product_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='ProductInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class UserEventInputConfig(proto.Message): - r"""The input config source for user events. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - user_event_inline_source (google.cloud.retail_v2alpha.types.UserEventInlineSource): - Required. The Inline source for the input - content for UserEvents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2alpha.types.GcsSource): - Required. Google Cloud Storage location for - the input content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): - Required. BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - user_event_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='UserEventInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class CompletionDataInputConfig(proto.Message): - r"""The input config source for completion data. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): - Required. BigQuery input source. - Add the IAM permission "BigQuery Data Viewer" - for - cloud-retail-customer-data-access@system.gserviceaccount.com - before using this feature otherwise an error is - thrown. - - This field is a member of `oneof`_ ``source``. - """ - - big_query_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='BigQuerySource', - ) - - -class ImportMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - request_id (str): - Deprecated. This field is never set. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=3, - ) - failure_count = proto.Field( - proto.INT64, - number=4, - ) - request_id = proto.Field( - proto.STRING, - number=5, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=6, - ) - - -class ImportProductsResponse(proto.Message): - r"""Response of the - [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. - If the long running operation is done, then this message is returned - by the google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - import_summary (google.cloud.retail_v2alpha.types.UserEventImportSummary): - Aggregated statistics of user event import - status. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - import_summary = proto.Field( - proto.MESSAGE, - number=3, - message='UserEventImportSummary', - ) - - -class UserEventImportSummary(proto.Message): - r"""A summary of import result. The UserEventImportSummary - summarizes the import status for user events. - - Attributes: - joined_events_count (int): - Count of user events imported with complete - existing catalog information. - unjoined_events_count (int): - Count of user events imported, but with - catalog information not found in the imported - catalog. - """ - - joined_events_count = proto.Field( - proto.INT64, - number=1, - ) - unjoined_events_count = proto.Field( - proto.INT64, - number=2, - ) - - -class ImportCompletionDataResponse(proto.Message): - r"""Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. - 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 (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py deleted file mode 100644 index 51233cae..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import user_event as gcr_user_event -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'PredictRequest', - 'PredictResponse', - }, -) - - -class PredictRequest(proto.Message): - r"""Request message for Predict method. - - Attributes: - placement (str): - Required. Full resource name of the format: - {name=projects/*/locations/global/catalogs/default_catalog/placements/*} - The ID of the Recommendations AI placement. Before you can - request predictions from your model, you must create at - least one placement for it. For more information, see - `Managing - placements `__. - - The full list of available placements can be seen at - https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements - user_event (google.cloud.retail_v2alpha.types.UserEvent): - Required. Context about the user, what they - are looking at and what action they took to - trigger the predict request. Note that this user - event detail won't be ingested to userEvent - logs. Thus, a separate userEvent write request - is required for event logging. - page_size (int): - Maximum number of results to return per page. - Set this property to the number of prediction - results needed. If zero, the service will choose - a reasonable default. The maximum allowed value - is 100. Values above 100 will be coerced to 100. - page_token (str): - The previous PredictResponse.next_page_token. - filter (str): - Filter for restricting prediction results with a length - limit of 5,000 characters. Accepts values for tags and the - ``filterOutOfStockItems`` flag. - - - Tag expressions. Restricts predictions to products that - match all of the specified tags. Boolean operators ``OR`` - and ``NOT`` are supported if the expression is enclosed - in parentheses, and must be separated from the tag values - by a space. ``-"tagA"`` is also supported and is - equivalent to ``NOT "tagA"``. Tag values must be double - quoted UTF-8 encoded strings with a size limit of 1,000 - characters. - - Note: "Recently viewed" models don't support tag - filtering at the moment. - - - filterOutOfStockItems. Restricts predictions to products - that do not have a stockState value of OUT_OF_STOCK. - - Examples: - - - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT - "promotional") - - filterOutOfStockItems tag=(-"promotional") - - filterOutOfStockItems - - If your filter blocks all prediction results, the API will - return generic (unfiltered) popular products. If you only - want results strictly matching the filters, set - ``strictFiltering`` to True in ``PredictRequest.params`` to - receive empty results instead. Note that the API will never - return items with storageStatus of "EXPIRED" or "DELETED" - regardless of filter choices. - validate_only (bool): - Use validate only mode for this prediction - query. If set to true, a dummy model will be - used that returns arbitrary products. Note that - the validate only mode should only be used for - testing the API, or if the model is not ready. - params (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional domain specific parameters for the predictions. - - Allowed values: - - - ``returnProduct``: Boolean. If set to true, the - associated product object will be returned in the - ``results.metadata`` field in the prediction response. - - ``returnScore``: Boolean. If set to true, the prediction - 'score' corresponding to each returned product will be - set in the ``results.metadata`` field in the prediction - response. The given 'score' indicates the probability of - an product being clicked/purchased given the user's - context and history. - - ``strictFiltering``: Boolean. True by default. If set to - false, the service will return generic (unfiltered) - popular products instead of empty if your filter blocks - all prediction results. - - ``priceRerankLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of - {'no-price-reranking', 'low-price-reranking', - 'medium-price-reranking', 'high-price-reranking'}. This - gives request-level control and adjusts prediction - results based on product price. - - ``diversityLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of {'no-diversity', - 'low-diversity', 'medium-diversity', 'high-diversity', - 'auto-diversity'}. This gives request-level control and - adjusts prediction results based on product category. - labels (Mapping[str, str]): - The labels applied to a resource must meet the following - requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters, and cannot be empty. Values can - be empty, and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - """ - - placement = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - validate_only = proto.Field( - proto.BOOL, - number=6, - ) - params = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class PredictResponse(proto.Message): - r"""Response message for predict method. - - Attributes: - results (Sequence[google.cloud.retail_v2alpha.types.PredictResponse.PredictionResult]): - A list of recommended products. The order - represents the ranking (from the most relevant - product to the least). - attribution_token (str): - A unique attribution token. This should be included in the - [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs - resulting from this recommendation, which enables accurate - attribution of recommendation model performance. - missing_ids (Sequence[str]): - IDs of products in the request that were - missing from the inventory. - validate_only (bool): - True if the validateOnly property was set in - the request. - """ - - class PredictionResult(proto.Message): - r"""PredictionResult represents the recommendation prediction - results. - - Attributes: - id (str): - ID of the recommended product - metadata (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional product metadata / annotations. - - Possible values: - - - ``product``: JSON representation of the product. Will be - set if ``returnProduct`` is set to true in - ``PredictRequest.params``. - - ``score``: Prediction score in double value. Will be set - if ``returnScore`` is set to true in - ``PredictRequest.params``. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - metadata = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=PredictionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - missing_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py deleted file mode 100644 index 492a51ff..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py +++ /dev/null @@ -1,705 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'Product', - }, -) - - -class Product(proto.Message): - r"""Product captures all metadata information of items to be - recommended or searched. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this product becomes unavailable for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - If it is set, the - [Product][google.cloud.retail.v2alpha.Product] is not - available for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - after - [expire_time][google.cloud.retail.v2alpha.Product.expire_time]. - However, the product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - [expire_time][google.cloud.retail.v2alpha.Product.expire_time] - must be later than - [available_time][google.cloud.retail.v2alpha.Product.available_time] - and - [publish_time][google.cloud.retail.v2alpha.Product.publish_time], - otherwise an INVALID_ARGUMENT error is thrown. - - Corresponding properties: Google Merchant Center property - `expiration_date `__. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Input only. The TTL (time to live) of the product. - - If it is set, it must be a non-negative value, and - [expire_time][google.cloud.retail.v2alpha.Product.expire_time] - is set as current timestamp plus - [ttl][google.cloud.retail.v2alpha.Product.ttl]. The derived - [expire_time][google.cloud.retail.v2alpha.Product.expire_time] - is returned in the output and - [ttl][google.cloud.retail.v2alpha.Product.ttl] is left blank - when retrieving the - [Product][google.cloud.retail.v2alpha.Product]. - - If it is set, the product is not available for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - after current timestamp plus - [ttl][google.cloud.retail.v2alpha.Product.ttl]. However, the - product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This field is a member of `oneof`_ ``expiration``. - name (str): - Immutable. Full resource name of the product, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. - id (str): - Immutable. [Product][google.cloud.retail.v2alpha.Product] - identifier, which is the final component of - [name][google.cloud.retail.v2alpha.Product.name]. For - example, this field is "id_1", if - [name][google.cloud.retail.v2alpha.Product.name] is - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `id `__. - Schema.org property - `Product.sku `__. - type_ (google.cloud.retail_v2alpha.types.Product.Type): - Immutable. The type of the product. Default to - [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2alpha.ProductLevelConfig.ingestion_product_type] - if unset. - primary_product_id (str): - Variant group identifier. Must be an - [id][google.cloud.retail.v2alpha.Product.id], with the same - parent branch with this product. Otherwise, an error is - thrown. - - For - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]s, this field - can only be empty or set to the same value as - [id][google.cloud.retail.v2alpha.Product.id]. - - For VARIANT [Product][google.cloud.retail.v2alpha.Product]s, - this field cannot be empty. A maximum of 2,000 products are - allowed to share the same - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]. Otherwise, - an INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `item_group_id `__. - Schema.org property - `Product.inProductGroupWithID `__. - collection_member_ids (Sequence[str]): - The [id][google.cloud.retail.v2alpha.Product.id] of the - collection members when - [type][google.cloud.retail.v2alpha.Product.type] is - [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION]. - - Non-existent product ids are allowed. The - [type][google.cloud.retail.v2alpha.Product.type] of the - members must be either - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - or - [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - otherwise and INVALID_ARGUMENT error is thrown. Should not - set it for other types. A maximum of 1000 values are - allowed. Otherwise, an INVALID_ARGUMENT error is return. - gtin (str): - The Global Trade Item Number (GTIN) of the product. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This field must be a Unigram. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `gtin `__. - Schema.org property - `Product.isbn `__, - `Product.gtin8 `__, - `Product.gtin12 `__, - `Product.gtin13 `__, or - `Product.gtin14 `__. - - If the value is not a valid GTIN, an INVALID_ARGUMENT error - is returned. - categories (Sequence[str]): - Product categories. This field is repeated for supporting - one product belonging to several parallel categories. - Strongly recommended using the full path for better search / - recommendation quality. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - For example, if a shoes product belongs to both ["Shoes & - Accessories" -> "Shoes"] and ["Sports & Fitness" -> - "Athletic Clothing" -> "Shoes"], it could be represented as: - - :: - - "categories": [ - "Shoes & Accessories > Shoes", - "Sports & Fitness > Athletic Clothing > Shoes" - ] - - Must be set for - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] otherwise an - INVALID_ARGUMENT error is returned. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. Empty values - are not allowed. Each value must be a UTF-8 encoded string - with a length limit of 5,000 characters. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `google_product_category `__. - Schema.org property [Product.category] - (https://schema.org/category). - title (str): - Required. Product title. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `title `__. - Schema.org property - `Product.name `__. - brands (Sequence[str]): - The brands of the product. - - A maximum of 30 brands are allowed. Each brand must be a - UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `brand `__. - Schema.org property - `Product.brand `__. - description (str): - Product description. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `description `__. - Schema.org property - `Product.description `__. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. - - For product prediction, this field is ignored and the model - automatically detects the text language. The - [Product][google.cloud.retail.v2alpha.Product] can include - text in different languages, but duplicating - [Product][google.cloud.retail.v2alpha.Product]s to provide - text in multiple languages can result in degraded model - performance. - - For product search this field is in use. It defaults to - "en-US" if unset. - attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): - Highly encouraged. Extra product attributes to be included. - For example, for products, this could include the store - name, vendor, style, color, etc. These are very strong - signals for recommendation model, thus we highly recommend - providing the attributes here. - - Features that can take on one of a limited number of - possible values. Two types of features can be set are: - - Textual features. some examples would be the brand/maker of - a product, or country of a customer. Numerical features. - Some examples would be the height/weight of a product, or - age of a customer. - - For example: - ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - Max entries count: 200. - - The key must be a UTF-8 encoded string with a length - limit of 128 characters. - - For indexable attribute, the key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, - ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a - non-empty UTF-8 encoded string with a length limit of 256 - characters. - - For number attributes, at most 400 values are allowed. - tags (Sequence[str]): - Custom tags associated with the product. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. This value - must be a UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This tag can be used for filtering recommendation results by - passing the tag as part of the - [PredictRequest.filter][google.cloud.retail.v2alpha.PredictRequest.filter]. - - Corresponding properties: Google Merchant Center property - `custom_label_0–4 `__. - price_info (google.cloud.retail_v2alpha.types.PriceInfo): - Product price and cost information. - - Corresponding properties: Google Merchant Center property - `price `__. - rating (google.cloud.retail_v2alpha.types.Rating): - The rating of this product. - available_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this - [Product][google.cloud.retail.v2alpha.Product] becomes - available for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - availability (google.cloud.retail_v2alpha.types.Product.Availability): - The online availability of the - [Product][google.cloud.retail.v2alpha.Product]. Default to - [Availability.IN_STOCK][google.cloud.retail.v2alpha.Product.Availability.IN_STOCK]. - - Corresponding properties: Google Merchant Center property - `availability `__. - Schema.org property - `Offer.availability `__. - available_quantity (google.protobuf.wrappers_pb2.Int32Value): - The available quantity of the item. - fulfillment_info (Sequence[google.cloud.retail_v2alpha.types.FulfillmentInfo]): - Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - All the elements must have distinct - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type]. - Otherwise, an INVALID_ARGUMENT error is returned. - uri (str): - Canonical URL directly linking to the product detail page. - - It is strongly recommended to provide a valid uri for the - product, otherwise the service performance could be - significantly degraded. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `link `__. - Schema.org property `Offer.url `__. - images (Sequence[google.cloud.retail_v2alpha.types.Image]): - Product images for the product. We highly recommend putting - the main image first. - - A maximum of 300 images are allowed. - - Corresponding properties: Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - audience (google.cloud.retail_v2alpha.types.Audience): - The target group associated with a given - audience (e.g. male, veterans, car owners, - musicians, etc.) of the product. - color_info (google.cloud.retail_v2alpha.types.ColorInfo): - The color of the product. - - Corresponding properties: Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - sizes (Sequence[str]): - The size of the product. To represent different size systems - or size types, consider using this format: - [[[size_system:]size_type:]size_value]. - - For example, in "US:MENS:M", "US" represents size system; - "MENS" represents size type; "M" represents size value. In - "GIRLS:27", size system is empty; "GIRLS" represents size - type; "27" represents size value. In "32 inches", both size - system and size type are empty, while size value is "32 - inches". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `size `__, - `size_type `__, - and - `size_system `__. - Schema.org property - `Product.size `__. - materials (Sequence[str]): - The material of the product. For example, "leather", - "wooden". - - A maximum of 20 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 200 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `material `__. - Schema.org property - `Product.material `__. - patterns (Sequence[str]): - The pattern or graphic print of the product. For example, - "striped", "polka dot", "paisley". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `pattern `__. - Schema.org property - `Product.pattern `__. - conditions (Sequence[str]): - The condition of the product. Strongly encouraged to use the - standard values: "new", "refurbished", "used". - - A maximum of 1 value is allowed per - [Product][google.cloud.retail.v2alpha.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `condition `__. - Schema.org property - `Offer.itemCondition `__. - promotions (Sequence[google.cloud.retail_v2alpha.types.Promotion]): - The promotions applied to the product. A maximum of 10 - values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. Only - [Promotion.promotion_id][google.cloud.retail.v2alpha.Promotion.promotion_id] - will be used, other fields will be ignored if set. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the product is published by the retailer - for the first time, which indicates the freshness of the - products. Note that this field is different from - [available_time][google.cloud.retail.v2alpha.Product.available_time], - given it purely describes product freshness regardless of - when it is available on search and recommendation. - retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the - [Product][google.cloud.retail.v2alpha.Product]s are returned - in - [SearchResponse][google.cloud.retail.v2alpha.SearchResponse]. - - Supported fields for all - [type][google.cloud.retail.v2alpha.Product.type]s: - - - [audience][google.cloud.retail.v2alpha.Product.audience] - - [availability][google.cloud.retail.v2alpha.Product.availability] - - [brands][google.cloud.retail.v2alpha.Product.brands] - - [color_info][google.cloud.retail.v2alpha.Product.color_info] - - [conditions][google.cloud.retail.v2alpha.Product.conditions] - - [gtin][google.cloud.retail.v2alpha.Product.gtin] - - [materials][google.cloud.retail.v2alpha.Product.materials] - - [name][google.cloud.retail.v2alpha.Product.name] - - [patterns][google.cloud.retail.v2alpha.Product.patterns] - - [price_info][google.cloud.retail.v2alpha.Product.price_info] - - [rating][google.cloud.retail.v2alpha.Product.rating] - - [sizes][google.cloud.retail.v2alpha.Product.sizes] - - [title][google.cloud.retail.v2alpha.Product.title] - - [uri][google.cloud.retail.v2alpha.Product.uri] - - Supported fields only for - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION]: - - - [categories][google.cloud.retail.v2alpha.Product.categories] - - [description][google.cloud.retail.v2alpha.Product.description] - - [images][google.cloud.retail.v2alpha.Product.images] - - Supported fields only for - [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT]: - - - Only the first image in - [images][google.cloud.retail.v2alpha.Product.images] - - To mark - [attributes][google.cloud.retail.v2alpha.Product.attributes] - as retrievable, include paths of the form "attributes.key" - where "key" is the key of a custom attribute, as specified - in - [attributes][google.cloud.retail.v2alpha.Product.attributes]. - - For - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION], - the following fields are always returned in - [SearchResponse][google.cloud.retail.v2alpha.SearchResponse] - by default: - - - [name][google.cloud.retail.v2alpha.Product.name] - - For - [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT], - the following fields are always returned in by default: - - - [name][google.cloud.retail.v2alpha.Product.name] - - [color_info][google.cloud.retail.v2alpha.Product.color_info] - - Maximum number of paths is 30. Otherwise, an - INVALID_ARGUMENT error is returned. - - Note: Returning more fields in - [SearchResponse][google.cloud.retail.v2alpha.SearchResponse] - may increase response payload size and serving latency. - variants (Sequence[google.cloud.retail_v2alpha.types.Product]): - Output only. Product variants grouped together on primary - product which share similar product attributes. It's - automatically grouped by - [primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] - for all the product variants. Only populated for - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct]. - Do not set this field in API requests. - """ - class Type(proto.Enum): - r"""The type of this product.""" - TYPE_UNSPECIFIED = 0 - PRIMARY = 1 - VARIANT = 2 - COLLECTION = 3 - - class Availability(proto.Enum): - r"""Product availability. If this field is unspecified, the - product is assumed to be in stock. - """ - AVAILABILITY_UNSPECIFIED = 0 - IN_STOCK = 1 - OUT_OF_STOCK = 2 - PREORDER = 3 - BACKORDER = 4 - - expire_time = proto.Field( - proto.MESSAGE, - number=16, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl = proto.Field( - proto.MESSAGE, - number=17, - oneof='expiration', - message=duration_pb2.Duration, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - type_ = proto.Field( - proto.ENUM, - number=3, - enum=Type, - ) - primary_product_id = proto.Field( - proto.STRING, - number=4, - ) - collection_member_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - gtin = proto.Field( - proto.STRING, - number=6, - ) - categories = proto.RepeatedField( - proto.STRING, - number=7, - ) - title = proto.Field( - proto.STRING, - number=8, - ) - brands = proto.RepeatedField( - proto.STRING, - number=9, - ) - description = proto.Field( - proto.STRING, - number=10, - ) - language_code = proto.Field( - proto.STRING, - number=11, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=12, - message=common.CustomAttribute, - ) - tags = proto.RepeatedField( - proto.STRING, - number=13, - ) - price_info = proto.Field( - proto.MESSAGE, - number=14, - message=common.PriceInfo, - ) - rating = proto.Field( - proto.MESSAGE, - number=15, - message=common.Rating, - ) - available_time = proto.Field( - proto.MESSAGE, - number=18, - message=timestamp_pb2.Timestamp, - ) - availability = proto.Field( - proto.ENUM, - number=19, - enum=Availability, - ) - available_quantity = proto.Field( - proto.MESSAGE, - number=20, - message=wrappers_pb2.Int32Value, - ) - fulfillment_info = proto.RepeatedField( - proto.MESSAGE, - number=21, - message=common.FulfillmentInfo, - ) - uri = proto.Field( - proto.STRING, - number=22, - ) - images = proto.RepeatedField( - proto.MESSAGE, - number=23, - message=common.Image, - ) - audience = proto.Field( - proto.MESSAGE, - number=24, - message=common.Audience, - ) - color_info = proto.Field( - proto.MESSAGE, - number=25, - message=common.ColorInfo, - ) - sizes = proto.RepeatedField( - proto.STRING, - number=26, - ) - materials = proto.RepeatedField( - proto.STRING, - number=27, - ) - patterns = proto.RepeatedField( - proto.STRING, - number=28, - ) - conditions = proto.RepeatedField( - proto.STRING, - number=29, - ) - promotions = proto.RepeatedField( - proto.MESSAGE, - number=34, - message=promotion.Promotion, - ) - publish_time = proto.Field( - proto.MESSAGE, - number=33, - message=timestamp_pb2.Timestamp, - ) - retrievable_fields = proto.Field( - proto.MESSAGE, - number=30, - message=field_mask_pb2.FieldMask, - ) - variants = proto.RepeatedField( - proto.MESSAGE, - number=31, - message='Product', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py deleted file mode 100644 index ddfc08ed..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py +++ /dev/null @@ -1,877 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'CreateProductRequest', - 'GetProductRequest', - 'UpdateProductRequest', - 'DeleteProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'SetInventoryRequest', - 'SetInventoryMetadata', - 'SetInventoryResponse', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesResponse', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesResponse', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesResponse', - }, -) - - -class CreateProductRequest(proto.Message): - r"""Request message for [CreateProduct][] method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - product (google.cloud.retail_v2alpha.types.Product): - Required. The [Product][google.cloud.retail.v2alpha.Product] - to create. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2alpha.Product], which will - become the final component of the - [Product.name][google.cloud.retail.v2alpha.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2alpha.Product]s with the - same - [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - product_id = proto.Field( - proto.STRING, - number=3, - ) - - -class GetProductRequest(proto.Message): - r"""Request message for [GetProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested - [Product][google.cloud.retail.v2alpha.Product] does not - exist, a NOT_FOUND error is returned. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateProductRequest(proto.Message): - r"""Request message for [UpdateProduct][] method. - - Attributes: - product (google.cloud.retail_v2alpha.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Product][google.cloud.retail.v2alpha.Product] to update. - The immutable and output only fields are NOT supported. If - not set, all supported fields (the fields that are neither - immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - a new [Product][google.cloud.retail.v2alpha.Product] will be - created. In this situation, ``update_mask`` is ignored. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteProductRequest(proto.Message): - r"""Request message for [DeleteProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2alpha.Product] to delete - can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] with more - than one - [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2alpha.Product] will be - deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProductsRequest(proto.Message): - r"""Request message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - - Attributes: - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list products - under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2alpha.Product]s under this - branch, regardless of whether or not this branch exists, a - PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of - [Product][google.cloud.retail.v2alpha.Product]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 - [ListProductsResponse.next_page_token][google.cloud.retail.v2alpha.ListProductsResponse.next_page_token], - received from a previous - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - filter (str): - A filter to apply on the list results. Supported features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2alpha.ListProductsRequest.filter] - is unset. - - List - [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s sharing - the same - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]. For - example: ``primary_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2alpha.Product]s - bundled in a - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product]. For - example: ``collection_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2alpha.Product]s with - a partibular type. For example: ``type = "PRIMARY"`` - ``type = "VARIANT"`` ``type = "COLLECTION"`` - - If the field is unrecognizable, an INVALID_ARGUMENT error is - returned. - - If the specified - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] or - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product] does not - exist, a NOT_FOUND error is returned. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields of [Product][google.cloud.retail.v2alpha.Product] - to return in the responses. If not set or empty, the - following fields are returned: - - - [Product.name][google.cloud.retail.v2alpha.Product.name] - - [Product.id][google.cloud.retail.v2alpha.Product.id] - - [Product.title][google.cloud.retail.v2alpha.Product.title] - - [Product.uri][google.cloud.retail.v2alpha.Product.uri] - - [Product.images][google.cloud.retail.v2alpha.Product.images] - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.brands][google.cloud.retail.v2alpha.Product.brands] - - If "*" is provided, all fields are returned. - [Product.name][google.cloud.retail.v2alpha.Product.name] is - always returned no matter what mask is set. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - require_total_size (bool): - If true and - [page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] - is empty, - [ListProductsResponse.total_size][google.cloud.retail.v2alpha.ListProductsResponse.total_size] - is set to the total count of matched items irrespective of - pagination. - - Notice that setting this field to true affects the - performance. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - require_total_size = proto.Field( - proto.BOOL, - number=6, - ) - - -class ListProductsResponse(proto.Message): - r"""Response message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - - Attributes: - products (Sequence[google.cloud.retail_v2alpha.types.Product]): - The [Product][google.cloud.retail.v2alpha.Product]s. - next_page_token (str): - A token that can be sent as - [ListProductsRequest.page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - total_size (int): - The total count of matched - [Product][google.cloud.retail.v2alpha.Product]s irrespective - of pagination. The total number of - [Product][google.cloud.retail.v2alpha.Product]s returned by - pagination may be less than the - [total_size][google.cloud.retail.v2alpha.ListProductsResponse.total_size] - that matches. - - This field is ignored if - [ListProductsRequest.require_total_size][google.cloud.retail.v2alpha.ListProductsRequest.require_total_size] - is not set or - [ListProductsRequest.page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] - is not empty. - """ - - @property - def raw_page(self): - return self - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - - -class SetInventoryRequest(proto.Message): - r"""Request message for [SetInventory][] method. - - Attributes: - inventory (google.cloud.retail_v2alpha.types.Product): - Required. The inventory information to update. The allowable - fields to update are: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product] named in - [Product.name][google.cloud.retail.v2alpha.Product.name], - regardless of whether or not it exists, a PERMISSION_DENIED - error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting the - last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of fulfillment - types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear in - [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types have - empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following inventory - fields: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - - If a full overwrite of inventory information while ignoring - timestamps is needed, [UpdateProduct][] should be invoked - instead. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2alpha.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the request is issued, used to - prevent out-of-order updates on inventory fields - with the last update time recorded. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] with name - [Product.name][google.cloud.retail.v2alpha.Product.name] is - not found, the inventory update will still be processed and - retained for at most 1 day until the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - inventory = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - set_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - set_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=4, - ) - - -class SetInventoryMetadata(proto.Message): - r"""Metadata related to the progress of the SetInventory operation. - Currently empty because there is no meaningful metadata populated - from the [SetInventory][] method. - - """ - - -class SetInventoryResponse(proto.Message): - r"""Response of the SetInventoryRequest. Currently empty because there - is no meaningful response populated from the [SetInventory][] - method. - - """ - - -class AddFulfillmentPlacesRequest(proto.Message): - r"""Request message for [AddFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery" to be added for this - [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type]. - Duplicate IDs will be automatically ignored. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If the total number of place IDs exceeds 2000 for this - [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type] - after adding, then the update will be rejected. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - the fulfillment information will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - add_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class AddFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the AddFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [AddFulfillmentPlaces][] method. - - """ - - -class AddFulfillmentPlacesResponse(proto.Message): - r"""Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - - -class AddLocalInventoriesRequest(proto.Message): - r"""Request message for [AddLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - local_inventories (Sequence[google.cloud.retail_v2alpha.types.LocalInventory]): - Required. A list of inventory information at - difference places. Each place is identified by - its place ID. At most 3000 inventories are - allowed per request. - add_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided list of - [LocalInventory][google.cloud.retail.v2alpha.LocalInventory] - to update. The field is updated to the provided value. - - If a field is set while the place does not have a previous - local inventory, the local inventory at that store is - created. - - If a field is set while the value of that field is not - provided, the original field value, if it exists, is - deleted. - - If the mask is not set or set with empty paths, all - inventory fields will be updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory updates are - issued. Used to prevent out-of-order updates on - local inventory fields. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - the local inventory will still be processed and retained for - at most 1 day and processed once the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - local_inventories = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.LocalInventory, - ) - add_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - add_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=6, - ) - - -class AddLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the AddLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [AddLocalInventories][] method. - - """ - - -class AddLocalInventoriesResponse(proto.Message): - r"""Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesRequest(proto.Message): - r"""Request message for [RemoveLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - place_ids (Sequence[str]): - Required. A list of place IDs to have their - inventory deleted. At most 3000 place IDs are - allowed per request. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory deletions are - issued. Used to prevent out-of-order updates and - deletions on local inventory fields. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - the local inventory removal request will still be processed - and retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class RemoveLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesResponse(proto.Message): - r"""Response of the [RemoveLocalInventories][] API. Currently empty - because there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - - -class RemoveFulfillmentPlacesRequest(proto.Message): - r"""Request message for [RemoveFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery", to be removed for this - [type][google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type]. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - the fulfillment information will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class RemoveFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveFulfillmentPlaces][] method. - - """ - - -class RemoveFulfillmentPlacesResponse(proto.Message): - r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty - because there is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py deleted file mode 100644 index bd5b8a58..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'Promotion', - }, -) - - -class Promotion(proto.Message): - r"""Promotion information. - - Attributes: - promotion_id (str): - ID of the promotion. For example, "free gift". - - The value must be a UTF-8 encoded string with a length limit - of 128 characters, and match the pattern: - ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or - ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is - returned. - - Google Merchant Center property - `promotion `__. - """ - - promotion_id = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py deleted file mode 100644 index ad7ff6f6..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py +++ /dev/null @@ -1,251 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'PurgeMetadata', - 'PurgeProductsMetadata', - 'PurgeProductsRequest', - 'PurgeProductsResponse', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - }, -) - - -class PurgeMetadata(proto.Message): - r"""Metadata related to the progress of the Purge operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - """ - - -class PurgeProductsMetadata(proto.Message): - r"""Metadata related to the progress of the PurgeProducts - operation. This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were deleted - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=3, - ) - failure_count = proto.Field( - proto.INT64, - number=4, - ) - - -class PurgeProductsRequest(proto.Message): - r"""Request message for PurgeProducts method. - - Attributes: - parent (str): - Required. The resource name of the branch under which the - products are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}/branches/${branchId}`` - filter (str): - Required. The filter string to specify the products to be - deleted with a length limit of 5,000 characters. - - Empty string filter is not allowed. "*" implies delete all - items in a branch. - - The eligible fields for filtering are: - - - ``availability``: Double quoted - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - string. - - ``create_time`` : in ISO 8601 "zulu" format. - - Supported syntax: - - - Comparators (">", "<", ">=", "<=", "="). Examples: - - - create_time <= "2015-02-13T17:05:46Z" - - availability = "IN_STOCK" - - - Conjunctions ("AND") Examples: - - - create_time <= "2015-02-13T17:05:46Z" AND availability - = "PREORDER" - - - Disjunctions ("OR") Examples: - - - create_time <= "2015-02-13T17:05:46Z" OR availability - = "IN_STOCK" - - - Can support nested queries. Examples: - - - (create_time <= "2015-02-13T17:05:46Z" AND - availability = "PREORDER") OR (create_time >= - "2015-02-14T13:03:32Z" AND availability = "IN_STOCK") - - - Filter Limits: - - - Filter should not contain more than 6 conditions. - - Max nesting depth should not exceed 2 levels. - - Examples queries: - - - Delete back order products created before a timestamp. - create_time <= "2015-02-13T17:05:46Z" OR availability = - "BACKORDER". - force (bool): - Actually perform the purge. If ``force`` is set to false, - the method will return the expected purge count without - deleting any products. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeProductsResponse(proto.Message): - r"""Response of the PurgeProductsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purge_count (int): - The total count of products purged as a - result of the operation. - purge_sample (Sequence[str]): - A sample of the product names that will be deleted. Only - populated if ``force`` is set to false. A max of 100 names - will be returned and the names are chosen at random. - """ - - purge_count = proto.Field( - proto.INT64, - number=1, - ) - purge_sample = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class PurgeUserEventsRequest(proto.Message): - r"""Request message for PurgeUserEvents method. - - Attributes: - parent (str): - Required. The resource name of the catalog under which the - events are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}`` - filter (str): - Required. The filter string to specify the events to be - deleted with a length limit of 5,000 characters. Empty - string filter is not allowed. The eligible fields for - filtering are: - - - ``eventType``: Double quoted - [UserEvent.event_type][google.cloud.retail.v2alpha.UserEvent.event_type] - string. - - ``eventTime``: in ISO 8601 "zulu" format. - - ``visitorId``: Double quoted string. Specifying this will - delete all events associated with a visitor. - - ``userId``: Double quoted string. Specifying this will - delete all events associated with a user. - - Examples: - - - Deleting all events in a time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - - Deleting specific eventType in time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` - - Deleting all events for a specific visitor: - ``visitorId = "visitor1024"`` - - The filtering fields are assumed to have an implicit AND. - force (bool): - Actually perform the purge. If ``force`` is set to false, - the method will return the expected purge count without - deleting any user events. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeUserEventsResponse(proto.Message): - r"""Response of the PurgeUserEventsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purged_events_count (int): - The total count of events purged as a result - of the operation. - """ - - purged_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py deleted file mode 100644 index e4dc0ba2..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py +++ /dev/null @@ -1,1099 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'SearchRequest', - 'SearchResponse', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - - Attributes: - placement (str): - Required. The resource name of the search engine placement, - such as - ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` - This field is used to identify the serving configuration - name and the set of models that will be used to make the - search. - branch (str): - The branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - - Use "default_branch" as the branch ID or leave this field - empty, to search products under the default branch. - query (str): - Raw search query. - visitor_id (str): - Required. A unique identifier for tracking visitors. For - example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - This should be the same identifier as - [UserEvent.visitor_id][google.cloud.retail.v2alpha.UserEvent.visitor_id]. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2alpha.types.UserInfo): - User information. - page_size (int): - Maximum number of - [Product][google.cloud.retail.v2alpha.Product]s to return. - If unspecified, defaults to a reasonable value. The maximum - allowed value is 120. Values above 120 will be coerced to - 120. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [SearchResponse.next_page_token][google.cloud.retail.v2alpha.SearchResponse.next_page_token], - received from a previous - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - offset (int): - A 0-indexed integer that specifies the current offset (that - is, starting result location, amongst the - [Product][google.cloud.retail.v2alpha.Product]s deemed by - the API as relevant) in search results. This field is only - considered if - [page_token][google.cloud.retail.v2alpha.SearchRequest.page_token] - is unset. - - If this field is negative, an INVALID_ARGUMENT is returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. Filter expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - canonical_filter (str): - The default filter that is applied when a user performs a - search without checking any filters on the search page. - - The filter applied to every search request when quality - improvement such as query expansion is needed. For example, - if a query does not have enough results, an expanded query - with - [SearchRequest.canonical_filter][google.cloud.retail.v2alpha.SearchRequest.canonical_filter] - will be returned as a supplement of the original query. This - field is strongly recommended to achieve high search - quality. - - See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for more details about filter syntax. - order_by (str): - The order in which products are returned. Products can be - ordered by a field in an - [Product][google.cloud.retail.v2alpha.Product] object. Leave - it unset if ordered by relevance. OrderBy expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - facet_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec]): - Facet specifications for faceted search. If empty, no facets - are returned. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - dynamic_facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec): - Deprecated. Refer to - https://cloud.google.com/retail/docs/configs#dynamic - to enable dynamic facets. Do not set this field. - The specification for dynamically generated - facets. Notice that only textual facets can be - dynamically generated. - boost_spec (google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec): - Boost specification to boost certain products. See more - details at this `user - guide `__. - - Notice that if both - [ServingConfig.boost_control_ids][google.cloud.retail.v2alpha.ServingConfig.boost_control_ids] - and [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. - query_expansion_spec (google.cloud.retail_v2alpha.types.SearchRequest.QueryExpansionSpec): - The query expansion specification that specifies the - conditions under which query expansion will occur. See more - details at this `user - guide `__. - relevance_threshold (google.cloud.retail_v2alpha.types.SearchRequest.RelevanceThreshold): - The relevance threshold of the search results. - - Defaults to - [RelevanceThreshold.HIGH][google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH], - which means only the most relevant results are shown, and - the least number of results are returned. See more details - at this `user - guide `__. - variant_rollup_keys (Sequence[str]): - The keys to fetch and rollup the matching - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s attributes, - [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo] - or - [LocalInventory][google.cloud.retail.v2alpha.LocalInventory]s - attributes. The attributes from all the matching - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s or - [LocalInventory][google.cloud.retail.v2alpha.LocalInventory]s - are merged and de-duplicated. Notice that rollup attributes - will lead to extra query latency. Maximum number of keys is - 30. - - For - [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], - a fulfillment type and a fulfillment ID must be provided in - the format of "fulfillmentType.fulfillmentId". E.g., in - "pickupInStore.store123", "pickupInStore" is fulfillment - type and "store123" is the store ID. - - Supported keys are: - - - colorFamilies - - price - - originalPrice - - discount - - variantId - - inventory(place_id,price) - - inventory(place_id,original_price) - - inventory(place_id,attributes.key), where key is any key - in the [Product.inventories.attributes][] map. - - attributes.key, where key is any key in the - [Product.attributes][google.cloud.retail.v2alpha.Product.attributes] - map. - - pickupInStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "pickup-in-store". - - shipToStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "ship-to-store". - - sameDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "same-day-delivery". - - nextDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "next-day-delivery". - - customFulfillment1.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-1". - - customFulfillment2.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-2". - - customFulfillment3.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-3". - - customFulfillment4.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-4". - - customFulfillment5.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-5". - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. Required for - category navigation queries to achieve good search quality. - The format should be the same as - [UserEvent.page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories]; - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - search_mode (google.cloud.retail_v2alpha.types.SearchRequest.SearchMode): - The search mode of the search request. If not - specified, a single search request triggers both - product search and faceted search. - personalization_spec (google.cloud.retail_v2alpha.types.SearchRequest.PersonalizationSpec): - The specification for personalization. - """ - class RelevanceThreshold(proto.Enum): - r"""The relevance threshold of the search results. The higher - relevance threshold is, the higher relevant results are shown - and the less number of results are returned. - """ - RELEVANCE_THRESHOLD_UNSPECIFIED = 0 - HIGH = 1 - MEDIUM = 2 - LOW = 3 - LOWEST = 4 - - class SearchMode(proto.Enum): - r"""The search mode of each search request.""" - SEARCH_MODE_UNSPECIFIED = 0 - PRODUCT_SEARCH_ONLY = 1 - FACETED_SEARCH_ONLY = 2 - - class FacetSpec(proto.Message): - r"""A facet specification to perform faceted search. - - Attributes: - facet_key (google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec.FacetKey): - Required. The facet key specification. - limit (int): - Maximum of facet values that should be returned for this - facet. If unspecified, defaults to 20. The maximum allowed - value is 300. Values above 300 will be coerced to 300. - - If this field is negative, an INVALID_ARGUMENT is returned. - excluded_filter_keys (Sequence[str]): - List of keys to exclude when faceting. - - By default, - [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] - is not excluded from the filter unless it is listed in this - field. - - For example, suppose there are 100 products with color facet - "Red" and 200 products with color facet "Blue". A query - containing the filter "colorFamilies:ANY("Red")" and have - "colorFamilies" as - [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] - will by default return the "Red" with count 100. - - If this field contains "colorFamilies", then the query - returns both the "Red" with count 100 and "Blue" with count - 200, because the "colorFamilies" key is now excluded from - the filter. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - enable_dynamic_position (bool): - Enables dynamic position for this facet. If set to true, the - position of this facet among all facets in the response is - determined by Google Retail Search. It will be ordered - together with dynamic facets if dynamic facets is enabled. - If set to false, the position of this facet in the response - will be the same as in the request, and it will be ranked - before the facets with dynamic position enable and all - dynamic facets. - - For example, you may always want to have rating facet - returned in the response, but it's not necessarily to always - display the rating facet at the top. In that case, you can - set enable_dynamic_position to true so that the position of - rating facet in response will be determined by Google Retail - Search. - - Another example, assuming you have the following facets in - the request: - - - "rating", enable_dynamic_position = true - - - "price", enable_dynamic_position = false - - - "brands", enable_dynamic_position = false - - And also you have a dynamic facets enable, which will - generate a facet 'gender'. Then the final order of the - facets in the response can be ("price", "brands", "rating", - "gender") or ("price", "brands", "gender", "rating") depends - on how Google Retail Search orders "gender" and "rating" - facets. However, notice that "price" and "brands" will - always be ranked at 1st and 2nd position since their - enable_dynamic_position are false. - """ - - class FacetKey(proto.Message): - r"""Specifies how a facet is computed. - - Attributes: - key (str): - Required. Supported textual and numerical facet keys in - [Product][google.cloud.retail.v2alpha.Product] object, over - which the facet values are computed. Facet key is - case-sensitive. - - Allowed facet keys when - [FacetKey.query][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.query] - is not specified: - - - textual_field = - - - "brands" - - "categories" - - "genders" - - "ageGroups" - - "availability" - - "colorFamilies" - - "colors" - - "sizes" - - "materials" - - "patterns" - - "conditions" - - "attributes.key" - - "pickupInStore" - - "shipToStore" - - "sameDayDelivery" - - "nextDayDelivery" - - "customFulfillment1" - - "customFulfillment2" - - "customFulfillment3" - - "customFulfillment4" - - "customFulfillment5" - - "inventory(place_id,attributes.key)" - - - numerical_field = - - - "price" - - "discount" - - "rating" - - "ratingCount" - - "attributes.key" - - "inventory(place_id,price)" - - "inventory(place_id,original_price)" - - "inventory(place_id,attributes.key)". - intervals (Sequence[google.cloud.retail_v2alpha.types.Interval]): - Set only if values should be bucketized into - intervals. Must be set for facets with numerical - values. Must not be set for facet with text - values. Maximum number of intervals is 30. - restricted_values (Sequence[str]): - Only get facet for the given restricted values. For example, - when using "pickupInStore" as key and set restricted values - to ["store123", "store456"], only facets for "store123" and - "store456" are returned. Only supported on textual fields - and fulfillments. Maximum is 20. - - Must be set for the fulfillment facet keys: - - - pickupInStore - - - shipToStore - - - sameDayDelivery - - - nextDayDelivery - - - customFulfillment1 - - - customFulfillment2 - - - customFulfillment3 - - - customFulfillment4 - - - customFulfillment5 - prefixes (Sequence[str]): - Only get facet values that start with the - given string prefix. For example, suppose - "categories" has three values "Women > Shoe", - "Women > Dress" and "Men > Shoe". If set - "prefixes" to "Women", the "categories" facet - will give only "Women > Shoe" and "Women > - Dress". Only supported on textual fields. - Maximum is 10. - contains (Sequence[str]): - Only get facet values that contains the given - strings. For example, suppose "categories" has - three values "Women > Shoe", "Women > Dress" and - "Men > Shoe". If set "contains" to "Shoe", the - "categories" facet will give only "Women > Shoe" - and "Men > Shoe". Only supported on textual - fields. Maximum is 10. - order_by (str): - The order in which [Facet.values][] are returned. - - Allowed values are: - - - "count desc", which means order by - [Facet.FacetValue.count][] descending. - - - "value desc", which means order by - [Facet.FacetValue.value][] descending. Only applies to - textual facets. - - If not set, textual values are sorted in `natural - order `__; - numerical intervals are sorted in the order given by - [FacetSpec.FacetKey.intervals][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.intervals]; - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - are sorted in the order given by - [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.restricted_values]. - query (str): - The query that is used to compute facet for the given facet - key. When provided, it will override the default behavior of - facet computation. The query syntax is the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for detail syntax and limitations. Notice that there is no - limitation on - [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] - when query is specified. - - In the response, [FacetValue.value][] will be always "1" and - [FacetValue.count][] will be the number of results that - matches the query. - - For example, you can set a customized facet for - "shipToStore", where - [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] - is "customizedShipToStore", and - [FacetKey.query][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.query] - is "availability: ANY("IN_STOCK") AND shipToStore: - ANY("123")". Then the facet will count the products that are - both in stock and ship to store "123". - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - intervals = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Interval, - ) - restricted_values = proto.RepeatedField( - proto.STRING, - number=3, - ) - prefixes = proto.RepeatedField( - proto.STRING, - number=8, - ) - contains = proto.RepeatedField( - proto.STRING, - number=9, - ) - order_by = proto.Field( - proto.STRING, - number=4, - ) - query = proto.Field( - proto.STRING, - number=5, - ) - - facet_key = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.FacetSpec.FacetKey', - ) - limit = proto.Field( - proto.INT32, - number=2, - ) - excluded_filter_keys = proto.RepeatedField( - proto.STRING, - number=3, - ) - enable_dynamic_position = proto.Field( - proto.BOOL, - number=4, - ) - - class DynamicFacetSpec(proto.Message): - r"""The specifications of dynamically generated facets. - - Attributes: - mode (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec.Mode): - Mode of the DynamicFacet feature. Defaults to - [Mode.DISABLED][google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec.Mode.DISABLED] - if it's unset. - """ - class Mode(proto.Enum): - r"""Enum to control DynamicFacet mode""" - MODE_UNSPECIFIED = 0 - DISABLED = 1 - ENABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.DynamicFacetSpec.Mode', - ) - - class BoostSpec(proto.Message): - r"""Boost specification to boost certain items. - - Attributes: - condition_boost_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - Condition boost specifications. If a product - matches multiple conditions in the - specifictions, boost scores from these - specifications are all applied and combined in a - non-linear way. Maximum number of specifications - is 10. - skip_boost_spec_validation (bool): - Whether to skip boostspec validation. If this field is set - to true, invalid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] - will be ignored and valid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] - will still be applied. - - This field is a member of `oneof`_ ``_skip_boost_spec_validation``. - """ - - class ConditionBoostSpec(proto.Message): - r"""Boost applies to products which match a condition. - - Attributes: - condition (str): - An expression which specifies a boost condition. The syntax - and supported fields are the same as a filter expression. - See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": - - - (id: ANY("product_1", "product_2")) AND - (colorFamilies: ANY("Red","Blue")) - boost (float): - Strength of the condition boost, which should be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - """ - - condition = proto.Field( - proto.STRING, - number=1, - ) - boost = proto.Field( - proto.FLOAT, - number=2, - ) - - condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - skip_boost_spec_validation = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - - class QueryExpansionSpec(proto.Message): - r"""Specification to determine under which conditions query - expansion should occur. - - Attributes: - condition (google.cloud.retail_v2alpha.types.SearchRequest.QueryExpansionSpec.Condition): - The condition under which query expansion should occur. - Default to - [Condition.DISABLED][google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - pin_unexpanded_results (bool): - Whether to pin unexpanded results. If this - field is set to true, unexpanded products are - always at the top of the search results, - followed by the expanded results. - """ - class Condition(proto.Enum): - r"""Enum describing under which condition query expansion should - occur. - """ - CONDITION_UNSPECIFIED = 0 - DISABLED = 1 - AUTO = 3 - - condition = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.QueryExpansionSpec.Condition', - ) - pin_unexpanded_results = proto.Field( - proto.BOOL, - number=2, - ) - - class PersonalizationSpec(proto.Message): - r"""The specification for personalization. - - Attributes: - mode (google.cloud.retail_v2alpha.types.SearchRequest.PersonalizationSpec.Mode): - Defaults to - [Mode.AUTO][google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""The personalization mode of each search request.""" - MODE_UNSPECIFIED = 0 - AUTO = 1 - DISABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.PersonalizationSpec.Mode', - ) - - placement = proto.Field( - proto.STRING, - number=1, - ) - branch = proto.Field( - proto.STRING, - number=2, - ) - query = proto.Field( - proto.STRING, - number=3, - ) - visitor_id = proto.Field( - proto.STRING, - number=4, - ) - user_info = proto.Field( - proto.MESSAGE, - number=5, - message=common.UserInfo, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - offset = proto.Field( - proto.INT32, - number=9, - ) - filter = proto.Field( - proto.STRING, - number=10, - ) - canonical_filter = proto.Field( - proto.STRING, - number=28, - ) - order_by = proto.Field( - proto.STRING, - number=11, - ) - facet_specs = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=FacetSpec, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=21, - message=DynamicFacetSpec, - ) - boost_spec = proto.Field( - proto.MESSAGE, - number=13, - message=BoostSpec, - ) - query_expansion_spec = proto.Field( - proto.MESSAGE, - number=14, - message=QueryExpansionSpec, - ) - relevance_threshold = proto.Field( - proto.ENUM, - number=15, - enum=RelevanceThreshold, - ) - variant_rollup_keys = proto.RepeatedField( - proto.STRING, - number=17, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=23, - ) - search_mode = proto.Field( - proto.ENUM, - number=31, - enum=SearchMode, - ) - personalization_spec = proto.Field( - proto.MESSAGE, - number=32, - message=PersonalizationSpec, - ) - - -class SearchResponse(proto.Message): - r"""Response message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - - Attributes: - results (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.SearchResult]): - A list of matched items. The order represents - the ranking. - facets (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.Facet]): - Results of facets requested by user. - total_size (int): - The estimated total count of matched items irrespective of - pagination. The count of - [results][google.cloud.retail.v2alpha.SearchResponse.results] - returned by pagination may be less than the - [total_size][google.cloud.retail.v2alpha.SearchResponse.total_size] - that matches. - corrected_query (str): - If spell correction applies, the corrected - query. Otherwise, empty. - attribution_token (str): - A unique search token. This should be included in the - [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs - resulting from this search, which enables accurate - attribution of search model performance. - next_page_token (str): - A token that can be sent as - [SearchRequest.page_token][google.cloud.retail.v2alpha.SearchRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - query_expansion_info (google.cloud.retail_v2alpha.types.SearchResponse.QueryExpansionInfo): - Query expansion information for the returned - results. - redirect_uri (str): - The URI of a customer-defined redirect page. If redirect - action is triggered, no search will be performed, and only - [redirect_uri][google.cloud.retail.v2alpha.SearchResponse.redirect_uri] - and - [attribution_token][google.cloud.retail.v2alpha.SearchResponse.attribution_token] - will be set in the response. - applied_controls (Sequence[str]): - The fully qualified resource name of applied - `controls `__. - invalid_condition_boost_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - The invalid - [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] - that are not applied during serving. - """ - - class SearchResult(proto.Message): - r"""Represents the search results. - - Attributes: - id (str): - [Product.id][google.cloud.retail.v2alpha.Product.id] of the - searched [Product][google.cloud.retail.v2alpha.Product]. - product (google.cloud.retail_v2alpha.types.Product): - The product data snippet in the search response. Only - [Product.name][google.cloud.retail.v2alpha.Product.name] is - guaranteed to be populated. - - [Product.variants][google.cloud.retail.v2alpha.Product.variants] - contains the product variants that match the search query. - If there are multiple product variants matching the query, - top 5 most relevant product variants are returned and - ordered by relevancy. - - If relevancy can be deternmined, use - [matching_variant_fields][google.cloud.retail.v2alpha.SearchResponse.SearchResult.matching_variant_fields] - to look up matched product variants fields. If relevancy - cannot be determined, e.g. when searching "shoe" all - products in a shoe product can be a match, 5 product - variants are returned but order is meaningless. - matching_variant_count (int): - The count of matched - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s. - matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): - If a - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] matches the - search query, this map indicates which - [Product][google.cloud.retail.v2alpha.Product] fields are - matched. The key is the - [Product.name][google.cloud.retail.v2alpha.Product.name], - the value is a field mask of the matched - [Product][google.cloud.retail.v2alpha.Product] fields. If - matched attributes cannot be determined, this map will be - empty. - - For example, a key "sku1" with field mask - "products.color_info" indicates there is a match between - "sku1" [ColorInfo][google.cloud.retail.v2alpha.ColorInfo] - and the query. - variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): - The rollup matching - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] attributes. - The key is one of the - [SearchRequest.variant_rollup_keys][google.cloud.retail.v2alpha.SearchRequest.variant_rollup_keys]. - The values are the merged and de-duplicated - [Product][google.cloud.retail.v2alpha.Product] attributes. - Notice that the rollup values are respect filter. For - example, when filtering by "colorFamilies:ANY("red")" and - rollup "colorFamilies", only "red" is returned. - - For textual and numerical attributes, the rollup values is a - list of string or double values with type - [google.protobuf.ListValue][google.protobuf.ListValue]. For - example, if there are two variants with colors "red" and - "blue", the rollup values are - - :: - - { key: "colorFamilies" - value { - list_value { - values { string_value: "red" } - values { string_value: "blue" } - } - } - } - - For - [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], - the rollup values is a double value with type - [google.protobuf.Value][google.protobuf.Value]. For example, - ``{key: "pickupInStore.store1" value { number_value: 10 }}`` - means a there are 10 variants in this product are available - in the store "store1". - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - matching_variant_count = proto.Field( - proto.INT32, - number=3, - ) - matching_variant_fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - variant_rollup_values = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - - class Facet(proto.Message): - r"""A facet result. - - Attributes: - key (str): - The key for this facet. E.g., "colorFamilies" - or "price" or "attributes.attr1". - values (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.Facet.FacetValue]): - The facet values for this field. - dynamic_facet (bool): - Whether the facet is dynamically generated. - """ - - class FacetValue(proto.Message): - r"""A facet value which contains value names and their count. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Text value of a facet, such as "Black" for - facet "colorFamilies". - - This field is a member of `oneof`_ ``facet_value``. - interval (google.cloud.retail_v2alpha.types.Interval): - Interval value for a facet, such as [10, 20) for facet - "price". - - This field is a member of `oneof`_ ``facet_value``. - count (int): - Number of items that have this facet value. - """ - - value = proto.Field( - proto.STRING, - number=1, - oneof='facet_value', - ) - interval = proto.Field( - proto.MESSAGE, - number=2, - oneof='facet_value', - message=common.Interval, - ) - count = proto.Field( - proto.INT64, - number=3, - ) - - key = proto.Field( - proto.STRING, - number=1, - ) - values = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SearchResponse.Facet.FacetValue', - ) - dynamic_facet = proto.Field( - proto.BOOL, - number=3, - ) - - class QueryExpansionInfo(proto.Message): - r"""Information describing query expansion including whether - expansion has occurred. - - Attributes: - expanded_query (bool): - Bool describing whether query expansion has - occurred. - pinned_result_count (int): - Number of pinned results. This field will only be set when - expansion happens and - [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] - is set to true. - """ - - expanded_query = proto.Field( - proto.BOOL, - number=1, - ) - pinned_result_count = proto.Field( - proto.INT64, - number=2, - ) - - @property - def raw_page(self): - return self - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=SearchResult, - ) - facets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Facet, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - corrected_query = proto.Field( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - next_page_token = proto.Field( - proto.STRING, - number=6, - ) - query_expansion_info = proto.Field( - proto.MESSAGE, - number=7, - message=QueryExpansionInfo, - ) - redirect_uri = proto.Field( - proto.STRING, - number=10, - ) - applied_controls = proto.RepeatedField( - proto.STRING, - number=12, - ) - invalid_condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py deleted file mode 100644 index c8c3ccca..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py +++ /dev/null @@ -1,309 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'ServingConfig', - }, -) - - -class ServingConfig(proto.Message): - r"""Configures metadata that is used to generate serving time results - (e.g. search results or recommendation predictions). The - ServingConfig is passed in the search and predict request and - together with the Catalog.default_branch, generates results. - - Attributes: - name (str): - Immutable. Fully qualified name - projects/\ */locations/global/catalogs/*/servingConfig/\* - display_name (str): - Required. The human readable serving config display name. - Used in Retail UI. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - model_id (str): - The id of the model to use at serving time. Currently only - RecommendationModels are supported: - https://cloud.google.com/retail/recommendations-ai/docs/create-models - Can be changed but only to a compatible model (e.g. - others-you-may-like CTR to others-you-may-like CVR). - - Required when - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - price_reranking_level (str): - How much price ranking we want in serving results. Price - reranking causes product items with a similar recommendation - probability to be ordered by price, with the highest-priced - items first. This setting could result in a decrease in - click-through and conversion rates. Allowed values are: - - - 'no-price-reranking' - - 'low-price-raranking' - - 'medium-price-reranking' - - 'high-price-reranking' - - If not specified, we choose default based on model type. - Default value: 'no-price-reranking'. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - facet_control_ids (Sequence[str]): - Facet specifications for faceted search. If empty, no facets - are returned. The ids refer to the ids of - [Control][google.cloud.retail.v2alpha.Control] resources - with only the Facet control set. These controls are assumed - to be in the same - [Catalog][google.cloud.retail.v2alpha.Catalog] as the - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]. - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - dynamic_facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec): - The specification for dynamically generated facets. Notice - that only textual facets can be dynamically generated. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - boost_control_ids (Sequence[str]): - Condition boost specifications. If a product matches - multiple conditions in the specifications, boost scores from - these specifications are all applied and combined in a - non-linear way. Maximum number of specifications is 100. - - Notice that if both - [ServingConfig.boost_control_ids][google.cloud.retail.v2alpha.ServingConfig.boost_control_ids] - and [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - filter_control_ids (Sequence[str]): - Condition filter specifications. If a product matches - multiple conditions in the specifications, filters from - these specifications are all applied and combined via the - AND operator. Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - redirect_control_ids (Sequence[str]): - Condition redirect specifications. Only the first triggered - redirect action is applied, even if multiple apply. Maximum - number of specifications is 1000. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - twoway_synonyms_control_ids (Sequence[str]): - Condition synonyms specifications. If multiple syonyms - conditions match, all matching synonyms control in the list - will execute. Order of controls in the list will not matter. - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - oneway_synonyms_control_ids (Sequence[str]): - Condition oneway synonyms specifications. If multiple oneway - synonyms conditions match, all matching oneway synonyms - controls in the list will execute. Order of controls in the - list will not matter. Maximum number of specifications is - 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - do_not_associate_control_ids (Sequence[str]): - Condition do not associate specifications. If multiple do - not associate conditions match, all matching do not - associate controls in the list will execute. - - - Order does not matter. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - replacement_control_ids (Sequence[str]): - Condition replacement specifications. - - - Applied according to the order in the list. - - A previously replaced term can not be re-replaced. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - ignore_control_ids (Sequence[str]): - Condition ignore specifications. If multiple ignore - conditions match, all matching ignore controls in the list - will execute. - - - Order does not matter. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - diversity_level (str): - How much diversity to use in recommendation model results - e.g. 'medium-diversity' or 'high-diversity'. Currently - supported values: - - - 'no-diversity' - - 'low-diversity' - - 'medium-diversity' - - 'high-diversity' - - 'auto-diversity' - - If not specified, we choose default based on recommendation - model type. Default value: 'no-diversity'. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - enable_category_filter_level (str): - Whether to add additional category filters on the - 'similar-items' model. If not specified, we enable it by - default. Allowed values are: - - - 'no-category-match': No additional filtering of original - results from the model and the customer's filters. - - 'relaxed-category-match': Only keep results with - categories that match at least one item categories in the - PredictRequests's context item. - - - If customer also sends filters in the PredictRequest, - then the results will satisfy both conditions (user - given and category match). - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - solution_types (Sequence[google.cloud.retail_v2alpha.types.SolutionType]): - Required. Immutable. Specifies the solution - types that a serving config can be associated - with. Currently we support setting only one type - of solution. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - model_id = proto.Field( - proto.STRING, - number=3, - ) - price_reranking_level = proto.Field( - proto.STRING, - number=4, - ) - facet_control_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=6, - message=search_service.SearchRequest.DynamicFacetSpec, - ) - boost_control_ids = proto.RepeatedField( - proto.STRING, - number=7, - ) - filter_control_ids = proto.RepeatedField( - proto.STRING, - number=9, - ) - redirect_control_ids = proto.RepeatedField( - proto.STRING, - number=10, - ) - twoway_synonyms_control_ids = proto.RepeatedField( - proto.STRING, - number=18, - ) - oneway_synonyms_control_ids = proto.RepeatedField( - proto.STRING, - number=12, - ) - do_not_associate_control_ids = proto.RepeatedField( - proto.STRING, - number=13, - ) - replacement_control_ids = proto.RepeatedField( - proto.STRING, - number=14, - ) - ignore_control_ids = proto.RepeatedField( - proto.STRING, - number=15, - ) - diversity_level = proto.Field( - proto.STRING, - number=8, - ) - enable_category_filter_level = proto.Field( - proto.STRING, - number=16, - ) - solution_types = proto.RepeatedField( - proto.ENUM, - number=19, - enum=common.SolutionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py deleted file mode 100644 index 635f42bb..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py +++ /dev/null @@ -1,234 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'CreateServingConfigRequest', - 'UpdateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'AddControlRequest', - 'RemoveControlRequest', - }, -) - - -class CreateServingConfigRequest(proto.Message): - r"""Request for CreateServingConfig method. - - Attributes: - parent (str): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - serving_config (google.cloud.retail_v2alpha.types.ServingConfig): - Required. The ServingConfig to create. - serving_config_id (str): - Required. The ID to use for the ServingConfig, which will - become the final component of the ServingConfig's resource - name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-_/. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - serving_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_serving_config.ServingConfig, - ) - serving_config_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateServingConfigRequest(proto.Message): - r"""Request for UpdateServingConfig method. - - Attributes: - serving_config (google.cloud.retail_v2alpha.types.ServingConfig): - Required. The ServingConfig to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] - - If not set, all supported fields are updated. - """ - - serving_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_serving_config.ServingConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteServingConfigRequest(proto.Message): - r"""Request for DeleteServingConfig method. - - Attributes: - name (str): - Required. The resource name of the ServingConfig to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetServingConfigRequest(proto.Message): - r"""Request for GetServingConfig method. - - Attributes: - name (str): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListServingConfigsRequest(proto.Message): - r"""Request for ListServingConfigs method. - - Attributes: - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - page_size (int): - Optional. Maximum number of results to - return. If unspecified, defaults to 100. If a - value greater than 100 is provided, at most 100 - results are returned. - page_token (str): - Optional. A page token, received from a previous - ``ListServingConfigs`` call. Provide this to retrieve the - subsequent page. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListServingConfigsResponse(proto.Message): - r"""Response for ListServingConfigs method. - - Attributes: - serving_configs (Sequence[google.cloud.retail_v2alpha.types.ServingConfig]): - All the ServingConfigs for a given catalog. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - serving_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_serving_config.ServingConfig, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class AddControlRequest(proto.Message): - r"""Request for AddControl method. - - Attributes: - serving_config (str): - Required. The source ServingConfig resource name . Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - control_id (str): - Required. The id of the control to apply. Assumed to be in - the same catalog as the serving config - if id is not found - a NOT_FOUND error is returned. - """ - - serving_config = proto.Field( - proto.STRING, - number=1, - ) - control_id = proto.Field( - proto.STRING, - number=2, - ) - - -class RemoveControlRequest(proto.Message): - r"""Request for RemoveControl method. - - Attributes: - serving_config (str): - Required. The source ServingConfig resource name . Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - control_id (str): - Required. The id of the control to apply. - Assumed to be in the same catalog as the serving - config. - """ - - serving_config = proto.Field( - proto.STRING, - number=1, - ) - control_id = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py deleted file mode 100644 index f9d6a684..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py +++ /dev/null @@ -1,507 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'UserEvent', - 'ProductDetail', - 'CompletionDetail', - 'PurchaseTransaction', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information Retail API needs - to know about how end users interact with customers' website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - - ``add-to-cart``: Products being added to cart. - - ``category-page-view``: Special pages such as sale or - promotion pages viewed. - - ``detail-page-view``: Products detail page viewed. - - ``home-page-view``: Homepage viewed. - - ``promotion-offered``: Promotion is offered to a user. - - ``promotion-not-offered``: Promotion is not offered to a - user. - - ``purchase-complete``: User finishing a purchase. - - ``search``: Product search. - - ``shopping-cart-page-view``: User viewing a shopping - cart. - visitor_id (str): - Required. A unique identifier for tracking visitors. - - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor log in/out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - The field should not contain PII or user-data. We recommend - to use Google Analystics `Client - ID `__ - for this field. - session_id (str): - A unique identifier for tracking a visitor session with a - length limit of 128 bytes. A session is an aggregation of an - end user behavior in a time span. - - A general guideline to populate the sesion_id: - - 1. If user has no activity for 30 min, a new session_id - should be assigned. - 2. The session_id should be unique across users, suggest use - uuid or add visitor_id as prefix. - event_time (google.protobuf.timestamp_pb2.Timestamp): - Only required for - [UserEventService.ImportUserEvents][google.cloud.retail.v2alpha.UserEventService.ImportUserEvents] - method. Timestamp of when the user event happened. - experiment_ids (Sequence[str]): - A list of identifiers for the independent - experiment groups this user event belongs to. - This is used to distinguish between user events - associated with different experiment setups - (e.g. using Retail API, using different - recommendation models). - attribution_token (str): - Highly recommended for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2alpha.PredictionService.Predict]. - This field enables accurate attribution of recommendation - model performance. - - The value must be a valid - [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] - for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2alpha.PredictionService.Predict]. - The value must be a valid - [SearchResponse.attribution_token][google.cloud.retail.v2alpha.SearchResponse.attribution_token] - for user events that are the result of - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - This token enables us to accurately attribute page view or - purchase back to the event and the particular predict - response containing this clicked/purchased product. If user - clicks on product K in the recommendation results, pass - [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] - as a URL parameter to product K's page. When recording - events on product K's page, log the - [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] - to this field. - product_details (Sequence[google.cloud.retail_v2alpha.types.ProductDetail]): - The main product details related to the event. - - This field is required for the following event types: - - - ``add-to-cart`` - - ``detail-page-view`` - - ``purchase-complete`` - - ``search`` - - In a ``search`` event, this field represents the products - returned to the end user on the current page (the end user - may have not finished browsing the whole page yet). When a - new page is returned to the end user, after - pagination/filtering/ordering even for the same query, a new - ``search`` event with different - [product_details][google.cloud.retail.v2alpha.UserEvent.product_details] - is desired. The end user may have not finished browsing the - whole page yet. - completion_detail (google.cloud.retail_v2alpha.types.CompletionDetail): - The main auto-completion details related to the event. - - This field should be set for ``search`` event when - autocomplete function is enabled and the user clicks a - suggestion for search. - attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): - Extra user event features to include in the recommendation - model. - - If you provide custom attributes for ingested user events, - also include them in the user events that you associate with - prediction requests. Custom attribute formatting must be - consistent between imported events and events provided with - prediction requests. This lets the Retail API use those - custom attributes when training models and serving - predictions, which helps improve recommendation quality. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - The key must be a UTF-8 encoded string with a length - limit of 5,000 characters. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a UTF-8 - encoded string with a length limit of 256 characters. - - For number attributes, at most 400 values are allowed. - - For product recommendations, an example of extra user - information is traffic_channel, which is how a user arrives - at the site. Users can arrive at the site by coming to the - site directly, coming through Google search, or in other - ways. - cart_id (str): - The ID or name of the associated shopping cart. This ID is - used to associate multiple items added or present in the - cart before purchase. - - This can only be set for ``add-to-cart``, - ``purchase-complete``, or ``shopping-cart-page-view`` - events. - purchase_transaction (google.cloud.retail_v2alpha.types.PurchaseTransaction): - A transaction represents the entire purchase transaction. - - Required for ``purchase-complete`` events. Other event types - should not set this field. Otherwise, an INVALID_ARGUMENT - error is returned. - search_query (str): - The user's search query. - - See - [SearchRequest.query][google.cloud.retail.v2alpha.SearchRequest.query] - for definition. - - The value must be a UTF-8 encoded string with a length limit - of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - At least one of - [search_query][google.cloud.retail.v2alpha.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. - - See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - order_by (str): - The order in which products are returned. - - See - [SearchRequest.order_by][google.cloud.retail.v2alpha.SearchRequest.order_by] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - offset (int): - An integer that specifies the current offset for pagination - (the 0-indexed starting location, amongst the products - deemed by the API as relevant). - - See - [SearchRequest.offset][google.cloud.retail.v2alpha.SearchRequest.offset] - for definition. - - If this field is negative, an INVALID_ARGUMENT is returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - - Required for ``category-page-view`` events. At least one of - [search_query][google.cloud.retail.v2alpha.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2alpha.types.UserInfo): - User information. - uri (str): - Complete URL (window.location.href) of the - user's current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. Maximum length - 5,000 characters. - referrer_uri (str): - The referrer URL of the current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. - page_view_id (str): - A unique ID of a web page view. - - This should be kept the same for all user events triggered - from the same pageview. For example, an item detail page - view could trigger multiple events as the user is browsing - the page. The ``pageViewId`` property should be kept the - same for all these events so that they can be grouped - together properly. - - When using the client side event reporting with JavaScript - pixel and Google Tag Manager, this value is filled in - automatically. - """ - - event_type = proto.Field( - proto.STRING, - number=1, - ) - visitor_id = proto.Field( - proto.STRING, - number=2, - ) - session_id = proto.Field( - proto.STRING, - number=21, - ) - event_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - experiment_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - product_details = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='ProductDetail', - ) - completion_detail = proto.Field( - proto.MESSAGE, - number=22, - message='CompletionDetail', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=common.CustomAttribute, - ) - cart_id = proto.Field( - proto.STRING, - number=8, - ) - purchase_transaction = proto.Field( - proto.MESSAGE, - number=9, - message='PurchaseTransaction', - ) - search_query = proto.Field( - proto.STRING, - number=10, - ) - filter = proto.Field( - proto.STRING, - number=16, - ) - order_by = proto.Field( - proto.STRING, - number=17, - ) - offset = proto.Field( - proto.INT32, - number=18, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=11, - ) - user_info = proto.Field( - proto.MESSAGE, - number=12, - message=common.UserInfo, - ) - uri = proto.Field( - proto.STRING, - number=13, - ) - referrer_uri = proto.Field( - proto.STRING, - number=14, - ) - page_view_id = proto.Field( - proto.STRING, - number=15, - ) - - -class ProductDetail(proto.Message): - r"""Detailed product information associated with a user event. - - Attributes: - product (google.cloud.retail_v2alpha.types.Product): - Required. [Product][google.cloud.retail.v2alpha.Product] - information. - - Required field(s): - - - [Product.id][google.cloud.retail.v2alpha.Product.id] - - Optional override field(s): - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - If any supported optional fields are provided, we will treat - them as a full override when looking up product information - from the catalog. Thus, it is important to ensure that the - overriding fields are accurate and complete. - - All other product fields are ignored and instead populated - via catalog lookup after event ingestion. - quantity (google.protobuf.wrappers_pb2.Int32Value): - Quantity of the product associated with the user event. - - For example, this field will be 2 if two products are added - to the shopping cart for ``purchase-complete`` event. - Required for ``add-to-cart`` and ``purchase-complete`` event - types. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - quantity = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -class CompletionDetail(proto.Message): - r"""Detailed completion information including completion - attribution token and clicked completion info. - - Attributes: - completion_attribution_token (str): - Completion attribution token in - [CompleteQueryResponse.attribution_token][google.cloud.retail.v2alpha.CompleteQueryResponse.attribution_token]. - selected_suggestion (str): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2alpha.CompleteQueryResponse.CompletionResult.suggestion]. - selected_position (int): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2alpha.CompleteQueryResponse.CompletionResult.suggestion] - position, starting from 0. - """ - - completion_attribution_token = proto.Field( - proto.STRING, - number=1, - ) - selected_suggestion = proto.Field( - proto.STRING, - number=2, - ) - selected_position = proto.Field( - proto.INT32, - number=3, - ) - - -class PurchaseTransaction(proto.Message): - r"""A transaction represents the entire purchase transaction. - - Attributes: - id (str): - The transaction ID with a length limit of 128 - characters. - revenue (float): - Required. Total non-zero revenue or grand - total associated with the transaction. This - value include shipping, tax, or other - adjustments to total revenue that you want to - include as part of your revenue calculations. - tax (float): - All the taxes associated with the - transaction. - cost (float): - All the costs associated with the products. These can be - manufacturing costs, shipping expenses not borne by the end - user, or any other costs, such that: - - - Profit = - [revenue][google.cloud.retail.v2alpha.PurchaseTransaction.revenue] - - - [tax][google.cloud.retail.v2alpha.PurchaseTransaction.tax] - - - [cost][google.cloud.retail.v2alpha.PurchaseTransaction.cost] - currency_code (str): - Required. Currency code. Use three-character - ISO-4217 code. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - revenue = proto.Field( - proto.FLOAT, - number=2, - ) - tax = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - currency_code = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py deleted file mode 100644 index 0e679b22..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import user_event as gcr_user_event - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'WriteUserEventRequest', - 'CollectUserEventRequest', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'RejoinUserEventsMetadata', - }, -) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (google.cloud.retail_v2alpha.types.UserEvent): - Required. User event to write. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (str): - Required. URL encoded UserEvent proto with a - length limit of 2,000,000 characters. - uri (str): - The URL including cgi-parameters but - excluding the hash fragment with a length limit - of 5,000 characters. This is often more useful - than the referer URL, because many browsers only - send the domain for 3rd party requests. - ets (int): - The event timestamp in milliseconds. This - prevents browser caching of otherwise identical - get requests. The name is abbreviated to reduce - the payload bytes. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.STRING, - number=2, - ) - uri = proto.Field( - proto.STRING, - number=3, - ) - ets = proto.Field( - proto.INT64, - number=4, - ) - - -class RejoinUserEventsRequest(proto.Message): - r"""Request message for RejoinUserEvents method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event_rejoin_scope (google.cloud.retail_v2alpha.types.RejoinUserEventsRequest.UserEventRejoinScope): - The type of the user event rejoin to define the scope and - range of the user events to be rejoined with the latest - product catalog. Defaults to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not - set, or set to an invalid integer value. - """ - class UserEventRejoinScope(proto.Enum): - r"""The scope of user events to be rejoined with the latest product - catalog. If the rejoining aims at reducing number of unjoined - events, set UserEventRejoinScope to UNJOINED_EVENTS. If the - rejoining aims at correcting product catalog information in joined - events, set UserEventRejoinScope to JOINED_EVENTS. If all events - needs to be rejoined, set UserEventRejoinScope to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. - """ - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 - JOINED_EVENTS = 1 - UNJOINED_EVENTS = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event_rejoin_scope = proto.Field( - proto.ENUM, - number=2, - enum=UserEventRejoinScope, - ) - - -class RejoinUserEventsResponse(proto.Message): - r"""Response message for RejoinUserEvents method. - - Attributes: - rejoined_user_events_count (int): - Number of user events that were joined with - latest product catalog. - """ - - rejoined_user_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -class RejoinUserEventsMetadata(proto.Message): - r"""Metadata for RejoinUserEvents method. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/mypy.ini b/owl-bot-staging/v2alpha/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v2alpha/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2alpha/noxfile.py b/owl-bot-staging/v2alpha/noxfile.py deleted file mode 100644 index 9f7eeaa1..00000000 --- a/owl-bot-staging/v2alpha/noxfile.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.6", - "3.7", - "3.8", - "3.9", - "3.10", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==19.10b0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.9" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/retail_v2alpha/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py deleted file mode 100644 index 9b5622c2..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async] -from google.cloud import retail_v2alpha - - -async def sample_add_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py deleted file mode 100644 index ec76bc9f..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync] -from google.cloud import retail_v2alpha - - -def sample_add_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py deleted file mode 100644 index d2f66638..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetAttributesConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_get_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetAttributesConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py deleted file mode 100644 index 91c914b3..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_get_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py deleted file mode 100644 index 9da8e840..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetCompletionConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_get_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetCompletionConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py deleted file mode 100644 index 5da5cd9f..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_get_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py deleted file mode 100644 index 2134a810..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetDefaultBranch_async] -from google.cloud import retail_v2alpha - - -async def sample_get_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py deleted file mode 100644 index d233b424..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync] -from google.cloud import retail_v2alpha - - -def sample_get_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py deleted file mode 100644 index 7e7fbf33..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_ListCatalogs_async] -from google.cloud import retail_v2alpha - - -async def sample_list_catalogs(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py deleted file mode 100644 index 8165c25b..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_ListCatalogs_sync] -from google.cloud import retail_v2alpha - - -def sample_list_catalogs(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py deleted file mode 100644 index f79bd768..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async] -from google.cloud import retail_v2alpha - - -async def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = await client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py deleted file mode 100644 index 35b6611c..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync] -from google.cloud import retail_v2alpha - - -def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py deleted file mode 100644 index c42a8bb1..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReplaceCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async] -from google.cloud import retail_v2alpha - - -async def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py deleted file mode 100644 index 56e779ab..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReplaceCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync] -from google.cloud import retail_v2alpha - - -def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py deleted file mode 100644 index 9ddf2f8e..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_SetDefaultBranch_async] -from google.cloud import retail_v2alpha - - -async def sample_set_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - -# [END retail_v2alpha_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py deleted file mode 100644 index 6fa13ce6..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync] -from google.cloud import retail_v2alpha - - -def sample_set_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - -# [END retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py deleted file mode 100644 index c4654be4..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_update_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - attributes_config = retail_v2alpha.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2alpha.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = await client.update_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py deleted file mode 100644 index 1f4d3432..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_update_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - attributes_config = retail_v2alpha.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2alpha.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = client.update_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py deleted file mode 100644 index 6035f718..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateCatalog_async] -from google.cloud import retail_v2alpha - - -async def sample_update_catalog(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2alpha.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2alpha.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py deleted file mode 100644 index 35fff0d1..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateCatalog_sync] -from google.cloud import retail_v2alpha - - -def sample_update_catalog(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2alpha.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2alpha.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py deleted file mode 100644 index 26cac134..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_update_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - completion_config = retail_v2alpha.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2alpha.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = await client.update_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py deleted file mode 100644 index b9e11448..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_update_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - completion_config = retail_v2alpha.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2alpha.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = client.update_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py deleted file mode 100644 index 13dce99f..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CompletionService_CompleteQuery_async] -from google.cloud import retail_v2alpha - - -async def sample_complete_query(): - # Create a client - client = retail_v2alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py deleted file mode 100644 index 20687e33..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CompletionService_CompleteQuery_sync] -from google.cloud import retail_v2alpha - - -def sample_complete_query(): - # Create a client - client = retail_v2alpha.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py deleted file mode 100644 index d1a515f2..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CompletionService_ImportCompletionData_async] -from google.cloud import retail_v2alpha - - -async def sample_import_completion_data(): - # Create a client - client = retail_v2alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2alpha.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py deleted file mode 100644 index 3c6ddc55..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CompletionService_ImportCompletionData_sync] -from google.cloud import retail_v2alpha - - -def sample_import_completion_data(): - # Create a client - client = retail_v2alpha.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2alpha.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py deleted file mode 100644 index 131de87e..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_CreateControl_async] -from google.cloud import retail_v2alpha - - -async def sample_create_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = await client.create_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_CreateControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py deleted file mode 100644 index 8fee66d8..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_CreateControl_sync] -from google.cloud import retail_v2alpha - - -def sample_create_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = client.create_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_CreateControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py deleted file mode 100644 index ae438a78..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_DeleteControl_async] -from google.cloud import retail_v2alpha - - -async def sample_delete_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteControlRequest( - name="name_value", - ) - - # Make the request - await client.delete_control(request=request) - - -# [END retail_v2alpha_generated_ControlService_DeleteControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py deleted file mode 100644 index b83ddcd5..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_DeleteControl_sync] -from google.cloud import retail_v2alpha - - -def sample_delete_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteControlRequest( - name="name_value", - ) - - # Make the request - client.delete_control(request=request) - - -# [END retail_v2alpha_generated_ControlService_DeleteControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py deleted file mode 100644 index 588c8955..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_GetControl_async] -from google.cloud import retail_v2alpha - - -async def sample_get_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetControlRequest( - name="name_value", - ) - - # Make the request - response = await client.get_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_GetControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py deleted file mode 100644 index f04eb36b..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_GetControl_sync] -from google.cloud import retail_v2alpha - - -def sample_get_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetControlRequest( - name="name_value", - ) - - # Make the request - response = client.get_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_GetControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py deleted file mode 100644 index 005329c1..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListControls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_ListControls_async] -from google.cloud import retail_v2alpha - - -async def sample_list_controls(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ControlService_ListControls_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py deleted file mode 100644 index 301c6036..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListControls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_ListControls_sync] -from google.cloud import retail_v2alpha - - -def sample_list_controls(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ControlService_ListControls_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py deleted file mode 100644 index dc422066..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_UpdateControl_async] -from google.cloud import retail_v2alpha - - -async def sample_update_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.UpdateControlRequest( - control=control, - ) - - # Make the request - response = await client.update_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_UpdateControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py deleted file mode 100644 index cf7823fd..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_UpdateControl_sync] -from google.cloud import retail_v2alpha - - -def sample_update_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.UpdateControlRequest( - control=control, - ) - - # Make the request - response = client.update_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_UpdateControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py deleted file mode 100644 index 7d3c4540..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_PredictionService_Predict_async] -from google.cloud import retail_v2alpha - - -async def sample_predict(): - # Create a client - client = retail_v2alpha.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py deleted file mode 100644 index c3dbd187..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_PredictionService_Predict_sync] -from google.cloud import retail_v2alpha - - -def sample_predict(): - # Create a client - client = retail_v2alpha.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py deleted file mode 100644 index 4ef15987..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async] -from google.cloud import retail_v2alpha - - -async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py deleted file mode 100644 index 03f0cd6d..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync] -from google.cloud import retail_v2alpha - - -def sample_add_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py deleted file mode 100644 index c3b7dfdf..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_AddLocalInventories_async] -from google.cloud import retail_v2alpha - - -async def sample_add_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py deleted file mode 100644 index b91b57f3..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_AddLocalInventories_sync] -from google.cloud import retail_v2alpha - - -def sample_add_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py deleted file mode 100644 index 8ca45663..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_CreateProduct_async] -from google.cloud import retail_v2alpha - - -async def sample_create_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py deleted file mode 100644 index b2946508..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_CreateProduct_sync] -from google.cloud import retail_v2alpha - - -def sample_create_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py deleted file mode 100644 index 1ae74222..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_DeleteProduct_async] -from google.cloud import retail_v2alpha - - -async def sample_delete_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - -# [END retail_v2alpha_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py deleted file mode 100644 index faebc2e4..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_DeleteProduct_sync] -from google.cloud import retail_v2alpha - - -def sample_delete_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - -# [END retail_v2alpha_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py deleted file mode 100644 index 70903b9e..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_GetProduct_async] -from google.cloud import retail_v2alpha - - -async def sample_get_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py deleted file mode 100644 index 25fccda2..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_GetProduct_sync] -from google.cloud import retail_v2alpha - - -def sample_get_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py deleted file mode 100644 index 5cfaf031..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_ImportProducts_async] -from google.cloud import retail_v2alpha - - -async def sample_import_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2alpha.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py deleted file mode 100644 index ca54ea57..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_ImportProducts_sync] -from google.cloud import retail_v2alpha - - -def sample_import_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2alpha.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py deleted file mode 100644 index 8dcf7a71..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_ListProducts_async] -from google.cloud import retail_v2alpha - - -async def sample_list_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py deleted file mode 100644 index aa96e9c2..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_ListProducts_sync] -from google.cloud import retail_v2alpha - - -def sample_list_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py deleted file mode 100644 index 8adf6af4..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_PurgeProducts_async] -from google.cloud import retail_v2alpha - - -async def sample_purge_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeProductsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_PurgeProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py deleted file mode 100644 index 72c32c88..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_PurgeProducts_sync] -from google.cloud import retail_v2alpha - - -def sample_purge_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeProductsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_PurgeProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py deleted file mode 100644 index da379da0..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async] -from google.cloud import retail_v2alpha - - -async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py deleted file mode 100644 index 55bf6522..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync] -from google.cloud import retail_v2alpha - - -def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py deleted file mode 100644 index bc0b9406..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_RemoveLocalInventories_async] -from google.cloud import retail_v2alpha - - -async def sample_remove_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py deleted file mode 100644 index 40e0b2bb..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync] -from google.cloud import retail_v2alpha - - -def sample_remove_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py deleted file mode 100644 index 64dc769c..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_SetInventory_async] -from google.cloud import retail_v2alpha - - -async def sample_set_inventory(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2alpha.Product() - inventory.title = "title_value" - - request = retail_v2alpha.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py deleted file mode 100644 index 9dbf88b6..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_SetInventory_sync] -from google.cloud import retail_v2alpha - - -def sample_set_inventory(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2alpha.Product() - inventory.title = "title_value" - - request = retail_v2alpha.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py deleted file mode 100644 index 35df5c2b..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_UpdateProduct_async] -from google.cloud import retail_v2alpha - - -async def sample_update_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py deleted file mode 100644 index 6248e977..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_UpdateProduct_sync] -from google.cloud import retail_v2alpha - - -def sample_update_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py deleted file mode 100644 index 75520b76..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_SearchService_Search_async] -from google.cloud import retail_v2alpha - - -async def sample_search(): - # Create a client - client = retail_v2alpha.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py deleted file mode 100644 index 2b2853a3..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_SearchService_Search_sync] -from google.cloud import retail_v2alpha - - -def sample_search(): - # Create a client - client = retail_v2alpha.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py deleted file mode 100644 index 0694590c..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_AddControl_async] -from google.cloud import retail_v2alpha - - -async def sample_add_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.add_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_AddControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py deleted file mode 100644 index 10d50ff7..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_AddControl_sync] -from google.cloud import retail_v2alpha - - -def sample_add_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.add_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_AddControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py deleted file mode 100644 index 33b080fc..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_create_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = await client.create_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py deleted file mode 100644 index e7b0e80e..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_create_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = client.create_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py deleted file mode 100644 index f8259bdf..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_delete_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_serving_config(request=request) - - -# [END retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py deleted file mode 100644 index 621916ef..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_delete_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_serving_config(request=request) - - -# [END retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py deleted file mode 100644 index fdfd4d80..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_GetServingConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_get_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_GetServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py deleted file mode 100644 index a1408016..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_get_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py deleted file mode 100644 index c8244f95..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServingConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async] -from google.cloud import retail_v2alpha - - -async def sample_list_serving_configs(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py deleted file mode 100644 index 86e02687..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServingConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync] -from google.cloud import retail_v2alpha - - -def sample_list_serving_configs(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py deleted file mode 100644 index 66e07902..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_RemoveControl_async] -from google.cloud import retail_v2alpha - - -async def sample_remove_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.remove_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_RemoveControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py deleted file mode 100644 index 8b39362b..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_RemoveControl_sync] -from google.cloud import retail_v2alpha - - -def sample_remove_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.remove_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_RemoveControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py deleted file mode 100644 index 64e82dba..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_update_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = await client.update_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py deleted file mode 100644 index 46d2d65c..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_update_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = client.update_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py deleted file mode 100644 index f8aa3f78..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_CollectUserEvent_async] -from google.cloud import retail_v2alpha - - -async def sample_collect_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py deleted file mode 100644 index 026972b1..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_CollectUserEvent_sync] -from google.cloud import retail_v2alpha - - -def sample_collect_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py deleted file mode 100644 index 540ce130..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_ImportUserEvents_async] -from google.cloud import retail_v2alpha - - -async def sample_import_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2alpha.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py deleted file mode 100644 index fe9310db..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_ImportUserEvents_sync] -from google.cloud import retail_v2alpha - - -def sample_import_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2alpha.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py deleted file mode 100644 index 17d5c66d..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_PurgeUserEvents_async] -from google.cloud import retail_v2alpha - - -async def sample_purge_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py deleted file mode 100644 index d8b2ae83..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync] -from google.cloud import retail_v2alpha - - -def sample_purge_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py deleted file mode 100644 index d38bb5f4..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_RejoinUserEvents_async] -from google.cloud import retail_v2alpha - - -async def sample_rejoin_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py deleted file mode 100644 index f88f6437..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync] -from google.cloud import retail_v2alpha - - -def sample_rejoin_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py deleted file mode 100644 index 2dda0e65..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_WriteUserEvent_async] -from google.cloud import retail_v2alpha - - -async def sample_write_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py deleted file mode 100644 index a121bdbd..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_WriteUserEvent_sync] -from google.cloud import retail_v2alpha - - -def sample_write_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json b/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json deleted file mode 100644 index ea2cf419..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json +++ /dev/null @@ -1,7066 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.retail.v2alpha", - "version": "v2alpha" - } - ], - "language": "PYTHON", - "name": "google-cloud-retail" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.add_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "AddCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "add_catalog_attribute" - }, - "description": "Sample for AddCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.add_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "AddCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "add_catalog_attribute" - }, - "description": "Sample for AddCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetAttributesConfigRequest" - }, - { - "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.retail_v2alpha.types.AttributesConfig", - "shortName": "get_attributes_config" - }, - "description": "Sample for GetAttributesConfig", - "file": "retail_v2alpha_generated_catalog_service_get_attributes_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetAttributesConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_attributes_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetAttributesConfigRequest" - }, - { - "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.retail_v2alpha.types.AttributesConfig", - "shortName": "get_attributes_config" - }, - "description": "Sample for GetAttributesConfig", - "file": "retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_completion_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetCompletionConfigRequest" - }, - { - "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.retail_v2alpha.types.CompletionConfig", - "shortName": "get_completion_config" - }, - "description": "Sample for GetCompletionConfig", - "file": "retail_v2alpha_generated_catalog_service_get_completion_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetCompletionConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_completion_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_completion_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetCompletionConfigRequest" - }, - { - "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.retail_v2alpha.types.CompletionConfig", - "shortName": "get_completion_config" - }, - "description": "Sample for GetCompletionConfig", - "file": "retail_v2alpha_generated_catalog_service_get_completion_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_completion_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2alpha_generated_catalog_service_get_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetDefaultBranch_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2alpha_generated_catalog_service_get_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListCatalogsRequest" - }, - { - "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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsAsyncPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2alpha_generated_catalog_service_list_catalogs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_ListCatalogs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_list_catalogs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListCatalogsRequest" - }, - { - "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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2alpha_generated_catalog_service_list_catalogs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_ListCatalogs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_list_catalogs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.remove_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "RemoveCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "remove_catalog_attribute" - }, - "description": "Sample for RemoveCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.remove_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "RemoveCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "remove_catalog_attribute" - }, - "description": "Sample for RemoveCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.replace_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ReplaceCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "replace_catalog_attribute" - }, - "description": "Sample for ReplaceCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.replace_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ReplaceCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "replace_catalog_attribute" - }, - "description": "Sample for ReplaceCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2alpha_generated_catalog_service_set_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_SetDefaultBranch_async", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_set_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2alpha_generated_catalog_service_set_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_set_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest" - }, - { - "name": "attributes_config", - "type": "google.cloud.retail_v2alpha.types.AttributesConfig" - }, - { - "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.retail_v2alpha.types.AttributesConfig", - "shortName": "update_attributes_config" - }, - "description": "Sample for UpdateAttributesConfig", - "file": "retail_v2alpha_generated_catalog_service_update_attributes_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_attributes_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest" - }, - { - "name": "attributes_config", - "type": "google.cloud.retail_v2alpha.types.AttributesConfig" - }, - { - "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.retail_v2alpha.types.AttributesConfig", - "shortName": "update_attributes_config" - }, - "description": "Sample for UpdateAttributesConfig", - "file": "retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2alpha.types.Catalog" - }, - { - "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.retail_v2alpha.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2alpha_generated_catalog_service_update_catalog_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCatalog_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_catalog_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2alpha.types.Catalog" - }, - { - "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.retail_v2alpha.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2alpha_generated_catalog_service_update_catalog_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCatalog_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_catalog_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_completion_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest" - }, - { - "name": "completion_config", - "type": "google.cloud.retail_v2alpha.types.CompletionConfig" - }, - { - "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.retail_v2alpha.types.CompletionConfig", - "shortName": "update_completion_config" - }, - "description": "Sample for UpdateCompletionConfig", - "file": "retail_v2alpha_generated_catalog_service_update_completion_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_completion_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_completion_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest" - }, - { - "name": "completion_config", - "type": "google.cloud.retail_v2alpha.types.CompletionConfig" - }, - { - "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.retail_v2alpha.types.CompletionConfig", - "shortName": "update_completion_config" - }, - "description": "Sample for UpdateCompletionConfig", - "file": "retail_v2alpha_generated_catalog_service_update_completion_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_completion_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2alpha.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2alpha_generated_completion_service_complete_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CompletionService_CompleteQuery_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_completion_service_complete_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2alpha.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2alpha_generated_completion_service_complete_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CompletionService_CompleteQuery_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_completion_service_complete_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2alpha.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2alpha_generated_completion_service_import_completion_data_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CompletionService_ImportCompletionData_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_completion_service_import_completion_data_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2alpha.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2alpha_generated_completion_service_import_completion_data_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CompletionService_ImportCompletionData_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_completion_service_import_completion_data_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.create_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.CreateControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "CreateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateControlRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "control", - "type": "google.cloud.retail_v2alpha.types.Control" - }, - { - "name": "control_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.retail_v2alpha.types.Control", - "shortName": "create_control" - }, - "description": "Sample for CreateControl", - "file": "retail_v2alpha_generated_control_service_create_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_CreateControl_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_create_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.create_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.CreateControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "CreateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateControlRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "control", - "type": "google.cloud.retail_v2alpha.types.Control" - }, - { - "name": "control_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.retail_v2alpha.types.Control", - "shortName": "create_control" - }, - "description": "Sample for CreateControl", - "file": "retail_v2alpha_generated_control_service_create_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_CreateControl_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_create_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.delete_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.DeleteControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "DeleteControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteControlRequest" - }, - { - "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_control" - }, - "description": "Sample for DeleteControl", - "file": "retail_v2alpha_generated_control_service_delete_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_DeleteControl_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_delete_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.delete_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.DeleteControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "DeleteControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteControlRequest" - }, - { - "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_control" - }, - "description": "Sample for DeleteControl", - "file": "retail_v2alpha_generated_control_service_delete_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_DeleteControl_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_delete_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.get_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.GetControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "GetControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetControlRequest" - }, - { - "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.retail_v2alpha.types.Control", - "shortName": "get_control" - }, - "description": "Sample for GetControl", - "file": "retail_v2alpha_generated_control_service_get_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_GetControl_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_get_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.get_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.GetControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "GetControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetControlRequest" - }, - { - "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.retail_v2alpha.types.Control", - "shortName": "get_control" - }, - "description": "Sample for GetControl", - "file": "retail_v2alpha_generated_control_service_get_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_GetControl_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_get_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.list_controls", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.ListControls", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "ListControls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListControlsRequest" - }, - { - "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.retail_v2alpha.services.control_service.pagers.ListControlsAsyncPager", - "shortName": "list_controls" - }, - "description": "Sample for ListControls", - "file": "retail_v2alpha_generated_control_service_list_controls_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_ListControls_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_list_controls_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.list_controls", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.ListControls", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "ListControls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListControlsRequest" - }, - { - "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.retail_v2alpha.services.control_service.pagers.ListControlsPager", - "shortName": "list_controls" - }, - "description": "Sample for ListControls", - "file": "retail_v2alpha_generated_control_service_list_controls_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_ListControls_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_list_controls_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.update_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.UpdateControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "UpdateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateControlRequest" - }, - { - "name": "control", - "type": "google.cloud.retail_v2alpha.types.Control" - }, - { - "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.retail_v2alpha.types.Control", - "shortName": "update_control" - }, - "description": "Sample for UpdateControl", - "file": "retail_v2alpha_generated_control_service_update_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_UpdateControl_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_update_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.update_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.UpdateControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "UpdateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateControlRequest" - }, - { - "name": "control", - "type": "google.cloud.retail_v2alpha.types.Control" - }, - { - "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.retail_v2alpha.types.Control", - "shortName": "update_control" - }, - "description": "Sample for UpdateControl", - "file": "retail_v2alpha_generated_control_service_update_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_UpdateControl_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_update_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.PredictionServiceAsyncClient", - "shortName": "PredictionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.PredictionServiceAsyncClient.predict", - "method": { - "fullName": "google.cloud.retail.v2alpha.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2alpha.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2alpha_generated_prediction_service_predict_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_PredictionService_Predict_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_prediction_service_predict_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.PredictionServiceClient", - "shortName": "PredictionServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.PredictionServiceClient.predict", - "method": { - "fullName": "google.cloud.retail.v2alpha.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2alpha.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2alpha_generated_prediction_service_predict_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_PredictionService_Predict_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_prediction_service_predict_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2alpha_generated_product_service_add_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_add_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2alpha_generated_product_service_add_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_AddLocalInventories_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_add_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2alpha_generated_product_service_add_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_AddLocalInventories_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_add_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "name": "product_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.retail_v2alpha.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2alpha_generated_product_service_create_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_CreateProduct_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_create_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "name": "product_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.retail_v2alpha.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2alpha_generated_product_service_create_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_CreateProduct_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_create_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2alpha_generated_product_service_delete_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_DeleteProduct_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_delete_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2alpha_generated_product_service_delete_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_DeleteProduct_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_delete_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetProductRequest" - }, - { - "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.retail_v2alpha.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2alpha_generated_product_service_get_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_GetProduct_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_get_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetProductRequest" - }, - { - "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.retail_v2alpha.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2alpha_generated_product_service_get_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_GetProduct_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_get_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2alpha_generated_product_service_import_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_ImportProducts_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_import_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2alpha_generated_product_service_import_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_ImportProducts_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_import_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListProductsRequest" - }, - { - "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.retail_v2alpha.services.product_service.pagers.ListProductsAsyncPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2alpha_generated_product_service_list_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_ListProducts_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_list_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListProductsRequest" - }, - { - "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.retail_v2alpha.services.product_service.pagers.ListProductsPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2alpha_generated_product_service_list_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_ListProducts_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_list_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.purge_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.PurgeProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "PurgeProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PurgeProductsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_products" - }, - "description": "Sample for PurgeProducts", - "file": "retail_v2alpha_generated_product_service_purge_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_PurgeProducts_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_purge_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.purge_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.PurgeProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "PurgeProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PurgeProductsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_products" - }, - "description": "Sample for PurgeProducts", - "file": "retail_v2alpha_generated_product_service_purge_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_PurgeProducts_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_purge_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2alpha_generated_product_service_remove_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_RemoveLocalInventories_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_remove_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2alpha_generated_product_service_remove_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_remove_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2alpha_generated_product_service_set_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_SetInventory_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_set_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2alpha_generated_product_service_set_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_SetInventory_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_set_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "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.retail_v2alpha.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2alpha_generated_product_service_update_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_UpdateProduct_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_update_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "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.retail_v2alpha.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2alpha_generated_product_service_update_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_UpdateProduct_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_update_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.SearchServiceAsyncClient.search", - "method": { - "fullName": "google.cloud.retail.v2alpha.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2alpha.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2alpha_generated_search_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_SearchService_Search_async", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_search_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.SearchServiceClient", - "shortName": "SearchServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.SearchServiceClient.search", - "method": { - "fullName": "google.cloud.retail.v2alpha.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2alpha.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.services.search_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2alpha_generated_search_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_SearchService_Search_sync", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_search_service_search_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.add_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.AddControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "AddControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "add_control" - }, - "description": "Sample for AddControl", - "file": "retail_v2alpha_generated_serving_config_service_add_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_AddControl_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_add_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.add_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.AddControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "AddControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "add_control" - }, - "description": "Sample for AddControl", - "file": "retail_v2alpha_generated_serving_config_service_add_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_AddControl_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_add_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.create_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.CreateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "CreateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateServingConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2alpha.types.ServingConfig" - }, - { - "name": "serving_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "create_serving_config" - }, - "description": "Sample for CreateServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_create_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_create_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.create_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.CreateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "CreateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateServingConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2alpha.types.ServingConfig" - }, - { - "name": "serving_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "create_serving_config" - }, - "description": "Sample for CreateServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.delete_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.DeleteServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "DeleteServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteServingConfigRequest" - }, - { - "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_serving_config" - }, - "description": "Sample for DeleteServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.delete_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.DeleteServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "DeleteServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteServingConfigRequest" - }, - { - "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_serving_config" - }, - "description": "Sample for DeleteServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.get_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.GetServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "GetServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetServingConfigRequest" - }, - { - "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.retail_v2alpha.types.ServingConfig", - "shortName": "get_serving_config" - }, - "description": "Sample for GetServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_get_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_GetServingConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_get_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.get_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.GetServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "GetServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetServingConfigRequest" - }, - { - "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.retail_v2alpha.types.ServingConfig", - "shortName": "get_serving_config" - }, - "description": "Sample for GetServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.list_serving_configs", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.ListServingConfigs", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "ListServingConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListServingConfigsRequest" - }, - { - "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.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsAsyncPager", - "shortName": "list_serving_configs" - }, - "description": "Sample for ListServingConfigs", - "file": "retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.list_serving_configs", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.ListServingConfigs", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "ListServingConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListServingConfigsRequest" - }, - { - "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.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsPager", - "shortName": "list_serving_configs" - }, - "description": "Sample for ListServingConfigs", - "file": "retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.remove_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.RemoveControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "RemoveControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "remove_control" - }, - "description": "Sample for RemoveControl", - "file": "retail_v2alpha_generated_serving_config_service_remove_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_RemoveControl_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_remove_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.remove_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.RemoveControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "RemoveControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "remove_control" - }, - "description": "Sample for RemoveControl", - "file": "retail_v2alpha_generated_serving_config_service_remove_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_RemoveControl_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_remove_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.update_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.UpdateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "UpdateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2alpha.types.ServingConfig" - }, - { - "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.retail_v2alpha.types.ServingConfig", - "shortName": "update_serving_config" - }, - "description": "Sample for UpdateServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_update_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_update_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.update_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.UpdateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "UpdateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2alpha.types.ServingConfig" - }, - { - "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.retail_v2alpha.types.ServingConfig", - "shortName": "update_serving_config" - }, - "description": "Sample for UpdateServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2alpha_generated_user_event_service_collect_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_CollectUserEvent_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_collect_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2alpha_generated_user_event_service_collect_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_CollectUserEvent_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_collect_user_event_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2alpha_generated_user_event_service_import_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_ImportUserEvents_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_import_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2alpha_generated_user_event_service_import_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_ImportUserEvents_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_import_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2alpha_generated_user_event_service_purge_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_PurgeUserEvents_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_purge_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2alpha_generated_user_event_service_purge_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_purge_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_RejoinUserEvents_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2alpha_generated_user_event_service_write_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_WriteUserEvent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_write_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2alpha_generated_user_event_service_write_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_WriteUserEvent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_write_user_event_sync.py" - } - ] -} diff --git a/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py b/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py deleted file mode 100644 index 5fbe2d4d..00000000 --- a/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py +++ /dev/null @@ -1,219 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class retailCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_catalog_attribute': ('attributes_config', 'catalog_attribute', ), - 'add_control': ('serving_config', 'control_id', ), - 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), - 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), - 'create_control': ('parent', 'control', 'control_id', ), - 'create_product': ('parent', 'product', 'product_id', ), - 'create_serving_config': ('parent', 'serving_config', 'serving_config_id', ), - 'delete_control': ('name', ), - 'delete_product': ('name', ), - 'delete_serving_config': ('name', ), - 'get_attributes_config': ('name', ), - 'get_completion_config': ('name', ), - 'get_control': ('name', ), - 'get_default_branch': ('catalog', ), - 'get_product': ('name', ), - 'get_serving_config': ('name', ), - 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), - 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), - 'import_user_events': ('parent', 'input_config', 'errors_config', ), - 'list_catalogs': ('parent', 'page_size', 'page_token', ), - 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', 'require_total_size', ), - 'list_serving_configs': ('parent', 'page_size', 'page_token', ), - 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), - 'purge_products': ('parent', 'filter', 'force', ), - 'purge_user_events': ('parent', 'filter', 'force', ), - 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), - 'remove_catalog_attribute': ('attributes_config', 'key', ), - 'remove_control': ('serving_config', 'control_id', ), - 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), - 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), - 'replace_catalog_attribute': ('attributes_config', 'catalog_attribute', 'update_mask', ), - 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'relevance_threshold', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), - 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), - 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), - 'update_attributes_config': ('attributes_config', 'update_mask', ), - 'update_catalog': ('catalog', 'update_mask', ), - 'update_completion_config': ('completion_config', 'update_mask', ), - 'update_control': ('control', 'update_mask', ), - 'update_product': ('product', 'update_mask', 'allow_missing', ), - 'update_serving_config': ('serving_config', 'update_mask', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=retailCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the retail client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2alpha/setup.py b/owl-bot-staging/v2alpha/setup.py deleted file mode 100644 index 3d49d09f..00000000 --- a/owl-bot-staging/v2alpha/setup.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-retail', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-retail", - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.31.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'googleapis-common-protos >= 1.55.0, <2.0.0dev', - 'proto-plus >= 1.19.7', - ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v2alpha/tests/__init__.py b/owl-bot-staging/v2alpha/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2alpha/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/tests/unit/__init__.py b/owl-bot-staging/v2alpha/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py deleted file mode 100644 index b956c510..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py +++ /dev/null @@ -1,3793 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.catalog_service import CatalogServiceAsyncClient -from google.cloud.retail_v2alpha.services.catalog_service import CatalogServiceClient -from google.cloud.retail_v2alpha.services.catalog_service import pagers -from google.cloud.retail_v2alpha.services.catalog_service import transports -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CatalogServiceClient._get_default_mtls_endpoint(None) is None - assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CatalogServiceGrpcTransport, "grpc"), - (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_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", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_catalog_service_client_get_transport_class(): - transport = CatalogServiceClient.get_transport_class() - available_transports = [ - transports.CatalogServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CatalogServiceClient.get_transport_class("grpc") - assert transport == transports.CatalogServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - CatalogServiceClient, CatalogServiceAsyncClient -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_catalog_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CatalogServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ListCatalogsRequest, - dict, -]) -def test_list_catalogs(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalogs), - '__call__') as call: - client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - -@pytest.mark.asyncio -async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_catalogs_async_from_dict(): - await test_list_catalogs_async(request_type=dict) - - -def test_list_catalogs_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = catalog_service.ListCatalogsResponse() - client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_catalogs( - 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_catalogs_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_catalogs_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_catalogs( - 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_catalogs_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - - -def test_list_catalogs_pager(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_catalogs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, catalog.Catalog) - for i in results) -def test_list_catalogs_pages(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = list(client.list_catalogs(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_catalogs_async_pager(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_catalogs(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, catalog.Catalog) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_catalogs_async_pages(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCatalogRequest, - dict, -]) -def test_update_catalog(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - ) - response = client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_catalog_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalog), - '__call__') as call: - client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - -@pytest.mark.asyncio -async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_catalog_async_from_dict(): - await test_update_catalog_async(request_type=dict) - - -def test_update_catalog_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = gcr_catalog.Catalog() - client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_catalog_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -def test_update_catalog_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_catalog_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.SetDefaultBranchRequest, - dict, -]) -def test_set_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_set_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_set_default_branch_async_from_dict(): - await test_set_default_branch_async(request_type=dict) - - -def test_set_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = None - client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_set_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_set_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetDefaultBranchRequest, - dict, -]) -def test_get_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - ) - response = client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -def test_get_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_default_branch), - '__call__') as call: - client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - )) - response = await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -@pytest.mark.asyncio -async def test_get_default_branch_async_from_dict(): - await test_get_default_branch_async(request_type=dict) - - -def test_get_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = catalog_service.GetDefaultBranchResponse() - client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_get_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_get_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetCompletionConfigRequest, - dict, -]) -def test_get_completion_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - ) - response = client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -def test_get_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_completion_config), - '__call__') as call: - client.get_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - -@pytest.mark.asyncio -async def test_get_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCompletionConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - )) - response = await client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -@pytest.mark.asyncio -async def test_get_completion_config_async_from_dict(): - await test_get_completion_config_async(request_type=dict) - - -def test_get_completion_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCompletionConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - call.return_value = catalog.CompletionConfig() - client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_completion_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCompletionConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - await client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_completion_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_completion_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_completion_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_completion_config( - catalog_service.GetCompletionConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_completion_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_completion_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_completion_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_completion_config( - catalog_service.GetCompletionConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCompletionConfigRequest, - dict, -]) -def test_update_completion_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - ) - response = client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -def test_update_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_completion_config), - '__call__') as call: - client.update_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - -@pytest.mark.asyncio -async def test_update_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCompletionConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - )) - response = await client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -@pytest.mark.asyncio -async def test_update_completion_config_async_from_dict(): - await test_update_completion_config_async(request_type=dict) - - -def test_update_completion_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCompletionConfigRequest() - - request.completion_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - call.return_value = catalog.CompletionConfig() - client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'completion_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_completion_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCompletionConfigRequest() - - request.completion_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - await client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'completion_config.name=name_value', - ) in kw['metadata'] - - -def test_update_completion_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_completion_config( - completion_config=catalog.CompletionConfig(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].completion_config - mock_val = catalog.CompletionConfig(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_completion_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_completion_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_completion_config( - completion_config=catalog.CompletionConfig(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].completion_config - mock_val = catalog.CompletionConfig(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_completion_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetAttributesConfigRequest, - dict, -]) -def test_get_attributes_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_get_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_attributes_config), - '__call__') as call: - client.get_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - -@pytest.mark.asyncio -async def test_get_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetAttributesConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_get_attributes_config_async_from_dict(): - await test_get_attributes_config_async(request_type=dict) - - -def test_get_attributes_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetAttributesConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_attributes_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetAttributesConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_attributes_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_attributes_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_attributes_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_attributes_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_attributes_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_attributes_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateAttributesConfigRequest, - dict, -]) -def test_update_attributes_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_update_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_attributes_config), - '__call__') as call: - client.update_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - -@pytest.mark.asyncio -async def test_update_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateAttributesConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_update_attributes_config_async_from_dict(): - await test_update_attributes_config_async(request_type=dict) - - -def test_update_attributes_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateAttributesConfigRequest() - - request.attributes_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_attributes_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateAttributesConfigRequest() - - request.attributes_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config.name=name_value', - ) in kw['metadata'] - - -def test_update_attributes_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_attributes_config( - attributes_config=catalog.AttributesConfig(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].attributes_config - mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_attributes_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_attributes_config( - attributes_config=catalog.AttributesConfig(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].attributes_config - mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.AddCatalogAttributeRequest, - dict, -]) -def test_add_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_add_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - client.add_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_add_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.AddCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_add_catalog_attribute_async_from_dict(): - await test_add_catalog_attribute_async(request_type=dict) - - -def test_add_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.AddCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.AddCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - catalog_service.RemoveCatalogAttributeRequest, - dict, -]) -def test_remove_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_remove_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - client.remove_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.RemoveCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_async_from_dict(): - await test_remove_catalog_attribute_async(request_type=dict) - - -def test_remove_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.RemoveCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.RemoveCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ReplaceCatalogAttributeRequest, - dict, -]) -def test_replace_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_replace_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - client.replace_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ReplaceCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_async_from_dict(): - await test_replace_catalog_attribute_async(request_type=dict) - - -def test_replace_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ReplaceCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ReplaceCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CatalogServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.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 = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CatalogServiceGrpcTransport, - ) - -def test_catalog_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_catalog_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_catalogs', - 'update_catalog', - 'set_default_branch', - 'get_default_branch', - 'get_completion_config', - 'update_completion_config', - 'get_attributes_config', - 'update_attributes_config', - 'add_catalog_attribute', - 'remove_catalog_attribute', - 'replace_catalog_attribute', - ) - 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_catalog_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.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport( - 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_catalog_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.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport() - adc.assert_called_once() - - -def test_catalog_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) - CatalogServiceClient() - 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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -def test_catalog_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,grpc_helpers", - [ - (transports.CatalogServiceGrpcTransport, grpc_helpers), - (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_catalog_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_no_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_with_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_catalog_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcTransport( - 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_catalog_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcAsyncIOTransport( - 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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_attributes_config_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.attributes_config_path(project, location, catalog) - assert expected == actual - - -def test_parse_attributes_config_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CatalogServiceClient.attributes_config_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_attributes_config_path(path) - assert expected == actual - -def test_branch_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = CatalogServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "branch": "clam", - } - path = CatalogServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_branch_path(path) - assert expected == actual - -def test_catalog_path(): - project = "whelk" - location = "octopus" - catalog = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - } - path = CatalogServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_completion_config_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.completion_config_path(project, location, catalog) - assert expected == actual - - -def test_parse_completion_config_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - } - path = CatalogServiceClient.completion_config_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_completion_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CatalogServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = CatalogServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = CatalogServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = CatalogServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CatalogServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = CatalogServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = CatalogServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = CatalogServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = CatalogServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CatalogServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py deleted file mode 100644 index 9cd6cc79..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py +++ /dev/null @@ -1,1451 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.completion_service import CompletionServiceAsyncClient -from google.cloud.retail_v2alpha.services.completion_service import CompletionServiceClient -from google.cloud.retail_v2alpha.services.completion_service import transports -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CompletionServiceClient._get_default_mtls_endpoint(None) is None - assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CompletionServiceGrpcTransport, "grpc"), - (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_completion_service_client_get_transport_class(): - transport = CompletionServiceClient.get_transport_class() - available_transports = [ - transports.CompletionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CompletionServiceClient.get_transport_class("grpc") - assert transport == transports.CompletionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - CompletionServiceClient, CompletionServiceAsyncClient -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_completion_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CompletionServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - ) - response = client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - -@pytest.mark.asyncio -async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - )) - response = await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -@pytest.mark.asyncio -async def test_complete_query_async_from_dict(): - await test_complete_query_async(request_type=dict) - - -def test_complete_query_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = completion_service.CompleteQueryResponse() - client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_complete_query_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) - await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportCompletionDataRequest, - dict, -]) -def test_import_completion_data(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_completion_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - -@pytest.mark.asyncio -async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_completion_data_async_from_dict(): - await test_import_completion_data_async(request_type=dict) - - -def test_import_completion_data_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # 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_completion_data_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CompletionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CompletionServiceGrpcTransport, - ) - -def test_completion_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_completion_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'complete_query', - 'import_completion_data', - ) - 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_completion_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_completion_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport() - adc.assert_called_once() - - -def test_completion_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CompletionServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionServiceGrpcTransport, grpc_helpers), - (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_completion_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_no_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_with_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_completion_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_completion_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_completion_service_grpc_lro_client(): - client = CompletionServiceClient( - 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_completion_service_grpc_lro_async_client(): - client = CompletionServiceAsyncClient( - 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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CompletionServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CompletionServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CompletionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CompletionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = CompletionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CompletionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CompletionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CompletionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = CompletionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CompletionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CompletionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CompletionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CompletionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py deleted file mode 100644 index 197c7a8b..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py +++ /dev/null @@ -1,2566 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.control_service import ControlServiceAsyncClient -from google.cloud.retail_v2alpha.services.control_service import ControlServiceClient -from google.cloud.retail_v2alpha.services.control_service import pagers -from google.cloud.retail_v2alpha.services.control_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.cloud.retail_v2alpha.types import search_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ControlServiceClient._get_default_mtls_endpoint(None) is None - assert ControlServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ControlServiceClient, "grpc"), - (ControlServiceAsyncClient, "grpc_asyncio"), -]) -def test_control_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ControlServiceGrpcTransport, "grpc"), - (transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_control_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", [ - (ControlServiceClient, "grpc"), - (ControlServiceAsyncClient, "grpc_asyncio"), -]) -def test_control_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_control_service_client_get_transport_class(): - transport = ControlServiceClient.get_transport_class() - available_transports = [ - transports.ControlServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ControlServiceClient.get_transport_class("grpc") - assert transport == transports.ControlServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -def test_control_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(ControlServiceClient, '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(ControlServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "true"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "false"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_control_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - ControlServiceClient, ControlServiceAsyncClient -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -def test_control_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_control_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_control_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_control_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.control_service.transports.ControlServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ControlServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_control_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.CreateControlRequest, - dict, -]) -def test_create_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -def test_create_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.create_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - -@pytest.mark.asyncio -async def test_create_control_async(transport: str = 'grpc_asyncio', request_type=control_service.CreateControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - )) - response = await client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -@pytest.mark.asyncio -async def test_create_control_async_from_dict(): - await test_create_control_async(request_type=dict) - - -def test_create_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.CreateControlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - call.return_value = gcr_control.Control() - client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.CreateControlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - await client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_control( - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) - assert arg == mock_val - arg = args[0].control_id - mock_val = 'control_id_value' - assert arg == mock_val - - -def test_create_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.CreateControlRequest(), - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_id_value', - ) - -@pytest.mark.asyncio -async def test_create_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_control( - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) - assert arg == mock_val - arg = args[0].control_id - mock_val = 'control_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.CreateControlRequest(), - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.DeleteControlRequest, - dict, -]) -def test_delete_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.delete_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - -@pytest.mark.asyncio -async def test_delete_control_async(transport: str = 'grpc_asyncio', request_type=control_service.DeleteControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_control_async_from_dict(): - await test_delete_control_async(request_type=dict) - - -def test_delete_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.DeleteControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__call__') as call: - call.return_value = None - client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.DeleteControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__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_control( - 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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.DeleteControlRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__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_control( - 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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.DeleteControlRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.UpdateControlRequest, - dict, -]) -def test_update_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -def test_update_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.update_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - -@pytest.mark.asyncio -async def test_update_control_async(transport: str = 'grpc_asyncio', request_type=control_service.UpdateControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - )) - response = await client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -@pytest.mark.asyncio -async def test_update_control_async_from_dict(): - await test_update_control_async(request_type=dict) - - -def test_update_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.UpdateControlRequest() - - request.control.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - call.return_value = gcr_control.Control() - client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'control.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.UpdateControlRequest() - - request.control.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - await client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'control.name=name_value', - ) in kw['metadata'] - - -def test_update_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_control( - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_control( - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.GetControlRequest, - dict, -]) -def test_get_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -def test_get_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.get_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - -@pytest.mark.asyncio -async def test_get_control_async(transport: str = 'grpc_asyncio', request_type=control_service.GetControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - )) - response = await client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -@pytest.mark.asyncio -async def test_get_control_async_from_dict(): - await test_get_control_async(request_type=dict) - - -def test_get_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.GetControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - call.return_value = control.Control() - client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.GetControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) - await client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_control( - 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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.GetControlRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_control( - 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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.GetControlRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.ListControlsRequest, - dict, -]) -def test_list_controls(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_controls_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_controls), - '__call__') as call: - client.list_controls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - -@pytest.mark.asyncio -async def test_list_controls_async(transport: str = 'grpc_asyncio', request_type=control_service.ListControlsRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_controls_async_from_dict(): - await test_list_controls_async(request_type=dict) - - -def test_list_controls_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.ListControlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - call.return_value = control_service.ListControlsResponse() - client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_controls_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.ListControlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) - await client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_controls_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_controls( - 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_controls_flattened_error(): - client = ControlServiceClient( - credentials=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_controls( - control_service.ListControlsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_controls_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_controls( - 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_controls_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_controls( - control_service.ListControlsRequest(), - parent='parent_value', - ) - - -def test_list_controls_pager(transport_name: str = "grpc"): - client = ControlServiceClient( - 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_controls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_controls(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, control.Control) - for i in results) -def test_list_controls_pages(transport_name: str = "grpc"): - client = ControlServiceClient( - 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_controls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - pages = list(client.list_controls(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_controls_async_pager(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_controls(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, control.Control) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_controls_async_pages(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_controls(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ControlServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ControlServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ControlServiceClient.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 = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ControlServiceGrpcTransport, - ) - -def test_control_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ControlServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_control_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.control_service.transports.ControlServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ControlServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_control', - 'delete_control', - 'update_control', - 'get_control', - 'list_controls', - ) - 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_control_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.retail_v2alpha.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ControlServiceTransport( - 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_control_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.retail_v2alpha.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ControlServiceTransport() - adc.assert_called_once() - - -def test_control_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) - ControlServiceClient() - 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.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - ], -) -def test_control_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,grpc_helpers", - [ - (transports.ControlServiceGrpcTransport, grpc_helpers), - (transports.ControlServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_control_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_control_service_host_no_port(transport_name): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_control_service_host_with_port(transport_name): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_control_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ControlServiceGrpcTransport( - 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_control_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ControlServiceGrpcAsyncIOTransport( - 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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = ControlServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = ControlServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_control_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - control = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) - actual = ControlServiceClient.control_path(project, location, catalog, control) - assert expected == actual - - -def test_parse_control_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "control": "clam", - } - path = ControlServiceClient.control_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_control_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ControlServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ControlServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ControlServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ControlServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ControlServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ControlServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ControlServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ControlServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.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 = ControlServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ControlServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.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.ControlServiceTransport, '_prep_wrapped_messages') as prep: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ControlServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ControlServiceClient.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 = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ControlServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ControlServiceClient( - 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", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py deleted file mode 100644 index c264812d..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py +++ /dev/null @@ -1,1279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.prediction_service import PredictionServiceAsyncClient -from google.cloud.retail_v2alpha.services.prediction_service import PredictionServiceClient -from google.cloud.retail_v2alpha.services.prediction_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import prediction_service -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import user_event -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PredictionServiceClient._get_default_mtls_endpoint(None) is None - assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PredictionServiceGrpcTransport, "grpc"), - (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_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", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_prediction_service_client_get_transport_class(): - transport = PredictionServiceClient.get_transport_class() - available_transports = [ - transports.PredictionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = PredictionServiceClient.get_transport_class("grpc") - assert transport == transports.PredictionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - PredictionServiceClient, PredictionServiceAsyncClient -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_prediction_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PredictionServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - prediction_service.PredictRequest, - dict, -]) -def test_predict(request_type, transport: str = 'grpc'): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - response = client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - -@pytest.mark.asyncio -async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - )) - response = await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -@pytest.mark.asyncio -async def test_predict_async_from_dict(): - await test_predict_async(request_type=dict) - - -def test_predict_field_headers(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = prediction_service.PredictResponse() - client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_predict_field_headers_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) - await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PredictionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PredictionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.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 = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, - ) - -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'predict', - ) - 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport( - 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport() - adc.assert_called_once() - - -def test_prediction_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) - PredictionServiceClient() - 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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -def test_prediction_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,grpc_helpers", - [ - (transports.PredictionServiceGrpcTransport, grpc_helpers), - (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_prediction_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_no_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_with_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_prediction_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcTransport( - 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_prediction_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcAsyncIOTransport( - 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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_product_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - product = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - "branch": "winkle", - "product": "nautilus", - } - path = PredictionServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PredictionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = PredictionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = PredictionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = PredictionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PredictionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = PredictionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = PredictionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = PredictionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = PredictionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PredictionServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py deleted file mode 100644 index f6da565c..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py +++ /dev/null @@ -1,4237 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.product_service import ProductServiceAsyncClient -from google.cloud.retail_v2alpha.services.product_service import ProductServiceClient -from google.cloud.retail_v2alpha.services.product_service import pagers -from google.cloud.retail_v2alpha.services.product_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import purge_config -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ProductServiceClient._get_default_mtls_endpoint(None) is None - assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ProductServiceGrpcTransport, "grpc"), - (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_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", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_product_service_client_get_transport_class(): - transport = ProductServiceClient.get_transport_class() - available_transports = [ - transports.ProductServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ProductServiceClient.get_transport_class("grpc") - assert transport == transports.ProductServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_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(ProductServiceClient, '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(ProductServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - ProductServiceClient, ProductServiceAsyncClient -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_product_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProductServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.CreateProductRequest, - dict, -]) -def test_create_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_create_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - -@pytest.mark.asyncio -async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_create_product_async_from_dict(): - await test_create_product_async(request_type=dict) - - -def test_create_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - - -def test_create_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - -@pytest.mark.asyncio -async def test_create_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.GetProductRequest, - dict, -]) -def test_get_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_get_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - -@pytest.mark.asyncio -async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_get_product_async_from_dict(): - await test_get_product_async(request_type=dict) - - -def test_get_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = product.Product() - client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.GetProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.GetProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.ListProductsRequest, - dict, -]) -def test_list_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - -@pytest.mark.asyncio -async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_products_async_from_dict(): - await test_list_products_async(request_type=dict) - - -def test_list_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = product_service.ListProductsResponse() - client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_products( - 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_products_flattened_error(): - client = ProductServiceClient( - credentials=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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_products_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_products( - 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_products_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - - -def test_list_products_pager(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_products(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, product.Product) - for i in results) -def test_list_products_pages(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = list(client.list_products(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_products_async_pager(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_products(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, product.Product) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_products_async_pages(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_products(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - product_service.UpdateProductRequest, - dict, -]) -def test_update_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_update_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - -@pytest.mark.asyncio -async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_update_product_async_from_dict(): - await test_update_product_async(request_type=dict) - - -def test_update_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -def test_update_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.DeleteProductRequest, - dict, -]) -def test_delete_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - -@pytest.mark.asyncio -async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_product_async_from_dict(): - await test_delete_product_async(request_type=dict) - - -def test_delete_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = None - client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeProductsRequest, - dict, -]) -def test_purge_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - client.purge_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - -@pytest.mark.asyncio -async def test_purge_products_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.purge_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_products_async_from_dict(): - await test_purge_products_async(request_type=dict) - - -def test_purge_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_purge_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportProductsRequest, - dict, -]) -def test_import_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - -@pytest.mark.asyncio -async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__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_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_products_async_from_dict(): - await test_import_products_async(request_type=dict) - - -def test_import_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - product_service.SetInventoryRequest, - dict, -]) -def test_set_inventory(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_inventory_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - -@pytest.mark.asyncio -async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_inventory_async_from_dict(): - await test_set_inventory_async(request_type=dict) - - -def test_set_inventory_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_inventory_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -def test_set_inventory_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_set_inventory_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_set_inventory_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_inventory_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddFulfillmentPlacesRequest, - dict, -]) -def test_add_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async_from_dict(): - await test_add_fulfillment_places_async(request_type=dict) - - -def test_add_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveFulfillmentPlacesRequest, - dict, -]) -def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async_from_dict(): - await test_remove_fulfillment_places_async(request_type=dict) - - -def test_remove_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddLocalInventoriesRequest, - dict, -]) -def test_add_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_local_inventories_async_from_dict(): - await test_add_local_inventories_async(request_type=dict) - - -def test_add_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveLocalInventoriesRequest, - dict, -]) -def test_remove_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_local_inventories_async_from_dict(): - await test_remove_local_inventories_async(request_type=dict) - - -def test_remove_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProductServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ProductServiceClient.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 = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProductServiceGrpcTransport, - ) - -def test_product_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_product_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.product_service.transports.ProductServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_product', - 'get_product', - 'list_products', - 'update_product', - 'delete_product', - 'purge_products', - 'import_products', - 'set_inventory', - 'add_fulfillment_places', - 'remove_fulfillment_places', - 'add_local_inventories', - 'remove_local_inventories', - ) - 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_product_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.retail_v2alpha.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport( - 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_product_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.retail_v2alpha.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport() - adc.assert_called_once() - - -def test_product_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) - ProductServiceClient() - 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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - ], -) -def test_product_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,grpc_helpers", - [ - (transports.ProductServiceGrpcTransport, grpc_helpers), - (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_product_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_no_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_with_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_product_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcTransport( - 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_product_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcAsyncIOTransport( - 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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_product_service_grpc_lro_client(): - client = ProductServiceClient( - 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_product_service_grpc_lro_async_client(): - client = ProductServiceAsyncClient( - 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" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = ProductServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = ProductServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = ProductServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = ProductServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProductServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ProductServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProductServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ProductServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProductServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ProductServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ProductServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ProductServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ProductServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ProductServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ProductServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py deleted file mode 100644 index feeb37e8..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py +++ /dev/null @@ -1,1496 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.search_service import SearchServiceAsyncClient -from google.cloud.retail_v2alpha.services.search_service import SearchServiceClient -from google.cloud.retail_v2alpha.services.search_service import pagers -from google.cloud.retail_v2alpha.services.search_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SearchServiceClient._get_default_mtls_endpoint(None) is None - assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SearchServiceGrpcTransport, "grpc"), - (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_search_service_client_get_transport_class(): - transport = SearchServiceClient.get_transport_class() - available_transports = [ - transports.SearchServiceGrpcTransport, - ] - assert transport in available_transports - - transport = SearchServiceClient.get_transport_class("grpc") - assert transport == transports.SearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - SearchServiceClient, SearchServiceAsyncClient -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SearchServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - search_service.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - - -def test_search_field_headers(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = search_service.SearchResponse() - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_field_headers_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_search_pager(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('placement', ''), - )), - ) - pager = client.search(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_async_pager(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, - ) - -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_search_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_search_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport() - adc.assert_called_once() - - -def test_search_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SearchServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SearchServiceGrpcTransport, grpc_helpers), - (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_search_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_no_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_with_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_branch_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = SearchServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = SearchServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = SearchServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = SearchServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py deleted file mode 100644 index a4c423fa..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py +++ /dev/null @@ -1,3279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.serving_config_service import ServingConfigServiceAsyncClient -from google.cloud.retail_v2alpha.services.serving_config_service import ServingConfigServiceClient -from google.cloud.retail_v2alpha.services.serving_config_service import pagers -from google.cloud.retail_v2alpha.services.serving_config_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ServingConfigServiceClient._get_default_mtls_endpoint(None) is None - assert ServingConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServingConfigServiceClient, "grpc"), - (ServingConfigServiceAsyncClient, "grpc_asyncio"), -]) -def test_serving_config_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ServingConfigServiceGrpcTransport, "grpc"), - (transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_serving_config_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", [ - (ServingConfigServiceClient, "grpc"), - (ServingConfigServiceAsyncClient, "grpc_asyncio"), -]) -def test_serving_config_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_serving_config_service_client_get_transport_class(): - transport = ServingConfigServiceClient.get_transport_class() - available_transports = [ - transports.ServingConfigServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ServingConfigServiceClient.get_transport_class("grpc") - assert transport == transports.ServingConfigServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -def test_serving_config_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(ServingConfigServiceClient, '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(ServingConfigServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "true"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "false"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_serving_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - ServingConfigServiceClient, ServingConfigServiceAsyncClient -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -def test_serving_config_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_serving_config_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_serving_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_serving_config_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ServingConfigServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_serving_config_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.CreateServingConfigRequest, - dict, -]) -def test_create_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_create_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.create_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - -@pytest.mark.asyncio -async def test_create_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.CreateServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_create_serving_config_async_from_dict(): - await test_create_serving_config_async(request_type=dict) - - -def test_create_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.CreateServingConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.CreateServingConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_serving_config( - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].serving_config - mock_val = gcr_serving_config.ServingConfig(name='name_value') - assert arg == mock_val - arg = args[0].serving_config_id - mock_val = 'serving_config_id_value' - assert arg == mock_val - - -def test_create_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.CreateServingConfigRequest(), - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_serving_config( - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].serving_config - mock_val = gcr_serving_config.ServingConfig(name='name_value') - assert arg == mock_val - arg = args[0].serving_config_id - mock_val = 'serving_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.CreateServingConfigRequest(), - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.DeleteServingConfigRequest, - dict, -]) -def test_delete_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.delete_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - -@pytest.mark.asyncio -async def test_delete_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.DeleteServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_serving_config_async_from_dict(): - await test_delete_serving_config_async(request_type=dict) - - -def test_delete_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.DeleteServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__call__') as call: - call.return_value = None - client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.DeleteServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__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_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.DeleteServingConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__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_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.DeleteServingConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.UpdateServingConfigRequest, - dict, -]) -def test_update_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_update_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.update_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - -@pytest.mark.asyncio -async def test_update_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.UpdateServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_update_serving_config_async_from_dict(): - await test_update_serving_config_async(request_type=dict) - - -def test_update_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.UpdateServingConfigRequest() - - request.serving_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.UpdateServingConfigRequest() - - request.serving_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config.name=name_value', - ) in kw['metadata'] - - -def test_update_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_serving_config( - serving_config=gcr_serving_config.ServingConfig(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].serving_config - mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_serving_config( - serving_config=gcr_serving_config.ServingConfig(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].serving_config - mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.GetServingConfigRequest, - dict, -]) -def test_get_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_get_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.get_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - -@pytest.mark.asyncio -async def test_get_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.GetServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_get_serving_config_async_from_dict(): - await test_get_serving_config_async(request_type=dict) - - -def test_get_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.GetServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - call.return_value = serving_config.ServingConfig() - client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.GetServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) - await client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.GetServingConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.GetServingConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.ListServingConfigsRequest, - dict, -]) -def test_list_serving_configs(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_serving_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_configs), - '__call__') as call: - client.list_serving_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - -@pytest.mark.asyncio -async def test_list_serving_configs_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.ListServingConfigsRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_serving_configs_async_from_dict(): - await test_list_serving_configs_async(request_type=dict) - - -def test_list_serving_configs_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.ListServingConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - call.return_value = serving_config_service.ListServingConfigsResponse() - client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_serving_configs_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.ListServingConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) - await client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_serving_configs_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_serving_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_serving_configs_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_serving_configs_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_serving_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_serving_configs_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent='parent_value', - ) - - -def test_list_serving_configs_pager(transport_name: str = "grpc"): - client = ServingConfigServiceClient( - 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_serving_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_serving_configs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, serving_config.ServingConfig) - for i in results) -def test_list_serving_configs_pages(transport_name: str = "grpc"): - client = ServingConfigServiceClient( - 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_serving_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_serving_configs(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_serving_configs_async_pager(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_serving_configs(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, serving_config.ServingConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_serving_configs_async_pages(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_serving_configs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - serving_config_service.AddControlRequest, - dict, -]) -def test_add_control(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_add_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - client.add_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - -@pytest.mark.asyncio -async def test_add_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.AddControlRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_add_control_async_from_dict(): - await test_add_control_async(request_type=dict) - - -def test_add_control_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.AddControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_control_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.AddControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_add_control_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.add_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - - -def test_add_control_flattened_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_control( - serving_config_service.AddControlRequest(), - serving_config='serving_config_value', - ) - -@pytest.mark.asyncio -async def test_add_control_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.add_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_control_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_control( - serving_config_service.AddControlRequest(), - serving_config='serving_config_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.RemoveControlRequest, - dict, -]) -def test_remove_control(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_remove_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - client.remove_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - -@pytest.mark.asyncio -async def test_remove_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.RemoveControlRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_remove_control_async_from_dict(): - await test_remove_control_async(request_type=dict) - - -def test_remove_control_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.RemoveControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_control_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.RemoveControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_remove_control_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.remove_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - - -def test_remove_control_flattened_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config='serving_config_value', - ) - -@pytest.mark.asyncio -async def test_remove_control_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.remove_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_control_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config='serving_config_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ServingConfigServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ServingConfigServiceClient.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 = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ServingConfigServiceGrpcTransport, - ) - -def test_serving_config_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ServingConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_serving_config_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ServingConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_serving_config', - 'delete_serving_config', - 'update_serving_config', - 'get_serving_config', - 'list_serving_configs', - 'add_control', - 'remove_control', - ) - 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_serving_config_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.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServingConfigServiceTransport( - 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_serving_config_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.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServingConfigServiceTransport() - adc.assert_called_once() - - -def test_serving_config_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) - ServingConfigServiceClient() - 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.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - ], -) -def test_serving_config_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,grpc_helpers", - [ - (transports.ServingConfigServiceGrpcTransport, grpc_helpers), - (transports.ServingConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_serving_config_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_serving_config_service_host_no_port(transport_name): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_serving_config_service_host_with_port(transport_name): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_serving_config_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServingConfigServiceGrpcTransport( - 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_serving_config_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( - 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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = ServingConfigServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = ServingConfigServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - serving_config = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, serving_config=serving_config, ) - actual = ServingConfigServiceClient.serving_config_path(project, location, catalog, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "serving_config": "clam", - } - path = ServingConfigServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ServingConfigServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ServingConfigServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ServingConfigServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ServingConfigServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ServingConfigServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ServingConfigServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ServingConfigServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ServingConfigServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.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 = ServingConfigServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ServingConfigServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.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.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ServingConfigServiceClient.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 = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ServingConfigServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ServingConfigServiceClient( - 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", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py deleted file mode 100644 index 88587802..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py +++ /dev/null @@ -1,1988 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.retail_v2alpha.services.user_event_service import UserEventServiceClient -from google.cloud.retail_v2alpha.services.user_event_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, UserEventServiceAsyncClient -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - ) - response = client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = user_event.UserEvent() - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) - await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeUserEventsRequest, - dict, -]) -def test_purge_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - -@pytest.mark.asyncio -async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_user_events_async_from_dict(): - await test_purge_user_events_async(request_type=dict) - - -def test_purge_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_purge_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.RejoinUserEventsRequest, - dict, -]) -def test_rejoin_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_rejoin_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - -@pytest.mark.asyncio -async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_rejoin_user_events_async_from_dict(): - await test_rejoin_user_events_async(request_type=dict) - - -def test_rejoin_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_rejoin_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'purge_user_events', - 'import_user_events', - 'rejoin_user_events', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_user_event_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_user_event_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -def test_user_event_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - UserEventServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_no_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_with_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = UserEventServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = UserEventServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_product_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - product = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - "branch": "whelk", - "product": "octopus", - } - path = UserEventServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2beta/.coveragerc b/owl-bot-staging/v2beta/.coveragerc deleted file mode 100644 index a8b114f0..00000000 --- a/owl-bot-staging/v2beta/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/retail/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2beta/.flake8 b/owl-bot-staging/v2beta/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v2beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2beta/MANIFEST.in b/owl-bot-staging/v2beta/MANIFEST.in deleted file mode 100644 index 43074617..00000000 --- a/owl-bot-staging/v2beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/retail *.py -recursive-include google/cloud/retail_v2beta *.py diff --git a/owl-bot-staging/v2beta/README.rst b/owl-bot-staging/v2beta/README.rst deleted file mode 100644 index cb039760..00000000 --- a/owl-bot-staging/v2beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Retail API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Retail API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2beta/docs/conf.py b/owl-bot-staging/v2beta/docs/conf.py deleted file mode 100644 index 5be9eb4b..00000000 --- a/owl-bot-staging/v2beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-retail documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-retail" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-retail-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-retail.tex", - u"google-cloud-retail Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-retail", - u"Google Cloud Retail Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-retail", - u"google-cloud-retail Documentation", - author, - "google-cloud-retail", - "GAPIC library for Google Cloud Retail API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2beta/docs/index.rst b/owl-bot-staging/v2beta/docs/index.rst deleted file mode 100644 index fd60fc85..00000000 --- a/owl-bot-staging/v2beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - retail_v2beta/services - retail_v2beta/types diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst deleted file mode 100644 index 3a7c19e6..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CatalogService --------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.catalog_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.catalog_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst deleted file mode 100644 index 1f6782ed..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CompletionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2beta.services.completion_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst deleted file mode 100644 index 86cfcba1..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ControlService --------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.control_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.control_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst deleted file mode 100644 index 903c951d..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -PredictionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2beta.services.prediction_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst deleted file mode 100644 index 489daa22..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ProductService --------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.product_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.product_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst deleted file mode 100644 index 591f5c86..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SearchService -------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst deleted file mode 100644 index 04251720..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst +++ /dev/null @@ -1,13 +0,0 @@ -Services for Google Cloud Retail v2beta API -=========================================== -.. toctree:: - :maxdepth: 2 - - catalog_service - completion_service - control_service - prediction_service - product_service - search_service - serving_config_service - user_event_service diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst deleted file mode 100644 index c074749c..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ServingConfigService --------------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.serving_config_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.serving_config_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst deleted file mode 100644 index ae17ce43..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Retail v2beta API -======================================== - -.. automodule:: google.cloud.retail_v2beta.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst deleted file mode 100644 index 11ab3794..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.user_event_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/google/cloud/retail/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail/__init__.py deleted file mode 100644 index 07f795e3..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail/__init__.py +++ /dev/null @@ -1,275 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.retail_v2beta.services.catalog_service.client import CatalogServiceClient -from google.cloud.retail_v2beta.services.catalog_service.async_client import CatalogServiceAsyncClient -from google.cloud.retail_v2beta.services.completion_service.client import CompletionServiceClient -from google.cloud.retail_v2beta.services.completion_service.async_client import CompletionServiceAsyncClient -from google.cloud.retail_v2beta.services.control_service.client import ControlServiceClient -from google.cloud.retail_v2beta.services.control_service.async_client import ControlServiceAsyncClient -from google.cloud.retail_v2beta.services.prediction_service.client import PredictionServiceClient -from google.cloud.retail_v2beta.services.prediction_service.async_client import PredictionServiceAsyncClient -from google.cloud.retail_v2beta.services.product_service.client import ProductServiceClient -from google.cloud.retail_v2beta.services.product_service.async_client import ProductServiceAsyncClient -from google.cloud.retail_v2beta.services.search_service.client import SearchServiceClient -from google.cloud.retail_v2beta.services.search_service.async_client import SearchServiceAsyncClient -from google.cloud.retail_v2beta.services.serving_config_service.client import ServingConfigServiceClient -from google.cloud.retail_v2beta.services.serving_config_service.async_client import ServingConfigServiceAsyncClient -from google.cloud.retail_v2beta.services.user_event_service.client import UserEventServiceClient -from google.cloud.retail_v2beta.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.retail_v2beta.types.catalog import AttributesConfig -from google.cloud.retail_v2beta.types.catalog import Catalog -from google.cloud.retail_v2beta.types.catalog import CatalogAttribute -from google.cloud.retail_v2beta.types.catalog import CompletionConfig -from google.cloud.retail_v2beta.types.catalog import MerchantCenterLink -from google.cloud.retail_v2beta.types.catalog import MerchantCenterLinkingConfig -from google.cloud.retail_v2beta.types.catalog import ProductLevelConfig -from google.cloud.retail_v2beta.types.catalog_service import AddCatalogAttributeRequest -from google.cloud.retail_v2beta.types.catalog_service import GetAttributesConfigRequest -from google.cloud.retail_v2beta.types.catalog_service import GetCompletionConfigRequest -from google.cloud.retail_v2beta.types.catalog_service import GetDefaultBranchRequest -from google.cloud.retail_v2beta.types.catalog_service import GetDefaultBranchResponse -from google.cloud.retail_v2beta.types.catalog_service import ListCatalogsRequest -from google.cloud.retail_v2beta.types.catalog_service import ListCatalogsResponse -from google.cloud.retail_v2beta.types.catalog_service import RemoveCatalogAttributeRequest -from google.cloud.retail_v2beta.types.catalog_service import ReplaceCatalogAttributeRequest -from google.cloud.retail_v2beta.types.catalog_service import SetDefaultBranchRequest -from google.cloud.retail_v2beta.types.catalog_service import UpdateAttributesConfigRequest -from google.cloud.retail_v2beta.types.catalog_service import UpdateCatalogRequest -from google.cloud.retail_v2beta.types.catalog_service import UpdateCompletionConfigRequest -from google.cloud.retail_v2beta.types.common import Audience -from google.cloud.retail_v2beta.types.common import ColorInfo -from google.cloud.retail_v2beta.types.common import Condition -from google.cloud.retail_v2beta.types.common import CustomAttribute -from google.cloud.retail_v2beta.types.common import FulfillmentInfo -from google.cloud.retail_v2beta.types.common import Image -from google.cloud.retail_v2beta.types.common import Interval -from google.cloud.retail_v2beta.types.common import LocalInventory -from google.cloud.retail_v2beta.types.common import PriceInfo -from google.cloud.retail_v2beta.types.common import Rating -from google.cloud.retail_v2beta.types.common import Rule -from google.cloud.retail_v2beta.types.common import UserInfo -from google.cloud.retail_v2beta.types.common import AttributeConfigLevel -from google.cloud.retail_v2beta.types.common import SearchSolutionUseCase -from google.cloud.retail_v2beta.types.common import SolutionType -from google.cloud.retail_v2beta.types.completion_service import CompleteQueryRequest -from google.cloud.retail_v2beta.types.completion_service import CompleteQueryResponse -from google.cloud.retail_v2beta.types.control import Control -from google.cloud.retail_v2beta.types.control_service import CreateControlRequest -from google.cloud.retail_v2beta.types.control_service import DeleteControlRequest -from google.cloud.retail_v2beta.types.control_service import GetControlRequest -from google.cloud.retail_v2beta.types.control_service import ListControlsRequest -from google.cloud.retail_v2beta.types.control_service import ListControlsResponse -from google.cloud.retail_v2beta.types.control_service import UpdateControlRequest -from google.cloud.retail_v2beta.types.export_config import ExportErrorsConfig -from google.cloud.retail_v2beta.types.export_config import ExportMetadata -from google.cloud.retail_v2beta.types.export_config import ExportProductsResponse -from google.cloud.retail_v2beta.types.export_config import ExportUserEventsResponse -from google.cloud.retail_v2beta.types.import_config import BigQuerySource -from google.cloud.retail_v2beta.types.import_config import CompletionDataInputConfig -from google.cloud.retail_v2beta.types.import_config import GcsSource -from google.cloud.retail_v2beta.types.import_config import ImportCompletionDataRequest -from google.cloud.retail_v2beta.types.import_config import ImportCompletionDataResponse -from google.cloud.retail_v2beta.types.import_config import ImportErrorsConfig -from google.cloud.retail_v2beta.types.import_config import ImportMetadata -from google.cloud.retail_v2beta.types.import_config import ImportProductsRequest -from google.cloud.retail_v2beta.types.import_config import ImportProductsResponse -from google.cloud.retail_v2beta.types.import_config import ImportUserEventsRequest -from google.cloud.retail_v2beta.types.import_config import ImportUserEventsResponse -from google.cloud.retail_v2beta.types.import_config import ProductInlineSource -from google.cloud.retail_v2beta.types.import_config import ProductInputConfig -from google.cloud.retail_v2beta.types.import_config import UserEventImportSummary -from google.cloud.retail_v2beta.types.import_config import UserEventInlineSource -from google.cloud.retail_v2beta.types.import_config import UserEventInputConfig -from google.cloud.retail_v2beta.types.prediction_service import PredictRequest -from google.cloud.retail_v2beta.types.prediction_service import PredictResponse -from google.cloud.retail_v2beta.types.product import Product -from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesMetadata -from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesRequest -from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesResponse -from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesMetadata -from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesRequest -from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesResponse -from google.cloud.retail_v2beta.types.product_service import CreateProductRequest -from google.cloud.retail_v2beta.types.product_service import DeleteProductRequest -from google.cloud.retail_v2beta.types.product_service import GetProductRequest -from google.cloud.retail_v2beta.types.product_service import ListProductsRequest -from google.cloud.retail_v2beta.types.product_service import ListProductsResponse -from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesMetadata -from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesRequest -from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesResponse -from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesMetadata -from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesRequest -from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesResponse -from google.cloud.retail_v2beta.types.product_service import SetInventoryMetadata -from google.cloud.retail_v2beta.types.product_service import SetInventoryRequest -from google.cloud.retail_v2beta.types.product_service import SetInventoryResponse -from google.cloud.retail_v2beta.types.product_service import UpdateProductRequest -from google.cloud.retail_v2beta.types.promotion import Promotion -from google.cloud.retail_v2beta.types.purge_config import PurgeMetadata -from google.cloud.retail_v2beta.types.purge_config import PurgeUserEventsRequest -from google.cloud.retail_v2beta.types.purge_config import PurgeUserEventsResponse -from google.cloud.retail_v2beta.types.search_service import SearchRequest -from google.cloud.retail_v2beta.types.search_service import SearchResponse -from google.cloud.retail_v2beta.types.serving_config import ServingConfig -from google.cloud.retail_v2beta.types.serving_config_service import AddControlRequest -from google.cloud.retail_v2beta.types.serving_config_service import CreateServingConfigRequest -from google.cloud.retail_v2beta.types.serving_config_service import DeleteServingConfigRequest -from google.cloud.retail_v2beta.types.serving_config_service import GetServingConfigRequest -from google.cloud.retail_v2beta.types.serving_config_service import ListServingConfigsRequest -from google.cloud.retail_v2beta.types.serving_config_service import ListServingConfigsResponse -from google.cloud.retail_v2beta.types.serving_config_service import RemoveControlRequest -from google.cloud.retail_v2beta.types.serving_config_service import UpdateServingConfigRequest -from google.cloud.retail_v2beta.types.user_event import CompletionDetail -from google.cloud.retail_v2beta.types.user_event import ProductDetail -from google.cloud.retail_v2beta.types.user_event import PurchaseTransaction -from google.cloud.retail_v2beta.types.user_event import UserEvent -from google.cloud.retail_v2beta.types.user_event_service import CollectUserEventRequest -from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsMetadata -from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsRequest -from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsResponse -from google.cloud.retail_v2beta.types.user_event_service import WriteUserEventRequest - -__all__ = ('CatalogServiceClient', - 'CatalogServiceAsyncClient', - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', - 'ControlServiceClient', - 'ControlServiceAsyncClient', - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', - 'ProductServiceClient', - 'ProductServiceAsyncClient', - 'SearchServiceClient', - 'SearchServiceAsyncClient', - 'ServingConfigServiceClient', - 'ServingConfigServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'AttributesConfig', - 'Catalog', - 'CatalogAttribute', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'ProductLevelConfig', - 'AddCatalogAttributeRequest', - 'GetAttributesConfigRequest', - 'GetCompletionConfigRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - 'SetDefaultBranchRequest', - 'UpdateAttributesConfigRequest', - 'UpdateCatalogRequest', - 'UpdateCompletionConfigRequest', - 'Audience', - 'ColorInfo', - 'Condition', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'Rule', - 'UserInfo', - 'AttributeConfigLevel', - 'SearchSolutionUseCase', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Control', - 'CreateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - 'UpdateControlRequest', - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'ServingConfig', - 'AddControlRequest', - 'CreateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'RemoveControlRequest', - 'UpdateServingConfigRequest', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail/py.typed b/owl-bot-staging/v2beta/google/cloud/retail/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py deleted file mode 100644 index 3ad83ab4..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py +++ /dev/null @@ -1,276 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.catalog_service import CatalogServiceClient -from .services.catalog_service import CatalogServiceAsyncClient -from .services.completion_service import CompletionServiceClient -from .services.completion_service import CompletionServiceAsyncClient -from .services.control_service import ControlServiceClient -from .services.control_service import ControlServiceAsyncClient -from .services.prediction_service import PredictionServiceClient -from .services.prediction_service import PredictionServiceAsyncClient -from .services.product_service import ProductServiceClient -from .services.product_service import ProductServiceAsyncClient -from .services.search_service import SearchServiceClient -from .services.search_service import SearchServiceAsyncClient -from .services.serving_config_service import ServingConfigServiceClient -from .services.serving_config_service import ServingConfigServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.catalog import AttributesConfig -from .types.catalog import Catalog -from .types.catalog import CatalogAttribute -from .types.catalog import CompletionConfig -from .types.catalog import MerchantCenterLink -from .types.catalog import MerchantCenterLinkingConfig -from .types.catalog import ProductLevelConfig -from .types.catalog_service import AddCatalogAttributeRequest -from .types.catalog_service import GetAttributesConfigRequest -from .types.catalog_service import GetCompletionConfigRequest -from .types.catalog_service import GetDefaultBranchRequest -from .types.catalog_service import GetDefaultBranchResponse -from .types.catalog_service import ListCatalogsRequest -from .types.catalog_service import ListCatalogsResponse -from .types.catalog_service import RemoveCatalogAttributeRequest -from .types.catalog_service import ReplaceCatalogAttributeRequest -from .types.catalog_service import SetDefaultBranchRequest -from .types.catalog_service import UpdateAttributesConfigRequest -from .types.catalog_service import UpdateCatalogRequest -from .types.catalog_service import UpdateCompletionConfigRequest -from .types.common import Audience -from .types.common import ColorInfo -from .types.common import Condition -from .types.common import CustomAttribute -from .types.common import FulfillmentInfo -from .types.common import Image -from .types.common import Interval -from .types.common import LocalInventory -from .types.common import PriceInfo -from .types.common import Rating -from .types.common import Rule -from .types.common import UserInfo -from .types.common import AttributeConfigLevel -from .types.common import SearchSolutionUseCase -from .types.common import SolutionType -from .types.completion_service import CompleteQueryRequest -from .types.completion_service import CompleteQueryResponse -from .types.control import Control -from .types.control_service import CreateControlRequest -from .types.control_service import DeleteControlRequest -from .types.control_service import GetControlRequest -from .types.control_service import ListControlsRequest -from .types.control_service import ListControlsResponse -from .types.control_service import UpdateControlRequest -from .types.export_config import ExportErrorsConfig -from .types.export_config import ExportMetadata -from .types.export_config import ExportProductsResponse -from .types.export_config import ExportUserEventsResponse -from .types.import_config import BigQuerySource -from .types.import_config import CompletionDataInputConfig -from .types.import_config import GcsSource -from .types.import_config import ImportCompletionDataRequest -from .types.import_config import ImportCompletionDataResponse -from .types.import_config import ImportErrorsConfig -from .types.import_config import ImportMetadata -from .types.import_config import ImportProductsRequest -from .types.import_config import ImportProductsResponse -from .types.import_config import ImportUserEventsRequest -from .types.import_config import ImportUserEventsResponse -from .types.import_config import ProductInlineSource -from .types.import_config import ProductInputConfig -from .types.import_config import UserEventImportSummary -from .types.import_config import UserEventInlineSource -from .types.import_config import UserEventInputConfig -from .types.prediction_service import PredictRequest -from .types.prediction_service import PredictResponse -from .types.product import Product -from .types.product_service import AddFulfillmentPlacesMetadata -from .types.product_service import AddFulfillmentPlacesRequest -from .types.product_service import AddFulfillmentPlacesResponse -from .types.product_service import AddLocalInventoriesMetadata -from .types.product_service import AddLocalInventoriesRequest -from .types.product_service import AddLocalInventoriesResponse -from .types.product_service import CreateProductRequest -from .types.product_service import DeleteProductRequest -from .types.product_service import GetProductRequest -from .types.product_service import ListProductsRequest -from .types.product_service import ListProductsResponse -from .types.product_service import RemoveFulfillmentPlacesMetadata -from .types.product_service import RemoveFulfillmentPlacesRequest -from .types.product_service import RemoveFulfillmentPlacesResponse -from .types.product_service import RemoveLocalInventoriesMetadata -from .types.product_service import RemoveLocalInventoriesRequest -from .types.product_service import RemoveLocalInventoriesResponse -from .types.product_service import SetInventoryMetadata -from .types.product_service import SetInventoryRequest -from .types.product_service import SetInventoryResponse -from .types.product_service import UpdateProductRequest -from .types.promotion import Promotion -from .types.purge_config import PurgeMetadata -from .types.purge_config import PurgeUserEventsRequest -from .types.purge_config import PurgeUserEventsResponse -from .types.search_service import SearchRequest -from .types.search_service import SearchResponse -from .types.serving_config import ServingConfig -from .types.serving_config_service import AddControlRequest -from .types.serving_config_service import CreateServingConfigRequest -from .types.serving_config_service import DeleteServingConfigRequest -from .types.serving_config_service import GetServingConfigRequest -from .types.serving_config_service import ListServingConfigsRequest -from .types.serving_config_service import ListServingConfigsResponse -from .types.serving_config_service import RemoveControlRequest -from .types.serving_config_service import UpdateServingConfigRequest -from .types.user_event import CompletionDetail -from .types.user_event import ProductDetail -from .types.user_event import PurchaseTransaction -from .types.user_event import UserEvent -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import RejoinUserEventsMetadata -from .types.user_event_service import RejoinUserEventsRequest -from .types.user_event_service import RejoinUserEventsResponse -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CatalogServiceAsyncClient', - 'CompletionServiceAsyncClient', - 'ControlServiceAsyncClient', - 'PredictionServiceAsyncClient', - 'ProductServiceAsyncClient', - 'SearchServiceAsyncClient', - 'ServingConfigServiceAsyncClient', - 'UserEventServiceAsyncClient', -'AddCatalogAttributeRequest', -'AddControlRequest', -'AddFulfillmentPlacesMetadata', -'AddFulfillmentPlacesRequest', -'AddFulfillmentPlacesResponse', -'AddLocalInventoriesMetadata', -'AddLocalInventoriesRequest', -'AddLocalInventoriesResponse', -'AttributeConfigLevel', -'AttributesConfig', -'Audience', -'BigQuerySource', -'Catalog', -'CatalogAttribute', -'CatalogServiceClient', -'CollectUserEventRequest', -'ColorInfo', -'CompleteQueryRequest', -'CompleteQueryResponse', -'CompletionConfig', -'CompletionDataInputConfig', -'CompletionDetail', -'CompletionServiceClient', -'Condition', -'Control', -'ControlServiceClient', -'CreateControlRequest', -'CreateProductRequest', -'CreateServingConfigRequest', -'CustomAttribute', -'DeleteControlRequest', -'DeleteProductRequest', -'DeleteServingConfigRequest', -'ExportErrorsConfig', -'ExportMetadata', -'ExportProductsResponse', -'ExportUserEventsResponse', -'FulfillmentInfo', -'GcsSource', -'GetAttributesConfigRequest', -'GetCompletionConfigRequest', -'GetControlRequest', -'GetDefaultBranchRequest', -'GetDefaultBranchResponse', -'GetProductRequest', -'GetServingConfigRequest', -'Image', -'ImportCompletionDataRequest', -'ImportCompletionDataResponse', -'ImportErrorsConfig', -'ImportMetadata', -'ImportProductsRequest', -'ImportProductsResponse', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'Interval', -'ListCatalogsRequest', -'ListCatalogsResponse', -'ListControlsRequest', -'ListControlsResponse', -'ListProductsRequest', -'ListProductsResponse', -'ListServingConfigsRequest', -'ListServingConfigsResponse', -'LocalInventory', -'MerchantCenterLink', -'MerchantCenterLinkingConfig', -'PredictRequest', -'PredictResponse', -'PredictionServiceClient', -'PriceInfo', -'Product', -'ProductDetail', -'ProductInlineSource', -'ProductInputConfig', -'ProductLevelConfig', -'ProductServiceClient', -'Promotion', -'PurchaseTransaction', -'PurgeMetadata', -'PurgeUserEventsRequest', -'PurgeUserEventsResponse', -'Rating', -'RejoinUserEventsMetadata', -'RejoinUserEventsRequest', -'RejoinUserEventsResponse', -'RemoveCatalogAttributeRequest', -'RemoveControlRequest', -'RemoveFulfillmentPlacesMetadata', -'RemoveFulfillmentPlacesRequest', -'RemoveFulfillmentPlacesResponse', -'RemoveLocalInventoriesMetadata', -'RemoveLocalInventoriesRequest', -'RemoveLocalInventoriesResponse', -'ReplaceCatalogAttributeRequest', -'Rule', -'SearchRequest', -'SearchResponse', -'SearchServiceClient', -'SearchSolutionUseCase', -'ServingConfig', -'ServingConfigServiceClient', -'SetDefaultBranchRequest', -'SetInventoryMetadata', -'SetInventoryRequest', -'SetInventoryResponse', -'SolutionType', -'UpdateAttributesConfigRequest', -'UpdateCatalogRequest', -'UpdateCompletionConfigRequest', -'UpdateControlRequest', -'UpdateProductRequest', -'UpdateServingConfigRequest', -'UserEvent', -'UserEventImportSummary', -'UserEventInlineSource', -'UserEventInputConfig', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json deleted file mode 100644 index bf3205b9..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json +++ /dev/null @@ -1,551 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.retail_v2beta", - "protoPackage": "google.cloud.retail.v2beta", - "schema": "1.0", - "services": { - "CatalogService": { - "clients": { - "grpc": { - "libraryClient": "CatalogServiceClient", - "rpcs": { - "AddCatalogAttribute": { - "methods": [ - "add_catalog_attribute" - ] - }, - "GetAttributesConfig": { - "methods": [ - "get_attributes_config" - ] - }, - "GetCompletionConfig": { - "methods": [ - "get_completion_config" - ] - }, - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "RemoveCatalogAttribute": { - "methods": [ - "remove_catalog_attribute" - ] - }, - "ReplaceCatalogAttribute": { - "methods": [ - "replace_catalog_attribute" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateAttributesConfig": { - "methods": [ - "update_attributes_config" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - }, - "UpdateCompletionConfig": { - "methods": [ - "update_completion_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CatalogServiceAsyncClient", - "rpcs": { - "AddCatalogAttribute": { - "methods": [ - "add_catalog_attribute" - ] - }, - "GetAttributesConfig": { - "methods": [ - "get_attributes_config" - ] - }, - "GetCompletionConfig": { - "methods": [ - "get_completion_config" - ] - }, - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "RemoveCatalogAttribute": { - "methods": [ - "remove_catalog_attribute" - ] - }, - "ReplaceCatalogAttribute": { - "methods": [ - "replace_catalog_attribute" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateAttributesConfig": { - "methods": [ - "update_attributes_config" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - }, - "UpdateCompletionConfig": { - "methods": [ - "update_completion_config" - ] - } - } - } - } - }, - "CompletionService": { - "clients": { - "grpc": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CompletionServiceAsyncClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - } - } - }, - "ControlService": { - "clients": { - "grpc": { - "libraryClient": "ControlServiceClient", - "rpcs": { - "CreateControl": { - "methods": [ - "create_control" - ] - }, - "DeleteControl": { - "methods": [ - "delete_control" - ] - }, - "GetControl": { - "methods": [ - "get_control" - ] - }, - "ListControls": { - "methods": [ - "list_controls" - ] - }, - "UpdateControl": { - "methods": [ - "update_control" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ControlServiceAsyncClient", - "rpcs": { - "CreateControl": { - "methods": [ - "create_control" - ] - }, - "DeleteControl": { - "methods": [ - "delete_control" - ] - }, - "GetControl": { - "methods": [ - "get_control" - ] - }, - "ListControls": { - "methods": [ - "list_controls" - ] - }, - "UpdateControl": { - "methods": [ - "update_control" - ] - } - } - } - } - }, - "PredictionService": { - "clients": { - "grpc": { - "libraryClient": "PredictionServiceClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PredictionServiceAsyncClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - } - } - }, - "ProductService": { - "clients": { - "grpc": { - "libraryClient": "ProductServiceClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProductServiceAsyncClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - } - } - }, - "SearchService": { - "clients": { - "grpc": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SearchServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - }, - "ServingConfigService": { - "clients": { - "grpc": { - "libraryClient": "ServingConfigServiceClient", - "rpcs": { - "AddControl": { - "methods": [ - "add_control" - ] - }, - "CreateServingConfig": { - "methods": [ - "create_serving_config" - ] - }, - "DeleteServingConfig": { - "methods": [ - "delete_serving_config" - ] - }, - "GetServingConfig": { - "methods": [ - "get_serving_config" - ] - }, - "ListServingConfigs": { - "methods": [ - "list_serving_configs" - ] - }, - "RemoveControl": { - "methods": [ - "remove_control" - ] - }, - "UpdateServingConfig": { - "methods": [ - "update_serving_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ServingConfigServiceAsyncClient", - "rpcs": { - "AddControl": { - "methods": [ - "add_control" - ] - }, - "CreateServingConfig": { - "methods": [ - "create_serving_config" - ] - }, - "DeleteServingConfig": { - "methods": [ - "delete_serving_config" - ] - }, - "GetServingConfig": { - "methods": [ - "get_serving_config" - ] - }, - "ListServingConfigs": { - "methods": [ - "list_serving_configs" - ] - }, - "RemoveControl": { - "methods": [ - "remove_control" - ] - }, - "UpdateServingConfig": { - "methods": [ - "update_serving_config" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py deleted file mode 100644 index d276b897..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CatalogServiceClient -from .async_client import CatalogServiceAsyncClient - -__all__ = ( - 'CatalogServiceClient', - 'CatalogServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py deleted file mode 100644 index dfff033b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py +++ /dev/null @@ -1,1350 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.catalog_service import pagers -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport -from .client import CatalogServiceClient - - -class CatalogServiceAsyncClient: - """Service for managing catalog configuration.""" - - _client: CatalogServiceClient - - DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT - - attributes_config_path = staticmethod(CatalogServiceClient.attributes_config_path) - parse_attributes_config_path = staticmethod(CatalogServiceClient.parse_attributes_config_path) - branch_path = staticmethod(CatalogServiceClient.branch_path) - parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) - catalog_path = staticmethod(CatalogServiceClient.catalog_path) - parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) - completion_config_path = staticmethod(CatalogServiceClient.completion_config_path) - parse_completion_config_path = staticmethod(CatalogServiceClient.parse_completion_config_path) - common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CatalogServiceClient.common_project_path) - parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) - common_location_path = staticmethod(CatalogServiceClient.common_location_path) - parse_common_location_path = staticmethod(CatalogServiceClient.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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CatalogServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsAsyncPager: - r"""Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_list_catalogs(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - parent (:class:`str`): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2beta.Catalog]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.retail_v2beta.services.catalog_service.pagers.ListCatalogsAsyncPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.ListCatalogsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_catalogs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCatalogsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_catalog(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2beta.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2beta.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] - method. - catalog (:class:`google.cloud.retail_v2beta.types.Catalog`): - Required. The - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2beta.Catalog], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Catalog][google.cloud.retail.v2beta.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCatalogRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_catalog, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_set_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (:class:`str`): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.SetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (:class:`str`): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # 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_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_completion_config(self, - request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Gets a - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] - method. - name (:class:`str`): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - - 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.retail_v2beta.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetCompletionConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_completion_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_completion_config(self, - request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, - *, - completion_config: catalog.CompletionConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Updates the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - completion_config = retail_v2beta.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2beta.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = await client.update_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] - method. - completion_config (:class:`google.cloud.retail_v2beta.types.CompletionConfig`): - Required. The - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``completion_config`` 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 - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([completion_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCompletionConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if completion_config is not None: - request.completion_config = completion_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_completion_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("completion_config.name", request.completion_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_attributes_config(self, - request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Gets an - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] - method. - name (:class:`str`): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - - 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.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetAttributesConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_attributes_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_attributes_config(self, - request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, - *, - attributes_config: catalog.AttributesConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Updates the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - attributes_config = retail_v2beta.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2beta.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = await client.update_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] - method. - attributes_config (:class:`google.cloud.retail_v2beta.types.AttributesConfig`): - Required. The - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. - - This corresponds to the ``attributes_config`` 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 - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([attributes_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateAttributesConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attributes_config is not None: - request.attributes_config = attributes_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_attributes_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config.name", request.attributes_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def add_catalog_attribute(self, - request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Adds the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_add_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.AddCatalogAttributeRequest(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.add_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def remove_catalog_attribute(self, - request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Removes the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = await client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.RemoveCatalogAttributeRequest(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.remove_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def replace_catalog_attribute(self, - request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Replaces the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.ReplaceCatalogAttributeRequest(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.replace_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py deleted file mode 100644 index bae42088..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py +++ /dev/null @@ -1,1579 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.catalog_service import pagers -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CatalogServiceGrpcTransport -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -class CatalogServiceClientMeta(type): - """Metaclass for the CatalogService 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[CatalogServiceTransport]] - _transport_registry["grpc"] = CatalogServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CatalogServiceTransport]: - """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): - """Service for managing catalog configuration.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CatalogServiceClient: 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: - CatalogServiceClient: 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) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def attributes_config_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified attributes_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_attributes_config_path(path: str) -> Dict[str,str]: - """Parses a attributes_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/attributesConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def completion_config_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified completion_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_completion_config_path(path: str) -> Dict[str,str]: - """Parses a completion_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/completionConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CatalogServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CatalogServiceTransport): - # transport is a CatalogServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsPager: - r"""Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_list_catalogs(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2beta.Catalog]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.retail_v2beta.services.catalog_service.pagers.ListCatalogsPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ListCatalogsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ListCatalogsRequest): - request = catalog_service.ListCatalogsRequest(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_catalogs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCatalogsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_catalog(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2beta.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2beta.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] - method. - catalog (google.cloud.retail_v2beta.types.Catalog): - Required. The - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2beta.Catalog], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Catalog][google.cloud.retail.v2beta.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCatalogRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCatalogRequest): - request = catalog_service.UpdateCatalogRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - 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_catalog] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_set_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.SetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.SetDefaultBranchRequest): - request = catalog_service.SetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetDefaultBranchRequest): - request = catalog_service.GetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_completion_config(self, - request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Gets a - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] - method. - name (str): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - - 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.retail_v2beta.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetCompletionConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetCompletionConfigRequest): - request = catalog_service.GetCompletionConfigRequest(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_completion_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_completion_config(self, - request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, - *, - completion_config: catalog.CompletionConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Updates the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - completion_config = retail_v2beta.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2beta.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = client.update_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] - method. - completion_config (google.cloud.retail_v2beta.types.CompletionConfig): - Required. The - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``completion_config`` 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 - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([completion_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCompletionConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCompletionConfigRequest): - request = catalog_service.UpdateCompletionConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if completion_config is not None: - request.completion_config = completion_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_completion_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("completion_config.name", request.completion_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_attributes_config(self, - request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Gets an - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] - method. - name (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - - 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.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetAttributesConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetAttributesConfigRequest): - request = catalog_service.GetAttributesConfigRequest(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_attributes_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_attributes_config(self, - request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, - *, - attributes_config: catalog.AttributesConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Updates the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - attributes_config = retail_v2beta.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2beta.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = client.update_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] - method. - attributes_config (google.cloud.retail_v2beta.types.AttributesConfig): - Required. The - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. - - This corresponds to the ``attributes_config`` 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 - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([attributes_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateAttributesConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateAttributesConfigRequest): - request = catalog_service.UpdateAttributesConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attributes_config is not None: - request.attributes_config = attributes_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_attributes_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config.name", request.attributes_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def add_catalog_attribute(self, - request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Adds the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_add_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.AddCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.AddCatalogAttributeRequest): - request = catalog_service.AddCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def remove_catalog_attribute(self, - request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Removes the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.RemoveCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.RemoveCatalogAttributeRequest): - request = catalog_service.RemoveCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def replace_catalog_attribute(self, - request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Replaces the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ReplaceCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ReplaceCatalogAttributeRequest): - request = catalog_service.ReplaceCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.replace_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py deleted file mode 100644 index 0ca25546..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog_service - - -class ListCatalogsPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` - 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[..., catalog_service.ListCatalogsResponse], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2beta.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - for page in self.pages: - yield from page.catalogs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCatalogsAsyncPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` - 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[catalog_service.ListCatalogsResponse]], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2beta.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - async def async_generator(): - async for page in self.pages: - for response in page.catalogs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py deleted file mode 100644 index 0cffa336..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CatalogServiceTransport -from .grpc import CatalogServiceGrpcTransport -from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] -_transport_registry['grpc'] = CatalogServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport - -__all__ = ( - 'CatalogServiceTransport', - 'CatalogServiceGrpcTransport', - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py deleted file mode 100644 index dfced0db..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py +++ /dev/null @@ -1,293 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CatalogServiceTransport(abc.ABC): - """Abstract transport class for CatalogService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_catalogs: gapic_v1.method.wrap_method( - self.list_catalogs, - default_timeout=None, - client_info=client_info, - ), - self.update_catalog: gapic_v1.method.wrap_method( - self.update_catalog, - default_timeout=None, - client_info=client_info, - ), - self.set_default_branch: gapic_v1.method.wrap_method( - self.set_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_default_branch: gapic_v1.method.wrap_method( - self.get_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_completion_config: gapic_v1.method.wrap_method( - self.get_completion_config, - default_timeout=None, - client_info=client_info, - ), - self.update_completion_config: gapic_v1.method.wrap_method( - self.update_completion_config, - default_timeout=None, - client_info=client_info, - ), - self.get_attributes_config: gapic_v1.method.wrap_method( - self.get_attributes_config, - default_timeout=None, - client_info=client_info, - ), - self.update_attributes_config: gapic_v1.method.wrap_method( - self.update_attributes_config, - default_timeout=None, - client_info=client_info, - ), - self.add_catalog_attribute: gapic_v1.method.wrap_method( - self.add_catalog_attribute, - default_timeout=None, - client_info=client_info, - ), - self.remove_catalog_attribute: gapic_v1.method.wrap_method( - self.remove_catalog_attribute, - default_timeout=None, - client_info=client_info, - ), - self.replace_catalog_attribute: gapic_v1.method.wrap_method( - self.replace_catalog_attribute, - 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Union[ - catalog_service.ListCatalogsResponse, - Awaitable[catalog_service.ListCatalogsResponse] - ]]: - raise NotImplementedError() - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Union[ - gcr_catalog.Catalog, - Awaitable[gcr_catalog.Catalog] - ]]: - raise NotImplementedError() - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Union[ - catalog_service.GetDefaultBranchResponse, - Awaitable[catalog_service.GetDefaultBranchResponse] - ]]: - raise NotImplementedError() - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - Union[ - catalog.CompletionConfig, - Awaitable[catalog.CompletionConfig] - ]]: - raise NotImplementedError() - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - Union[ - catalog.CompletionConfig, - Awaitable[catalog.CompletionConfig] - ]]: - raise NotImplementedError() - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CatalogServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py deleted file mode 100644 index 0f431d97..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py +++ /dev/null @@ -1,598 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO - - -class CatalogServiceGrpcTransport(CatalogServiceTransport): - """gRPC backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - catalog_service.ListCatalogsResponse]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - ~.ListCatalogsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - gcr_catalog.Catalog]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - ~.Catalog]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - empty_pb2.Empty]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - ~.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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - catalog_service.GetDefaultBranchResponse]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - ~.GetDefaultBranchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - catalog.CompletionConfig]: - r"""Return a callable for the get completion config method over gRPC. - - Gets a - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. - - Returns: - Callable[[~.GetCompletionConfigRequest], - ~.CompletionConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetCompletionConfig', - request_serializer=catalog_service.GetCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['get_completion_config'] - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - catalog.CompletionConfig]: - r"""Return a callable for the update completion config method over gRPC. - - Updates the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. - - Returns: - Callable[[~.UpdateCompletionConfigRequest], - ~.CompletionConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateCompletionConfig', - request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['update_completion_config'] - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - catalog.AttributesConfig]: - r"""Return a callable for the get attributes config method over gRPC. - - Gets an - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - Returns: - Callable[[~.GetAttributesConfigRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetAttributesConfig', - request_serializer=catalog_service.GetAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['get_attributes_config'] - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - catalog.AttributesConfig]: - r"""Return a callable for the update attributes config method over gRPC. - - Updates the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - Returns: - Callable[[~.UpdateAttributesConfigRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateAttributesConfig', - request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['update_attributes_config'] - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the add catalog attribute method over gRPC. - - Adds the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.AddCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_catalog_attribute' not in self._stubs: - self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/AddCatalogAttribute', - request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['add_catalog_attribute'] - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the remove catalog attribute method over gRPC. - - Removes the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.RemoveCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_catalog_attribute' not in self._stubs: - self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/RemoveCatalogAttribute', - request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['remove_catalog_attribute'] - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the replace catalog attribute method over gRPC. - - Replaces the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.ReplaceCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_catalog_attribute' not in self._stubs: - self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/ReplaceCatalogAttribute', - request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['replace_catalog_attribute'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CatalogServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py deleted file mode 100644 index ca9f808e..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,597 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CatalogServiceGrpcTransport - - -class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): - """gRPC AsyncIO backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Awaitable[catalog_service.ListCatalogsResponse]]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - Awaitable[~.ListCatalogsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Awaitable[gcr_catalog.Catalog]]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - Awaitable[~.Catalog]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - 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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Awaitable[catalog_service.GetDefaultBranchResponse]]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - Awaitable[~.GetDefaultBranchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - Awaitable[catalog.CompletionConfig]]: - r"""Return a callable for the get completion config method over gRPC. - - Gets a - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. - - Returns: - Callable[[~.GetCompletionConfigRequest], - Awaitable[~.CompletionConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetCompletionConfig', - request_serializer=catalog_service.GetCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['get_completion_config'] - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - Awaitable[catalog.CompletionConfig]]: - r"""Return a callable for the update completion config method over gRPC. - - Updates the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. - - Returns: - Callable[[~.UpdateCompletionConfigRequest], - Awaitable[~.CompletionConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateCompletionConfig', - request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['update_completion_config'] - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the get attributes config method over gRPC. - - Gets an - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - Returns: - Callable[[~.GetAttributesConfigRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetAttributesConfig', - request_serializer=catalog_service.GetAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['get_attributes_config'] - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the update attributes config method over gRPC. - - Updates the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - Returns: - Callable[[~.UpdateAttributesConfigRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateAttributesConfig', - request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['update_attributes_config'] - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the add catalog attribute method over gRPC. - - Adds the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.AddCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_catalog_attribute' not in self._stubs: - self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/AddCatalogAttribute', - request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['add_catalog_attribute'] - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the remove catalog attribute method over gRPC. - - Removes the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.RemoveCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_catalog_attribute' not in self._stubs: - self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/RemoveCatalogAttribute', - request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['remove_catalog_attribute'] - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the replace catalog attribute method over gRPC. - - Replaces the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.ReplaceCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_catalog_attribute' not in self._stubs: - self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/ReplaceCatalogAttribute', - request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['replace_catalog_attribute'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py deleted file mode 100644 index b8af95bd..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CompletionServiceClient -from .async_client import CompletionServiceAsyncClient - -__all__ = ( - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py deleted file mode 100644 index 66c91320..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py +++ /dev/null @@ -1,391 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .client import CompletionServiceClient - - -class CompletionServiceAsyncClient: - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: CompletionServiceClient - - DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(CompletionServiceClient.catalog_path) - parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) - common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CompletionServiceClient.common_project_path) - parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) - common_location_path = staticmethod(CompletionServiceClient.common_location_path) - parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CompletionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_complete_query(): - # Create a client - client = retail_v2beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.complete_query, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_import_completion_data(): - # Create a client - client = retail_v2beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2beta.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. - 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. - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_completion_data, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py deleted file mode 100644 index 9652a4f0..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py +++ /dev/null @@ -1,592 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CompletionServiceGrpcTransport -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -class CompletionServiceClientMeta(type): - """Metaclass for the CompletionService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] - _transport_registry["grpc"] = CompletionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CompletionServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class CompletionServiceClient(metaclass=CompletionServiceClientMeta): - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CompletionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CompletionServiceTransport): - # transport is a CompletionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_complete_query(): - # Create a client - client = retail_v2beta.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a completion_service.CompleteQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, completion_service.CompleteQueryRequest): - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_import_completion_data(): - # Create a client - client = retail_v2beta.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2beta.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. - 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. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportCompletionDataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportCompletionDataRequest): - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_completion_data] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py deleted file mode 100644 index a0c9542f..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CompletionServiceTransport -from .grpc import CompletionServiceGrpcTransport -from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] -_transport_registry['grpc'] = CompletionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport - -__all__ = ( - 'CompletionServiceTransport', - 'CompletionServiceGrpcTransport', - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py deleted file mode 100644 index 464b0bad..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py +++ /dev/null @@ -1,172 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CompletionServiceTransport(abc.ABC): - """Abstract transport class for CompletionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.complete_query: gapic_v1.method.wrap_method( - self.complete_query, - default_timeout=None, - client_info=client_info, - ), - self.import_completion_data: gapic_v1.method.wrap_method( - self.import_completion_data, - 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Union[ - completion_service.CompleteQueryResponse, - Awaitable[completion_service.CompleteQueryResponse] - ]]: - raise NotImplementedError() - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CompletionServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py deleted file mode 100644 index 916e8bec..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py +++ /dev/null @@ -1,323 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO - - -class CompletionServiceGrpcTransport(CompletionServiceTransport): - """gRPC backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - ~.CompleteQueryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - operations_pb2.Operation]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CompletionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py deleted file mode 100644 index b8d0ffbd..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,322 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CompletionServiceGrpcTransport - - -class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): - """gRPC AsyncIO backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Awaitable[completion_service.CompleteQueryResponse]]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - Awaitable[~.CompleteQueryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - 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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py deleted file mode 100644 index e9a7be2f..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ControlServiceClient -from .async_client import ControlServiceAsyncClient - -__all__ = ( - 'ControlServiceClient', - 'ControlServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py deleted file mode 100644 index 5d3cfeb7..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py +++ /dev/null @@ -1,742 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.control_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.cloud.retail_v2beta.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport -from .client import ControlServiceClient - - -class ControlServiceAsyncClient: - """Service for modifying Control.""" - - _client: ControlServiceClient - - DEFAULT_ENDPOINT = ControlServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ControlServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(ControlServiceClient.catalog_path) - parse_catalog_path = staticmethod(ControlServiceClient.parse_catalog_path) - control_path = staticmethod(ControlServiceClient.control_path) - parse_control_path = staticmethod(ControlServiceClient.parse_control_path) - common_billing_account_path = staticmethod(ControlServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ControlServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ControlServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ControlServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ControlServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ControlServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ControlServiceClient.common_project_path) - parse_common_project_path = staticmethod(ControlServiceClient.parse_common_project_path) - common_location_path = staticmethod(ControlServiceClient.common_location_path) - parse_common_location_path = staticmethod(ControlServiceClient.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: - ControlServiceAsyncClient: The constructed client. - """ - return ControlServiceClient.from_service_account_info.__func__(ControlServiceAsyncClient, 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: - ControlServiceAsyncClient: The constructed client. - """ - return ControlServiceClient.from_service_account_file.__func__(ControlServiceAsyncClient, 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 variabel 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 ControlServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ControlServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ControlServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ControlServiceClient).get_transport_class, type(ControlServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ControlServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the control service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ControlServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ControlServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_control(self, - request: Union[control_service.CreateControlRequest, dict] = None, - *, - parent: str = None, - control: gcr_control.Control = None, - control_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Creates a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_create_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = await client.create_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateControlRequest, dict]): - The request object. Request for CreateControl method. - parent (:class:`str`): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control (:class:`google.cloud.retail_v2beta.types.Control`): - Required. The Control to create. - This corresponds to the ``control`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control_id (:class:`str`): - Required. The ID to use for the Control, which will - become the final component of the Control's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``control_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.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, control, control_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.CreateControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if control is not None: - request.control = control - if control_id is not None: - request.control_id = control_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_control(self, - request: Union[control_service.DeleteControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_delete_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteControlRequest( - name="name_value", - ) - - # Make the request - await client.delete_control(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteControlRequest, dict]): - The request object. Request for DeleteControl method. - name (:class:`str`): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.DeleteControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_control(self, - request: Union[control_service.UpdateControlRequest, dict] = None, - *, - control: gcr_control.Control = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Updates a Control. - - [Control][google.cloud.retail.v2beta.Control] cannot be set to a - different oneof field, if so an INVALID_ARGUMENT is returned. If - the [Control][google.cloud.retail.v2beta.Control] to delete does - not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateControlRequest( - control=control, - ) - - # Make the request - response = await client.update_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateControlRequest, dict]): - The request object. Request for UpdateControl method. - control (:class:`google.cloud.retail_v2beta.types.Control`): - Required. The Control to update. - This corresponds to the ``control`` 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 - [Control][google.cloud.retail.v2beta.Control] to update. - The following are NOT supported: - - - [Control.name][google.cloud.retail.v2beta.Control.name] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([control, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.UpdateControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if control is not None: - request.control = control - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("control.name", request.control.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_control(self, - request: Union[control_service.GetControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> control.Control: - r"""Gets a Control. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetControlRequest( - name="name_value", - ) - - # Make the request - response = await client.get_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetControlRequest, dict]): - The request object. Request for GetControl method. - name (:class:`str`): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.GetControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_controls(self, - request: Union[control_service.ListControlsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListControlsAsyncPager: - r"""Lists all Controls linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_list_controls(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListControlsRequest, dict]): - The request object. Request for ListControls method. - parent (:class:`str`): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.control_service.pagers.ListControlsAsyncPager: - Response for ListControls method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.ListControlsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_controls, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListControlsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ControlServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py deleted file mode 100644 index 39e7a70e..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py +++ /dev/null @@ -1,950 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.control_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.cloud.retail_v2beta.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ControlServiceGrpcTransport -from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport - - -class ControlServiceClientMeta(type): - """Metaclass for the ControlService 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[ControlServiceTransport]] - _transport_registry["grpc"] = ControlServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ControlServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ControlServiceTransport]: - """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 ControlServiceClient(metaclass=ControlServiceClientMeta): - """Service for modifying Control.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ControlServiceClient: 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: - ControlServiceClient: 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) -> ControlServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ControlServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def control_path(project: str,location: str,catalog: str,control: str,) -> str: - """Returns a fully-qualified control string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) - - @staticmethod - def parse_control_path(path: str) -> Dict[str,str]: - """Parses a control path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/controls/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ControlServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the control service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ControlServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ControlServiceTransport): - # transport is a ControlServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_control(self, - request: Union[control_service.CreateControlRequest, dict] = None, - *, - parent: str = None, - control: gcr_control.Control = None, - control_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Creates a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_create_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = client.create_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateControlRequest, dict]): - The request object. Request for CreateControl method. - parent (str): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control (google.cloud.retail_v2beta.types.Control): - Required. The Control to create. - This corresponds to the ``control`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control_id (str): - Required. The ID to use for the Control, which will - become the final component of the Control's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``control_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.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, control, control_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.CreateControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.CreateControlRequest): - request = control_service.CreateControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if control is not None: - request.control = control - if control_id is not None: - request.control_id = control_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_control(self, - request: Union[control_service.DeleteControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_delete_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteControlRequest( - name="name_value", - ) - - # Make the request - client.delete_control(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteControlRequest, dict]): - The request object. Request for DeleteControl method. - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.DeleteControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.DeleteControlRequest): - request = control_service.DeleteControlRequest(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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_control(self, - request: Union[control_service.UpdateControlRequest, dict] = None, - *, - control: gcr_control.Control = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Updates a Control. - - [Control][google.cloud.retail.v2beta.Control] cannot be set to a - different oneof field, if so an INVALID_ARGUMENT is returned. If - the [Control][google.cloud.retail.v2beta.Control] to delete does - not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateControlRequest( - control=control, - ) - - # Make the request - response = client.update_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateControlRequest, dict]): - The request object. Request for UpdateControl method. - control (google.cloud.retail_v2beta.types.Control): - Required. The Control to update. - This corresponds to the ``control`` 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 - [Control][google.cloud.retail.v2beta.Control] to update. - The following are NOT supported: - - - [Control.name][google.cloud.retail.v2beta.Control.name] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([control, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.UpdateControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.UpdateControlRequest): - request = control_service.UpdateControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if control is not None: - request.control = control - 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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("control.name", request.control.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_control(self, - request: Union[control_service.GetControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> control.Control: - r"""Gets a Control. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetControlRequest( - name="name_value", - ) - - # Make the request - response = client.get_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetControlRequest, dict]): - The request object. Request for GetControl method. - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.GetControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.GetControlRequest): - request = control_service.GetControlRequest(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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_controls(self, - request: Union[control_service.ListControlsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListControlsPager: - r"""Lists all Controls linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_list_controls(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListControlsRequest, dict]): - The request object. Request for ListControls method. - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.control_service.pagers.ListControlsPager: - Response for ListControls method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.ListControlsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.ListControlsRequest): - request = control_service.ListControlsRequest(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_controls] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListControlsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ControlServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py deleted file mode 100644 index f51a3970..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control_service - - -class ListControlsPager: - """A pager for iterating through ``list_controls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListControlsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``controls`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListControls`` requests and continue to iterate - through the ``controls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListControlsResponse` - 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[..., control_service.ListControlsResponse], - request: control_service.ListControlsRequest, - response: control_service.ListControlsResponse, - *, - 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.retail_v2beta.types.ListControlsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListControlsResponse): - 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 = control_service.ListControlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[control_service.ListControlsResponse]: - 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[control.Control]: - for page in self.pages: - yield from page.controls - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListControlsAsyncPager: - """A pager for iterating through ``list_controls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListControlsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``controls`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListControls`` requests and continue to iterate - through the ``controls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListControlsResponse` - 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[control_service.ListControlsResponse]], - request: control_service.ListControlsRequest, - response: control_service.ListControlsResponse, - *, - 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.retail_v2beta.types.ListControlsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListControlsResponse): - 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 = control_service.ListControlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[control_service.ListControlsResponse]: - 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[control.Control]: - async def async_generator(): - async for page in self.pages: - for response in page.controls: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py deleted file mode 100644 index 3622876b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ControlServiceTransport -from .grpc import ControlServiceGrpcTransport -from .grpc_asyncio import ControlServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ControlServiceTransport]] -_transport_registry['grpc'] = ControlServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ControlServiceGrpcAsyncIOTransport - -__all__ = ( - 'ControlServiceTransport', - 'ControlServiceGrpcTransport', - 'ControlServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py deleted file mode 100644 index 3c75d59f..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py +++ /dev/null @@ -1,209 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ControlServiceTransport(abc.ABC): - """Abstract transport class for ControlService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_control: gapic_v1.method.wrap_method( - self.create_control, - default_timeout=None, - client_info=client_info, - ), - self.delete_control: gapic_v1.method.wrap_method( - self.delete_control, - default_timeout=None, - client_info=client_info, - ), - self.update_control: gapic_v1.method.wrap_method( - self.update_control, - default_timeout=None, - client_info=client_info, - ), - self.get_control: gapic_v1.method.wrap_method( - self.get_control, - default_timeout=None, - client_info=client_info, - ), - self.list_controls: gapic_v1.method.wrap_method( - self.list_controls, - 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 create_control(self) -> Callable[ - [control_service.CreateControlRequest], - Union[ - gcr_control.Control, - Awaitable[gcr_control.Control] - ]]: - raise NotImplementedError() - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - Union[ - gcr_control.Control, - Awaitable[gcr_control.Control] - ]]: - raise NotImplementedError() - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - Union[ - control.Control, - Awaitable[control.Control] - ]]: - raise NotImplementedError() - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - Union[ - control_service.ListControlsResponse, - Awaitable[control_service.ListControlsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ControlServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py deleted file mode 100644 index 33482592..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py +++ /dev/null @@ -1,380 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO - - -class ControlServiceGrpcTransport(ControlServiceTransport): - """gRPC backend transport for ControlService. - - Service for modifying Control. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_control(self) -> Callable[ - [control_service.CreateControlRequest], - gcr_control.Control]: - r"""Return a callable for the create control method over gRPC. - - Creates a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['create_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/CreateControl', - request_serializer=control_service.CreateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['create_control'] - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete control method over gRPC. - - Deletes a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteControlRequest], - ~.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_control' not in self._stubs: - self._stubs['delete_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/DeleteControl', - request_serializer=control_service.DeleteControlRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_control'] - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - gcr_control.Control]: - r"""Return a callable for the update control method over gRPC. - - Updates a Control. - - [Control][google.cloud.retail.v2beta.Control] cannot be set to a - different oneof field, if so an INVALID_ARGUMENT is returned. If - the [Control][google.cloud.retail.v2beta.Control] to delete does - not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.UpdateControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['update_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/UpdateControl', - request_serializer=control_service.UpdateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['update_control'] - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - control.Control]: - r"""Return a callable for the get control method over gRPC. - - Gets a Control. - - Returns: - Callable[[~.GetControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['get_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/GetControl', - request_serializer=control_service.GetControlRequest.serialize, - response_deserializer=control.Control.deserialize, - ) - return self._stubs['get_control'] - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - control_service.ListControlsResponse]: - r"""Return a callable for the list controls method over gRPC. - - Lists all Controls linked to this catalog. - - Returns: - Callable[[~.ListControlsRequest], - ~.ListControlsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_controls' not in self._stubs: - self._stubs['list_controls'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/ListControls', - request_serializer=control_service.ListControlsRequest.serialize, - response_deserializer=control_service.ListControlsResponse.deserialize, - ) - return self._stubs['list_controls'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ControlServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py deleted file mode 100644 index 2696c131..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,379 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ControlServiceGrpcTransport - - -class ControlServiceGrpcAsyncIOTransport(ControlServiceTransport): - """gRPC AsyncIO backend transport for ControlService. - - Service for modifying Control. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_control(self) -> Callable[ - [control_service.CreateControlRequest], - Awaitable[gcr_control.Control]]: - r"""Return a callable for the create control method over gRPC. - - Creates a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['create_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/CreateControl', - request_serializer=control_service.CreateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['create_control'] - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete control method over gRPC. - - Deletes a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteControlRequest], - 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_control' not in self._stubs: - self._stubs['delete_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/DeleteControl', - request_serializer=control_service.DeleteControlRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_control'] - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - Awaitable[gcr_control.Control]]: - r"""Return a callable for the update control method over gRPC. - - Updates a Control. - - [Control][google.cloud.retail.v2beta.Control] cannot be set to a - different oneof field, if so an INVALID_ARGUMENT is returned. If - the [Control][google.cloud.retail.v2beta.Control] to delete does - not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.UpdateControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['update_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/UpdateControl', - request_serializer=control_service.UpdateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['update_control'] - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - Awaitable[control.Control]]: - r"""Return a callable for the get control method over gRPC. - - Gets a Control. - - Returns: - Callable[[~.GetControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['get_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/GetControl', - request_serializer=control_service.GetControlRequest.serialize, - response_deserializer=control.Control.deserialize, - ) - return self._stubs['get_control'] - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - Awaitable[control_service.ListControlsResponse]]: - r"""Return a callable for the list controls method over gRPC. - - Lists all Controls linked to this catalog. - - Returns: - Callable[[~.ListControlsRequest], - Awaitable[~.ListControlsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_controls' not in self._stubs: - self._stubs['list_controls'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/ListControls', - request_serializer=control_service.ListControlsRequest.serialize, - response_deserializer=control_service.ListControlsResponse.deserialize, - ) - return self._stubs['list_controls'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ControlServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py deleted file mode 100644 index 7c079c80..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import PredictionServiceClient -from .async_client import PredictionServiceAsyncClient - -__all__ = ( - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py deleted file mode 100644 index d8a1a148..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py +++ /dev/null @@ -1,279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport -from .client import PredictionServiceClient - - -class PredictionServiceAsyncClient: - """Service for making recommendation prediction.""" - - _client: PredictionServiceClient - - DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT - - product_path = staticmethod(PredictionServiceClient.product_path) - parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) - common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(PredictionServiceClient.common_project_path) - parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) - common_location_path = staticmethod(PredictionServiceClient.common_location_path) - parse_common_location_path = staticmethod(PredictionServiceClient.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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PredictionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_predict(): - # Create a client - client = retail_v2beta.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - request = prediction_service.PredictRequest(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.predict, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py deleted file mode 100644 index 458e6650..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py +++ /dev/null @@ -1,479 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PredictionServiceGrpcTransport -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -class PredictionServiceClientMeta(type): - """Metaclass for the PredictionService 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[PredictionServiceTransport]] - _transport_registry["grpc"] = PredictionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PredictionServiceTransport]: - """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): - """Service for making recommendation prediction.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PredictionServiceClient: 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: - PredictionServiceClient: 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) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, PredictionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, PredictionServiceTransport): - # transport is a PredictionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_predict(): - # Create a client - client = retail_v2beta.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a prediction_service.PredictRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_service.PredictRequest): - request = prediction_service.PredictRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.predict] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py deleted file mode 100644 index bb65c664..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PredictionServiceTransport -from .grpc import PredictionServiceGrpcTransport -from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] -_transport_registry['grpc'] = PredictionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport - -__all__ = ( - 'PredictionServiceTransport', - 'PredictionServiceGrpcTransport', - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py deleted file mode 100644 index d4f07f59..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PredictionServiceTransport(abc.ABC): - """Abstract transport class for PredictionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.predict: gapic_v1.method.wrap_method( - self.predict, - 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - Union[ - prediction_service.PredictResponse, - Awaitable[prediction_service.PredictResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PredictionServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py deleted file mode 100644 index 500a4a04..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py +++ /dev/null @@ -1,262 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO - - -class PredictionServiceGrpcTransport(PredictionServiceTransport): - """gRPC backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - prediction_service.PredictResponse]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - ~.PredictResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PredictionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py deleted file mode 100644 index 49d0872c..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,261 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import PredictionServiceGrpcTransport - - -class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): - """gRPC AsyncIO backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def predict(self) -> Callable[ - [prediction_service.PredictRequest], - Awaitable[prediction_service.PredictResponse]]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - Awaitable[~.PredictResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py deleted file mode 100644 index 0fa6330a..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ProductServiceClient -from .async_client import ProductServiceAsyncClient - -__all__ = ( - 'ProductServiceClient', - 'ProductServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py deleted file mode 100644 index 493936e0..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py +++ /dev/null @@ -1,1692 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.services.product_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.cloud.retail_v2beta.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport -from .client import ProductServiceClient - - -class ProductServiceAsyncClient: - """Service for ingesting [Product][google.cloud.retail.v2beta.Product] - information of the customer's website. - """ - - _client: ProductServiceClient - - DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(ProductServiceClient.branch_path) - parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) - product_path = staticmethod(ProductServiceClient.product_path) - parse_product_path = staticmethod(ProductServiceClient.parse_product_path) - common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProductServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProductServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ProductServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) - common_location_path = staticmethod(ProductServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProductServiceClient.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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ProductServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ProductServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_create_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (:class:`str`): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (:class:`google.cloud.retail_v2beta.types.Product`): - Required. The - [Product][google.cloud.retail.v2beta.Product] to create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (:class:`str`): - Required. The ID to use for the - [Product][google.cloud.retail.v2beta.Product], which - will become the final component of the - [Product.name][google.cloud.retail.v2beta.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This field must be unique among all - [Product][google.cloud.retail.v2beta.Product]s with the - same - [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.CreateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the requested - [Product][google.cloud.retail.v2beta.Product] 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.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.GetProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsAsyncPager: - r"""Gets a list of [Product][google.cloud.retail.v2beta.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_list_products(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - parent (:class:`str`): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2beta.Product]s under - this branch, regardless of whether or not this branch - exists, a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.product_service.pagers.ListProductsAsyncPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.ListProductsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_products, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProductsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (:class:`google.cloud.retail_v2beta.types.Product`): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2beta.Product] to update. - The immutable and output only fields are NOT supported. - If not set, all supported fields (the fields that are - neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.UpdateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_delete_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2beta.Product] to - delete can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product] member nor - a - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] with more - than one - [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2beta.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.DeleteProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2beta.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2beta.Product]s to be - successfully updated. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_import_products(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2beta.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2beta.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_set_inventory(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2beta.Product() - inventory.title = "title_value" - - request = retail_v2beta.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (:class:`google.cloud.retail_v2beta.types.Product`): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product] named in - [Product.name][google.cloud.retail.v2beta.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2beta.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2beta.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.SetInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_inventory, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - async def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [AddFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_add_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [AddLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_remove_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py deleted file mode 100644 index e048bbc8..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py +++ /dev/null @@ -1,1894 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.services.product_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.cloud.retail_v2beta.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProductServiceGrpcTransport -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -class ProductServiceClientMeta(type): - """Metaclass for the ProductService 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[ProductServiceTransport]] - _transport_registry["grpc"] = ProductServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ProductServiceTransport]: - """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 ProductServiceClient(metaclass=ProductServiceClientMeta): - """Service for ingesting [Product][google.cloud.retail.v2beta.Product] - information of the customer's website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProductServiceClient: 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: - ProductServiceClient: 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) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProductServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ProductServiceTransport): - # transport is a ProductServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_create_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (google.cloud.retail_v2beta.types.Product): - Required. The - [Product][google.cloud.retail.v2beta.Product] to create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2beta.Product], which - will become the final component of the - [Product.name][google.cloud.retail.v2beta.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This field must be unique among all - [Product][google.cloud.retail.v2beta.Product]s with the - same - [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.CreateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.CreateProductRequest): - request = product_service.CreateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the requested - [Product][google.cloud.retail.v2beta.Product] 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.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.GetProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.GetProductRequest): - request = product_service.GetProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsPager: - r"""Gets a list of [Product][google.cloud.retail.v2beta.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_list_products(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2beta.Product]s under - this branch, regardless of whether or not this branch - exists, a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.product_service.pagers.ListProductsPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.ListProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.ListProductsRequest): - request = product_service.ListProductsRequest(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_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProductsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (google.cloud.retail_v2beta.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2beta.Product] to update. - The immutable and output only fields are NOT supported. - If not set, all supported fields (the fields that are - neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.UpdateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.UpdateProductRequest): - request = product_service.UpdateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - 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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_delete_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2beta.Product] to - delete can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product] member nor - a - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] with more - than one - [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2beta.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.DeleteProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.DeleteProductRequest): - request = product_service.DeleteProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2beta.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2beta.Product]s to be - successfully updated. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_import_products(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2beta.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportProductsRequest): - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2beta.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_set_inventory(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2beta.Product() - inventory.title = "title_value" - - request = retail_v2beta.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (google.cloud.retail_v2beta.types.Product): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product] named in - [Product.name][google.cloud.retail.v2beta.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2beta.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2beta.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.SetInventoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.SetInventoryRequest): - request = product_service.SetInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_add_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [AddFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddFulfillmentPlacesRequest): - request = product_service.AddFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): - request = product_service.RemoveFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_add_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [AddLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddLocalInventoriesRequest): - request = product_service.AddLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_remove_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveLocalInventoriesRequest): - request = product_service.RemoveLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py deleted file mode 100644 index 552c2bfa..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product_service - - -class ListProductsPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListProductsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListProductsResponse` - 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[..., product_service.ListProductsResponse], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2beta.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[product_service.ListProductsResponse]: - 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[product.Product]: - for page in self.pages: - yield from page.products - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProductsAsyncPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListProductsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListProductsResponse` - 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[product_service.ListProductsResponse]], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2beta.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: - 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[product.Product]: - async def async_generator(): - async for page in self.pages: - for response in page.products: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py deleted file mode 100644 index db824dec..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ProductServiceTransport -from .grpc import ProductServiceGrpcTransport -from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] -_transport_registry['grpc'] = ProductServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport - -__all__ = ( - 'ProductServiceTransport', - 'ProductServiceGrpcTransport', - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py deleted file mode 100644 index 8e3d5c7e..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py +++ /dev/null @@ -1,308 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ProductServiceTransport(abc.ABC): - """Abstract transport class for ProductService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_product: gapic_v1.method.wrap_method( - self.create_product, - default_timeout=None, - client_info=client_info, - ), - self.get_product: gapic_v1.method.wrap_method( - self.get_product, - default_timeout=None, - client_info=client_info, - ), - self.list_products: gapic_v1.method.wrap_method( - self.list_products, - default_timeout=None, - client_info=client_info, - ), - self.update_product: gapic_v1.method.wrap_method( - self.update_product, - default_timeout=None, - client_info=client_info, - ), - self.delete_product: gapic_v1.method.wrap_method( - self.delete_product, - default_timeout=None, - client_info=client_info, - ), - self.import_products: gapic_v1.method.wrap_method( - self.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.set_inventory: gapic_v1.method.wrap_method( - self.set_inventory, - default_timeout=None, - client_info=client_info, - ), - self.add_fulfillment_places: gapic_v1.method.wrap_method( - self.add_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.remove_fulfillment_places: gapic_v1.method.wrap_method( - self.remove_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.add_local_inventories: gapic_v1.method.wrap_method( - self.add_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.remove_local_inventories: gapic_v1.method.wrap_method( - self.remove_local_inventories, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Union[ - product.Product, - Awaitable[product.Product] - ]]: - raise NotImplementedError() - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Union[ - product_service.ListProductsResponse, - Awaitable[product_service.ListProductsResponse] - ]]: - raise NotImplementedError() - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ProductServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py deleted file mode 100644 index b4f474cd..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py +++ /dev/null @@ -1,678 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO - - -class ProductServiceGrpcTransport(ProductServiceTransport): - """gRPC backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2beta.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - gcr_product.Product]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.CreateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - product.Product]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.GetProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - product_service.ListProductsResponse]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2beta.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - ~.ListProductsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - gcr_product.Product]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - ~.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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2beta.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2beta.Product]s to be - successfully updated. - - Returns: - Callable[[~.ImportProductsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - operations_pb2.Operation]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2beta.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProductServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py deleted file mode 100644 index aad12324..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,677 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ProductServiceGrpcTransport - - -class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): - """gRPC AsyncIO backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2beta.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.CreateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Awaitable[product.Product]]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.GetProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Awaitable[product_service.ListProductsResponse]]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2beta.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - Awaitable[~.ListProductsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - 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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2beta.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2beta.Product]s to be - successfully updated. - - Returns: - Callable[[~.ImportProductsRequest], - 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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2beta.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - 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 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - 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 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - 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 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - 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 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py deleted file mode 100644 index 2f63fc22..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SearchServiceClient -from .async_client import SearchServiceAsyncClient - -__all__ = ( - 'SearchServiceClient', - 'SearchServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py deleted file mode 100644 index 4943cff9..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.search_service import pagers -from google.cloud.retail_v2beta.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .client import SearchServiceClient - - -class SearchServiceAsyncClient: - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: SearchServiceClient - - DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(SearchServiceClient.branch_path) - parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) - product_path = staticmethod(SearchServiceClient.product_path) - parse_product_path = staticmethod(SearchServiceClient.parse_product_path) - common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(SearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SearchServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAsyncPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_search(): - # Create a client - client = retail_v2beta.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.search_service.pagers.SearchAsyncPager: - Response message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py deleted file mode 100644 index b564fd9b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py +++ /dev/null @@ -1,512 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.search_service import pagers -from google.cloud.retail_v2beta.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SearchServiceGrpcTransport -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -class SearchServiceClientMeta(type): - """Metaclass for the SearchService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] - _transport_registry["grpc"] = SearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SearchServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SearchServiceClient(metaclass=SearchServiceClientMeta): - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SearchServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SearchServiceTransport): - # transport is a SearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_search(): - # Create a client - client = retail_v2beta.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.search_service.pagers.SearchPager: - Response message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a search_service.SearchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, search_service.SearchRequest): - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py deleted file mode 100644 index 6ff03162..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import search_service - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., search_service.SearchResponse], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2beta.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[search_service.SearchResponse]], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2beta.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py deleted file mode 100644 index 7917cd1d..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SearchServiceTransport -from .grpc import SearchServiceGrpcTransport -from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] -_transport_registry['grpc'] = SearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport - -__all__ = ( - 'SearchServiceTransport', - 'SearchServiceGrpcTransport', - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py deleted file mode 100644 index 26e7d5f2..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import search_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class SearchServiceTransport(abc.ABC): - """Abstract transport class for SearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search: gapic_v1.method.wrap_method( - self.search, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Union[ - search_service.SearchResponse, - Awaitable[search_service.SearchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SearchServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py deleted file mode 100644 index f21185b4..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py +++ /dev/null @@ -1,268 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO - - -class SearchServiceGrpcTransport(SearchServiceTransport): - """gRPC backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py deleted file mode 100644 index 33943b61..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,267 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SearchServiceGrpcTransport - - -class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): - """gRPC AsyncIO backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Awaitable[search_service.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py deleted file mode 100644 index d1a0a023..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ServingConfigServiceClient -from .async_client import ServingConfigServiceAsyncClient - -__all__ = ( - 'ServingConfigServiceClient', - 'ServingConfigServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py deleted file mode 100644 index cfdace1d..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py +++ /dev/null @@ -1,954 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.serving_config_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport -from .client import ServingConfigServiceClient - - -class ServingConfigServiceAsyncClient: - """Service for modifying ServingConfig.""" - - _client: ServingConfigServiceClient - - DEFAULT_ENDPOINT = ServingConfigServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ServingConfigServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(ServingConfigServiceClient.catalog_path) - parse_catalog_path = staticmethod(ServingConfigServiceClient.parse_catalog_path) - serving_config_path = staticmethod(ServingConfigServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(ServingConfigServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(ServingConfigServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ServingConfigServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ServingConfigServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ServingConfigServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ServingConfigServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ServingConfigServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ServingConfigServiceClient.common_project_path) - parse_common_project_path = staticmethod(ServingConfigServiceClient.parse_common_project_path) - common_location_path = staticmethod(ServingConfigServiceClient.common_location_path) - parse_common_location_path = staticmethod(ServingConfigServiceClient.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: - ServingConfigServiceAsyncClient: The constructed client. - """ - return ServingConfigServiceClient.from_service_account_info.__func__(ServingConfigServiceAsyncClient, 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: - ServingConfigServiceAsyncClient: The constructed client. - """ - return ServingConfigServiceClient.from_service_account_file.__func__(ServingConfigServiceAsyncClient, 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 variabel 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 ServingConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ServingConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ServingConfigServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ServingConfigServiceClient).get_transport_class, type(ServingConfigServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ServingConfigServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the serving config service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ServingConfigServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ServingConfigServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_serving_config(self, - request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, - *, - parent: str = None, - serving_config: gcr_serving_config.ServingConfig = None, - serving_config_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_create_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = await client.create_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateServingConfigRequest, dict]): - The request object. Request for CreateServingConfig - method. - parent (:class:`str`): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config (:class:`google.cloud.retail_v2beta.types.ServingConfig`): - Required. The ServingConfig to - create. - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config_id (:class:`str`): - Required. The ID to use for the ServingConfig, which - will become the final component of the ServingConfig's - resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``serving_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, serving_config, serving_config_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.CreateServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if serving_config is not None: - request.serving_config = serving_config - if serving_config_id is not None: - request.serving_config_id = serving_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_serving_config(self, - request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_delete_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_serving_config(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteServingConfigRequest, dict]): - The request object. Request for DeleteServingConfig - method. - name (:class:`str`): - Required. The resource name of the ServingConfig to - delete. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.DeleteServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_serving_config(self, - request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, - *, - serving_config: gcr_serving_config.ServingConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Updates a ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = await client.update_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateServingConfigRequest, dict]): - The request object. Request for UpdateServingConfig - method. - serving_config (:class:`google.cloud.retail_v2beta.types.ServingConfig`): - Required. The ServingConfig to - update. - - This corresponds to the ``serving_config`` 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 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.UpdateServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config.name", request.serving_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_serving_config(self, - request: Union[serving_config_service.GetServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> serving_config.ServingConfig: - r"""Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetServingConfigRequest, dict]): - The request object. Request for GetServingConfig method. - name (:class:`str`): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.GetServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_serving_configs(self, - request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServingConfigsAsyncPager: - r"""Lists all ServingConfigs linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_list_serving_configs(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListServingConfigsRequest, dict]): - The request object. Request for ListServingConfigs - method. - parent (:class:`str`): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager: - Response for ListServingConfigs - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.ListServingConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_serving_configs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListServingConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def add_control(self, - request: Union[serving_config_service.AddControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_add_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.add_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddControlRequest, dict]): - The request object. Request for AddControl method. - serving_config (:class:`str`): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.AddControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def remove_control(self, - request: Union[serving_config_service.RemoveControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_remove_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.remove_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveControlRequest, dict]): - The request object. Request for RemoveControl method. - serving_config (:class:`str`): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.RemoveControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServingConfigServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py deleted file mode 100644 index 122021ae..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py +++ /dev/null @@ -1,1162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.serving_config_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ServingConfigServiceGrpcTransport -from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport - - -class ServingConfigServiceClientMeta(type): - """Metaclass for the ServingConfigService 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[ServingConfigServiceTransport]] - _transport_registry["grpc"] = ServingConfigServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ServingConfigServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ServingConfigServiceTransport]: - """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 ServingConfigServiceClient(metaclass=ServingConfigServiceClientMeta): - """Service for modifying ServingConfig.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServingConfigServiceClient: 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: - ServingConfigServiceClient: 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) -> ServingConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ServingConfigServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,catalog: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ServingConfigServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the serving config service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ServingConfigServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ServingConfigServiceTransport): - # transport is a ServingConfigServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_serving_config(self, - request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, - *, - parent: str = None, - serving_config: gcr_serving_config.ServingConfig = None, - serving_config_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_create_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = client.create_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateServingConfigRequest, dict]): - The request object. Request for CreateServingConfig - method. - parent (str): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config (google.cloud.retail_v2beta.types.ServingConfig): - Required. The ServingConfig to - create. - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config_id (str): - Required. The ID to use for the ServingConfig, which - will become the final component of the ServingConfig's - resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``serving_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, serving_config, serving_config_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.CreateServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.CreateServingConfigRequest): - request = serving_config_service.CreateServingConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if serving_config is not None: - request.serving_config = serving_config - if serving_config_id is not None: - request.serving_config_id = serving_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_serving_config(self, - request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_delete_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_serving_config(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteServingConfigRequest, dict]): - The request object. Request for DeleteServingConfig - method. - name (str): - Required. The resource name of the ServingConfig to - delete. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.DeleteServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.DeleteServingConfigRequest): - request = serving_config_service.DeleteServingConfigRequest(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_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_serving_config(self, - request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, - *, - serving_config: gcr_serving_config.ServingConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Updates a ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = client.update_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateServingConfigRequest, dict]): - The request object. Request for UpdateServingConfig - method. - serving_config (google.cloud.retail_v2beta.types.ServingConfig): - Required. The ServingConfig to - update. - - This corresponds to the ``serving_config`` 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 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.UpdateServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.UpdateServingConfigRequest): - request = serving_config_service.UpdateServingConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config.name", request.serving_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_serving_config(self, - request: Union[serving_config_service.GetServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> serving_config.ServingConfig: - r"""Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetServingConfigRequest, dict]): - The request object. Request for GetServingConfig method. - name (str): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.GetServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.GetServingConfigRequest): - request = serving_config_service.GetServingConfigRequest(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_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_serving_configs(self, - request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServingConfigsPager: - r"""Lists all ServingConfigs linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_list_serving_configs(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListServingConfigsRequest, dict]): - The request object. Request for ListServingConfigs - method. - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsPager: - Response for ListServingConfigs - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.ListServingConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.ListServingConfigsRequest): - request = serving_config_service.ListServingConfigsRequest(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_serving_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListServingConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def add_control(self, - request: Union[serving_config_service.AddControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_add_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.add_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddControlRequest, dict]): - The request object. Request for AddControl method. - serving_config (str): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.AddControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.AddControlRequest): - request = serving_config_service.AddControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def remove_control(self, - request: Union[serving_config_service.RemoveControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_remove_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.remove_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveControlRequest, dict]): - The request object. Request for RemoveControl method. - serving_config (str): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.RemoveControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.RemoveControlRequest): - request = serving_config_service.RemoveControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServingConfigServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py deleted file mode 100644 index a45bf88c..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config_service - - -class ListServingConfigsPager: - """A pager for iterating through ``list_serving_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``serving_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServingConfigs`` requests and continue to iterate - through the ``serving_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` - 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[..., serving_config_service.ListServingConfigsResponse], - request: serving_config_service.ListServingConfigsRequest, - response: serving_config_service.ListServingConfigsResponse, - *, - 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.retail_v2beta.types.ListServingConfigsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListServingConfigsResponse): - 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 = serving_config_service.ListServingConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[serving_config_service.ListServingConfigsResponse]: - 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[serving_config.ServingConfig]: - for page in self.pages: - yield from page.serving_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServingConfigsAsyncPager: - """A pager for iterating through ``list_serving_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``serving_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServingConfigs`` requests and continue to iterate - through the ``serving_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` - 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[serving_config_service.ListServingConfigsResponse]], - request: serving_config_service.ListServingConfigsRequest, - response: serving_config_service.ListServingConfigsResponse, - *, - 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.retail_v2beta.types.ListServingConfigsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListServingConfigsResponse): - 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 = serving_config_service.ListServingConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[serving_config_service.ListServingConfigsResponse]: - 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[serving_config.ServingConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.serving_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py deleted file mode 100644 index 3726ac83..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ServingConfigServiceTransport -from .grpc import ServingConfigServiceGrpcTransport -from .grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ServingConfigServiceTransport]] -_transport_registry['grpc'] = ServingConfigServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ServingConfigServiceGrpcAsyncIOTransport - -__all__ = ( - 'ServingConfigServiceTransport', - 'ServingConfigServiceGrpcTransport', - 'ServingConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py deleted file mode 100644 index b6f20733..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py +++ /dev/null @@ -1,237 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ServingConfigServiceTransport(abc.ABC): - """Abstract transport class for ServingConfigService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_serving_config: gapic_v1.method.wrap_method( - self.create_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_serving_config: gapic_v1.method.wrap_method( - self.delete_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.update_serving_config: gapic_v1.method.wrap_method( - self.update_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.get_serving_config: gapic_v1.method.wrap_method( - self.get_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.list_serving_configs: gapic_v1.method.wrap_method( - self.list_serving_configs, - default_timeout=None, - client_info=client_info, - ), - self.add_control: gapic_v1.method.wrap_method( - self.add_control, - default_timeout=None, - client_info=client_info, - ), - self.remove_control: gapic_v1.method.wrap_method( - self.remove_control, - 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 create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - Union[ - serving_config.ServingConfig, - Awaitable[serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - Union[ - serving_config_service.ListServingConfigsResponse, - Awaitable[serving_config_service.ListServingConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ServingConfigServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py deleted file mode 100644 index a40958de..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py +++ /dev/null @@ -1,438 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO - - -class ServingConfigServiceGrpcTransport(ServingConfigServiceTransport): - """gRPC backend transport for ServingConfigService. - - Service for modifying ServingConfig. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the create serving config method over gRPC. - - Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - Returns: - Callable[[~.CreateServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/CreateServingConfig', - request_serializer=serving_config_service.CreateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['create_serving_config'] - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete serving config method over gRPC. - - Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.DeleteServingConfigRequest], - ~.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_serving_config' not in self._stubs: - self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/DeleteServingConfig', - request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_serving_config'] - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the update serving config method over gRPC. - - Updates a ServingConfig. - - Returns: - Callable[[~.UpdateServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/UpdateServingConfig', - request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['update_serving_config'] - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - serving_config.ServingConfig]: - r"""Return a callable for the get serving config method over gRPC. - - Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.GetServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/GetServingConfig', - request_serializer=serving_config_service.GetServingConfigRequest.serialize, - response_deserializer=serving_config.ServingConfig.deserialize, - ) - return self._stubs['get_serving_config'] - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - serving_config_service.ListServingConfigsResponse]: - r"""Return a callable for the list serving configs method over gRPC. - - Lists all ServingConfigs linked to this catalog. - - Returns: - Callable[[~.ListServingConfigsRequest], - ~.ListServingConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: - self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/ListServingConfigs', - request_serializer=serving_config_service.ListServingConfigsRequest.serialize, - response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, - ) - return self._stubs['list_serving_configs'] - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the add control method over gRPC. - - Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - Returns: - Callable[[~.AddControlRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_control' not in self._stubs: - self._stubs['add_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/AddControl', - request_serializer=serving_config_service.AddControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['add_control'] - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the remove control method over gRPC. - - Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - Returns: - Callable[[~.RemoveControlRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_control' not in self._stubs: - self._stubs['remove_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/RemoveControl', - request_serializer=serving_config_service.RemoveControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['remove_control'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ServingConfigServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py deleted file mode 100644 index ad0a2383..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,437 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ServingConfigServiceGrpcTransport - - -class ServingConfigServiceGrpcAsyncIOTransport(ServingConfigServiceTransport): - """gRPC AsyncIO backend transport for ServingConfigService. - - Service for modifying ServingConfig. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the create serving config method over gRPC. - - Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - Returns: - Callable[[~.CreateServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/CreateServingConfig', - request_serializer=serving_config_service.CreateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['create_serving_config'] - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete serving config method over gRPC. - - Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.DeleteServingConfigRequest], - 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_serving_config' not in self._stubs: - self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/DeleteServingConfig', - request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_serving_config'] - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the update serving config method over gRPC. - - Updates a ServingConfig. - - Returns: - Callable[[~.UpdateServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/UpdateServingConfig', - request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['update_serving_config'] - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - Awaitable[serving_config.ServingConfig]]: - r"""Return a callable for the get serving config method over gRPC. - - Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.GetServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/GetServingConfig', - request_serializer=serving_config_service.GetServingConfigRequest.serialize, - response_deserializer=serving_config.ServingConfig.deserialize, - ) - return self._stubs['get_serving_config'] - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - Awaitable[serving_config_service.ListServingConfigsResponse]]: - r"""Return a callable for the list serving configs method over gRPC. - - Lists all ServingConfigs linked to this catalog. - - Returns: - Callable[[~.ListServingConfigsRequest], - Awaitable[~.ListServingConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: - self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/ListServingConfigs', - request_serializer=serving_config_service.ListServingConfigsRequest.serialize, - response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, - ) - return self._stubs['list_serving_configs'] - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the add control method over gRPC. - - Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - Returns: - Callable[[~.AddControlRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_control' not in self._stubs: - self._stubs['add_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/AddControl', - request_serializer=serving_config_service.AddControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['add_control'] - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the remove control method over gRPC. - - Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - Returns: - Callable[[~.RemoveControlRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_control' not in self._stubs: - self._stubs['remove_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/RemoveControl', - request_serializer=serving_config_service.RemoveControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['remove_control'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ServingConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py deleted file mode 100644 index 5f5171c1..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py deleted file mode 100644 index 24cdc934..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py +++ /dev/null @@ -1,730 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on the customer - website. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(UserEventServiceClient.catalog_path) - parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) - product_path = staticmethod(UserEventServiceClient.product_path) - parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_write_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_collect_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_purge_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_import_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2beta.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_rejoin_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py deleted file mode 100644 index 04d1d50e..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py +++ /dev/null @@ -1,929 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[UserEventServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on the customer - website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_write_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_collect_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_purge_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeUserEventsRequest): - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_import_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2beta.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportUserEventsRequest): - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_rejoin_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.RejoinUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.RejoinUserEventsRequest): - request = user_event_service.RejoinUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py deleted file mode 100644 index f53ee5d7..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py deleted file mode 100644 index bfd58c51..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py +++ /dev/null @@ -1,231 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_timeout=None, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_timeout=None, - client_info=client_info, - ), - self.purge_user_events: gapic_v1.method.wrap_method( - self.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.rejoin_user_events: gapic_v1.method.wrap_method( - self.rejoin_user_events, - 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 write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - user_event.UserEvent, - Awaitable[user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py deleted file mode 100644 index aa8a47d4..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,415 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index b4b62767..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,414 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - 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 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py deleted file mode 100644 index 62477503..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py +++ /dev/null @@ -1,278 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .catalog import ( - AttributesConfig, - Catalog, - CatalogAttribute, - CompletionConfig, - MerchantCenterLink, - MerchantCenterLinkingConfig, - ProductLevelConfig, -) -from .catalog_service import ( - AddCatalogAttributeRequest, - GetAttributesConfigRequest, - GetCompletionConfigRequest, - GetDefaultBranchRequest, - GetDefaultBranchResponse, - ListCatalogsRequest, - ListCatalogsResponse, - RemoveCatalogAttributeRequest, - ReplaceCatalogAttributeRequest, - SetDefaultBranchRequest, - UpdateAttributesConfigRequest, - UpdateCatalogRequest, - UpdateCompletionConfigRequest, -) -from .common import ( - Audience, - ColorInfo, - Condition, - CustomAttribute, - FulfillmentInfo, - Image, - Interval, - LocalInventory, - PriceInfo, - Rating, - Rule, - UserInfo, - AttributeConfigLevel, - SearchSolutionUseCase, - SolutionType, -) -from .completion_service import ( - CompleteQueryRequest, - CompleteQueryResponse, -) -from .control import ( - Control, -) -from .control_service import ( - CreateControlRequest, - DeleteControlRequest, - GetControlRequest, - ListControlsRequest, - ListControlsResponse, - UpdateControlRequest, -) -from .export_config import ( - ExportErrorsConfig, - ExportMetadata, - ExportProductsResponse, - ExportUserEventsResponse, -) -from .import_config import ( - BigQuerySource, - CompletionDataInputConfig, - GcsSource, - ImportCompletionDataRequest, - ImportCompletionDataResponse, - ImportErrorsConfig, - ImportMetadata, - ImportProductsRequest, - ImportProductsResponse, - ImportUserEventsRequest, - ImportUserEventsResponse, - ProductInlineSource, - ProductInputConfig, - UserEventImportSummary, - UserEventInlineSource, - UserEventInputConfig, -) -from .prediction_service import ( - PredictRequest, - PredictResponse, -) -from .product import ( - Product, -) -from .product_service import ( - AddFulfillmentPlacesMetadata, - AddFulfillmentPlacesRequest, - AddFulfillmentPlacesResponse, - AddLocalInventoriesMetadata, - AddLocalInventoriesRequest, - AddLocalInventoriesResponse, - CreateProductRequest, - DeleteProductRequest, - GetProductRequest, - ListProductsRequest, - ListProductsResponse, - RemoveFulfillmentPlacesMetadata, - RemoveFulfillmentPlacesRequest, - RemoveFulfillmentPlacesResponse, - RemoveLocalInventoriesMetadata, - RemoveLocalInventoriesRequest, - RemoveLocalInventoriesResponse, - SetInventoryMetadata, - SetInventoryRequest, - SetInventoryResponse, - UpdateProductRequest, -) -from .promotion import ( - Promotion, -) -from .purge_config import ( - PurgeMetadata, - PurgeUserEventsRequest, - PurgeUserEventsResponse, -) -from .search_service import ( - SearchRequest, - SearchResponse, -) -from .serving_config import ( - ServingConfig, -) -from .serving_config_service import ( - AddControlRequest, - CreateServingConfigRequest, - DeleteServingConfigRequest, - GetServingConfigRequest, - ListServingConfigsRequest, - ListServingConfigsResponse, - RemoveControlRequest, - UpdateServingConfigRequest, -) -from .user_event import ( - CompletionDetail, - ProductDetail, - PurchaseTransaction, - UserEvent, -) -from .user_event_service import ( - CollectUserEventRequest, - RejoinUserEventsMetadata, - RejoinUserEventsRequest, - RejoinUserEventsResponse, - WriteUserEventRequest, -) - -__all__ = ( - 'AttributesConfig', - 'Catalog', - 'CatalogAttribute', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'ProductLevelConfig', - 'AddCatalogAttributeRequest', - 'GetAttributesConfigRequest', - 'GetCompletionConfigRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - 'SetDefaultBranchRequest', - 'UpdateAttributesConfigRequest', - 'UpdateCatalogRequest', - 'UpdateCompletionConfigRequest', - 'Audience', - 'ColorInfo', - 'Condition', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'Rule', - 'UserInfo', - 'AttributeConfigLevel', - 'SearchSolutionUseCase', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Control', - 'CreateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - 'UpdateControlRequest', - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'ServingConfig', - 'AddControlRequest', - 'CreateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'RemoveControlRequest', - 'UpdateServingConfigRequest', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py deleted file mode 100644 index 8398213f..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py +++ /dev/null @@ -1,528 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'ProductLevelConfig', - 'CatalogAttribute', - 'AttributesConfig', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'Catalog', - }, -) - - -class ProductLevelConfig(proto.Message): - r"""Configures what level the product should be uploaded with - regards to how users will be send events and how predictions - will be made. - - Attributes: - ingestion_product_type (str): - The type of [Product][google.cloud.retail.v2beta.Product]s - allowed to be ingested into the catalog. Acceptable values - are: - - - ``primary`` (default): You can ingest - [Product][google.cloud.retail.v2beta.Product]s of all - types. When ingesting a - [Product][google.cloud.retail.v2beta.Product], its type - will default to - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - if unset. - - ``variant``: You can only ingest - [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s. This - means - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] - cannot be empty. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``variant`` and - [merchant_center_product_id_field][google.cloud.retail.v2beta.ProductLevelConfig.merchant_center_product_id_field] - is ``itemGroupId``, an INVALID_ARGUMENT error is returned. - - See `Using product - levels `__ - for more details. - merchant_center_product_id_field (str): - Which field of `Merchant Center - Product `__ - should be imported as - [Product.id][google.cloud.retail.v2beta.Product.id]. - Acceptable values are: - - - ``offerId`` (default): Import ``offerId`` as the product - ID. - - ``itemGroupId``: Import ``itemGroupId`` as the product - ID. Notice that Retail API will choose one item from the - ones with the same ``itemGroupId``, and use it to - represent the item group. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``itemGroupId`` and - [ingestion_product_type][google.cloud.retail.v2beta.ProductLevelConfig.ingestion_product_type] - is ``variant``, an INVALID_ARGUMENT error is returned. - - See `Using product - levels `__ - for more details. - """ - - ingestion_product_type = proto.Field( - proto.STRING, - number=1, - ) - merchant_center_product_id_field = proto.Field( - proto.STRING, - number=2, - ) - - -class CatalogAttribute(proto.Message): - r"""Catalog level attribute config for an attribute. For example, - if customers want to enable/disable facet for a specific - attribute. - - Attributes: - key (str): - Required. Attribute name. For example: ``color``, - ``brands``, ``attributes.custom_attribute``, such as - ``attributes.xyz``. - in_use (bool): - Output only. Indicates whether this attribute has been used - by any products. ``True`` if at least one - [Product][google.cloud.retail.v2beta.Product] is using this - attribute in - [Product.attributes][google.cloud.retail.v2beta.Product.attributes]. - Otherwise, this field is ``False``. - - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - can be pre-loaded by using [AddCatalogAttribute][], - [ImportCatalogAttributes][], or [UpdateAttributesConfig][] - APIs. This field is ``False`` for pre-loaded - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s. - - Only - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s - that are not in use by products can be deleted. - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s - that are in use by products cannot be deleted; however, - their configuration properties will reset to default values - upon removal request. - - After catalog changes, it takes about 10 minutes for this - field to update. - type_ (google.cloud.retail_v2beta.types.CatalogAttribute.AttributeType): - Output only. The type of this attribute. This is derived - from the attribute in - [Product.attributes][google.cloud.retail.v2beta.Product.attributes]. - indexable_option (google.cloud.retail_v2beta.types.CatalogAttribute.IndexableOption): - When - [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] - is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if INDEXABLE_ENABLED - attribute values are indexed so that it can be filtered, - faceted, or boosted in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - dynamic_facetable_option (google.cloud.retail_v2beta.types.CatalogAttribute.DynamicFacetableOption): - If DYNAMIC_FACETABLE_ENABLED, attribute values are available - for dynamic facet. Could only be DYNAMIC_FACETABLE_DISABLED - if - [CatalogAttribute.indexable_option][google.cloud.retail.v2beta.CatalogAttribute.indexable_option] - is INDEXABLE_DISABLED. Otherwise, an INVALID_ARGUMENT error - is returned. - searchable_option (google.cloud.retail_v2beta.types.CatalogAttribute.SearchableOption): - When - [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] - is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if SEARCHABLE_ENABLED, - attribute values are searchable by text queries in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - If SEARCHABLE_ENABLED but attribute type is numerical, - attribute values will not be searchable by text queries in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - as there are no text values associated to numerical - attributes. - """ - class AttributeType(proto.Enum): - r"""The type of an attribute.""" - UNKNOWN = 0 - TEXTUAL = 1 - NUMERICAL = 2 - - class IndexableOption(proto.Enum): - r"""The status of the indexable option of a catalog attribute.""" - INDEXABLE_OPTION_UNSPECIFIED = 0 - INDEXABLE_ENABLED = 1 - INDEXABLE_DISABLED = 2 - - class DynamicFacetableOption(proto.Enum): - r"""The status of the dynamic facetable option of a catalog - attribute. - """ - DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 - DYNAMIC_FACETABLE_ENABLED = 1 - DYNAMIC_FACETABLE_DISABLED = 2 - - class SearchableOption(proto.Enum): - r"""The status of the searchable option of a catalog attribute.""" - SEARCHABLE_OPTION_UNSPECIFIED = 0 - SEARCHABLE_ENABLED = 1 - SEARCHABLE_DISABLED = 2 - - key = proto.Field( - proto.STRING, - number=1, - ) - in_use = proto.Field( - proto.BOOL, - number=9, - ) - type_ = proto.Field( - proto.ENUM, - number=10, - enum=AttributeType, - ) - indexable_option = proto.Field( - proto.ENUM, - number=5, - enum=IndexableOption, - ) - dynamic_facetable_option = proto.Field( - proto.ENUM, - number=6, - enum=DynamicFacetableOption, - ) - searchable_option = proto.Field( - proto.ENUM, - number=7, - enum=SearchableOption, - ) - - -class AttributesConfig(proto.Message): - r"""Catalog level attribute config. - - Attributes: - name (str): - Required. Immutable. The fully qualified resource name of - the attribute config. Format: - ``projects/*/locations/*/catalogs/*/attributesConfig`` - catalog_attributes (Mapping[str, google.cloud.retail_v2beta.types.CatalogAttribute]): - Enable attribute(s) config at catalog level. For example, - indexable, dynamic_facetable, or searchable for each - attribute. - - The key is catalog attribute's name. For example: ``color``, - ``brands``, ``attributes.custom_attribute``, such as - ``attributes.xyz``. - - The maximum number of catalog attributes allowed in a - request is 1000. - attribute_config_level (google.cloud.retail_v2beta.types.AttributeConfigLevel): - Output only. The - [AttributeConfigLevel][google.cloud.retail.v2beta.AttributeConfigLevel] - used for this catalog. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - catalog_attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='CatalogAttribute', - ) - attribute_config_level = proto.Field( - proto.ENUM, - number=3, - enum=common.AttributeConfigLevel, - ) - - -class CompletionConfig(proto.Message): - r"""Catalog level autocomplete config for customers to customize - autocomplete feature's settings. - - Attributes: - name (str): - Required. Immutable. Fully qualified name - ``projects/*/locations/*/catalogs/*/completionConfig`` - matching_order (str): - Specifies the matching order for autocomplete suggestions, - e.g., a query consisting of 'sh' with 'out-of-order' - specified would suggest "women's shoes", whereas a query of - 'red s' with 'exact-prefix' specified would suggest "red - shoes". Currently supported values: - - - 'out-of-order' - - 'exact-prefix' - - Default value: 'exact-prefix'. - max_suggestions (int): - The maximum number of autocomplete - suggestions returned per term. The maximum - allowed max suggestions is 20. Default value is - 20. If left unset or set to 0, then will - fallback to default value. - min_prefix_length (int): - The minimum number of characters needed to be - typed in order to get suggestions. Default value - is 2. If left unset or set to 0, then will - fallback to default value. - auto_learning (bool): - If set to true, the auto learning function is enabled. Auto - learning uses user data to generate suggestions using ML - techniques. Default value is false. Only after enabling auto - learning can users use ``cloud-retail`` data in - [CompleteQueryRequest][google.cloud.retail.v2beta.CompleteQueryRequest]. - suggestions_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the - autocomplete phrases uploaded by the customer. - last_suggestions_import_operation (str): - Output only. Name of the LRO corresponding to the latest - suggestion terms list import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - denylist_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the / - autocomplete denylist phrases uploaded by the - customer. - last_denylist_import_operation (str): - Output only. LRO corresponding to the latest denylist - import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - allowlist_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the - autocomplete allowlist phrases uploaded by the - customer. - last_allowlist_import_operation (str): - Output only. LRO corresponding to the latest allowlist - import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - matching_order = proto.Field( - proto.STRING, - number=2, - ) - max_suggestions = proto.Field( - proto.INT32, - number=3, - ) - min_prefix_length = proto.Field( - proto.INT32, - number=4, - ) - auto_learning = proto.Field( - proto.BOOL, - number=11, - ) - suggestions_input_config = proto.Field( - proto.MESSAGE, - number=5, - message=import_config.CompletionDataInputConfig, - ) - last_suggestions_import_operation = proto.Field( - proto.STRING, - number=6, - ) - denylist_input_config = proto.Field( - proto.MESSAGE, - number=7, - message=import_config.CompletionDataInputConfig, - ) - last_denylist_import_operation = proto.Field( - proto.STRING, - number=8, - ) - allowlist_input_config = proto.Field( - proto.MESSAGE, - number=9, - message=import_config.CompletionDataInputConfig, - ) - last_allowlist_import_operation = proto.Field( - proto.STRING, - number=10, - ) - - -class MerchantCenterLink(proto.Message): - r"""Represents a link between a Merchant Center account and a - branch. Once a link is established, products from the linked - merchant center account will be streamed to the linked branch. - - Attributes: - merchant_center_account_id (int): - Required. The linked `Merchant center account - id `__. - The account must be a standalone account or a sub-account of - a MCA. - branch_id (str): - The branch id (e.g. 0/1/2) within this catalog that products - from merchant_center_account_id are streamed to. When - updating this field, an empty value will use the currently - configured default branch. However, changing the default - branch later on won't change the linked branch here. - - A single branch id can only have one linked merchant center - account id. - destinations (Sequence[str]): - String representing the destination to import for, all if - left empty. List of possible values can be found here. - [https://support.google.com/merchants/answer/7501026] List - of allowed string values: "Shopping_ads", - "Buy_on_google_listings", "Display_ads", "Local_inventory - \_ads", "Free_listings", "Free_local_listings" NOTE: The - string values are case sensitive. - region_code (str): - Region code of offers to accept. 2-letter Uppercase ISO - 3166-1 alpha-2 code. List of values can be found - `here `__ - under the ``region`` tag. If left blank no region filtering - will be performed. - - Example value: ``US``. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. ISO - 639-1. - - This specifies the language of offers in Merchant Center - that will be accepted. If empty no language filtering will - be performed. - - Example value: ``en``. - """ - - merchant_center_account_id = proto.Field( - proto.INT64, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - destinations = proto.RepeatedField( - proto.STRING, - number=3, - ) - region_code = proto.Field( - proto.STRING, - number=4, - ) - language_code = proto.Field( - proto.STRING, - number=5, - ) - - -class MerchantCenterLinkingConfig(proto.Message): - r"""Configures Merchant Center linking. - Links contained in the config will be used to sync data from a - Merchant Center account to a Cloud Retail branch. - - Attributes: - links (Sequence[google.cloud.retail_v2beta.types.MerchantCenterLink]): - Links between Merchant Center accounts and - branches. - """ - - links = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='MerchantCenterLink', - ) - - -class Catalog(proto.Message): - r"""The catalog configuration. - - Attributes: - name (str): - Required. Immutable. The fully qualified - resource name of the catalog. - display_name (str): - Required. Immutable. The catalog display name. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - product_level_config (google.cloud.retail_v2beta.types.ProductLevelConfig): - Required. The product level configuration. - merchant_center_linking_config (google.cloud.retail_v2beta.types.MerchantCenterLinkingConfig): - The Merchant Center linking configuration. - Once a link is added, the data stream from - Merchant Center to Cloud Retail will be enabled - automatically. The requester must have access to - the merchant center account in order to make - changes to this field. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - product_level_config = proto.Field( - proto.MESSAGE, - number=4, - message='ProductLevelConfig', - ) - merchant_center_linking_config = proto.Field( - proto.MESSAGE, - number=6, - message='MerchantCenterLinkingConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py deleted file mode 100644 index c49ba005..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py +++ /dev/null @@ -1,453 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'UpdateCatalogRequest', - 'SetDefaultBranchRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'GetCompletionConfigRequest', - 'UpdateCompletionConfigRequest', - 'GetAttributesConfigRequest', - 'UpdateAttributesConfigRequest', - 'AddCatalogAttributeRequest', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - }, -) - - -class ListCatalogsRequest(proto.Message): - r"""Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - - Attributes: - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2beta.Catalog]s under this - location, regardless of whether or not this location exists, - a PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of - [Catalog][google.cloud.retail.v2beta.Catalog]s to return. If - unspecified, defaults to 50. The maximum allowed value is - 1000. Values above 1000 will be coerced to 1000. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [ListCatalogsResponse.next_page_token][google.cloud.retail.v2beta.ListCatalogsResponse.next_page_token], - received from a previous - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListCatalogsResponse(proto.Message): - r"""Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - - Attributes: - catalogs (Sequence[google.cloud.retail_v2beta.types.Catalog]): - All the customer's - [Catalog][google.cloud.retail.v2beta.Catalog]s. - next_page_token (str): - A token that can be sent as - [ListCatalogsRequest.page_token][google.cloud.retail.v2beta.ListCatalogsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - catalogs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateCatalogRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] - method. - - Attributes: - catalog (google.cloud.retail_v2beta.types.Catalog): - Required. The [Catalog][google.cloud.retail.v2beta.Catalog] - to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2beta.Catalog], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2beta.Catalog] 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 - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - catalog = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class SetDefaultBranchRequest(proto.Message): - r"""Request message to set a specified branch as new default_branch. - - Attributes: - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - branch_id (str): - The final component of the resource name of a branch. - - This field must be one of "0", "1" or "2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If there are no sufficient active products in the targeted - branch and - [force][google.cloud.retail.v2beta.SetDefaultBranchRequest.force] - is not set, a FAILED_PRECONDITION error is returned. - note (str): - Some note on this request, this can be retrieved by - [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch] - before next valid default branch set occurs. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - force (bool): - If set to true, it permits switching to a branch with - [branch_id][google.cloud.retail.v2beta.SetDefaultBranchRequest.branch_id] - even if it has no sufficient active products. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - force = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetDefaultBranchRequest(proto.Message): - r"""Request message to show which branch is currently the default - branch. - - Attributes: - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - - -class GetDefaultBranchResponse(proto.Message): - r"""Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. - - Attributes: - branch (str): - Full resource name of the branch id currently - set as default branch. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when this branch is set to default. - note (str): - This corresponds to - [SetDefaultBranchRequest.note][google.cloud.retail.v2beta.SetDefaultBranchRequest.note] - field, when this branch was set as default. - """ - - branch = proto.Field( - proto.STRING, - number=1, - ) - set_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - - -class GetCompletionConfigRequest(proto.Message): - r"""Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] - method. - - Attributes: - name (str): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateCompletionConfigRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] - method. - - Attributes: - completion_config (google.cloud.retail_v2beta.types.CompletionConfig): - Required. The - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - 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 - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - """ - - completion_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.CompletionConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetAttributesConfigRequest(proto.Message): - r"""Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] - method. - - Attributes: - name (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateAttributesConfigRequest(proto.Message): - r"""Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] - method. - - Attributes: - attributes_config (google.cloud.retail_v2beta.types.AttributesConfig): - Required. The - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - """ - - attributes_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.AttributesConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class AddCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - catalog_attribute (google.cloud.retail_v2beta.types.CatalogAttribute): - Required. The - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - catalog_attribute = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_catalog.CatalogAttribute, - ) - - -class RemoveCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - key (str): - Required. The attribute name key of the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - key = proto.Field( - proto.STRING, - number=2, - ) - - -class ReplaceCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - catalog_attribute (google.cloud.retail_v2beta.types.CatalogAttribute): - Required. The updated - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to update. The following are NOT supported: - - - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key] - - If not set, all supported fields are updated. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - catalog_attribute = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_catalog.CatalogAttribute, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py deleted file mode 100644 index c40843c0..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py +++ /dev/null @@ -1,1178 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'AttributeConfigLevel', - 'SolutionType', - 'SearchSolutionUseCase', - 'Condition', - 'Rule', - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'LocalInventory', - }, -) - - -class AttributeConfigLevel(proto.Enum): - r"""At which level we offer configuration for attributes.""" - ATTRIBUTE_CONFIG_LEVEL_UNSPECIFIED = 0 - PRODUCT_LEVEL_ATTRIBUTE_CONFIG = 1 - CATALOG_LEVEL_ATTRIBUTE_CONFIG = 2 - - -class SolutionType(proto.Enum): - r"""The type of solution.""" - SOLUTION_TYPE_UNSPECIFIED = 0 - SOLUTION_TYPE_RECOMMENDATION = 1 - SOLUTION_TYPE_SEARCH = 2 - - -class SearchSolutionUseCase(proto.Enum): - r"""The use case of Cloud Retail Search.""" - SEARCH_SOLUTION_USE_CASE_UNSPECIFIED = 0 - SEARCH_SOLUTION_USE_CASE_SEARCH = 1 - SEARCH_SOLUTION_USE_CASE_BROWSE = 2 - - -class Condition(proto.Message): - r"""Metadata that is used to define a condition that triggers an action. - A valid condition must specify at least one of 'query_terms' or - 'products_filter'. If multiple fields are specified, the condition - is met if all the fields are satisfied e.g. if a set of query terms - and product_filter are set, then only items matching the - product_filter for requests with a query matching the query terms - wil get boosted. - - Attributes: - query_terms (Sequence[google.cloud.retail_v2beta.types.Condition.QueryTerm]): - A list (up to 10 entries) of terms to match - the query on. If not specified, match all - queries. If many query terms are specified, the - condition is matched if any of the terms is a - match (i.e. using the OR operator). - active_time_range (Sequence[google.cloud.retail_v2beta.types.Condition.TimeRange]): - Range of time(s) specifying when Condition is - active. Condition true if any time range - matches. - """ - - class QueryTerm(proto.Message): - r"""Query terms that we want to match on. - - Attributes: - value (str): - The value of the term to match on. - Value cannot be empty. - Value can have at most 3 terms if specified as a - partial match. Each space separated string is - considered as one term. Example) "a b c" is 3 - terms and allowed, " a b c d" is 4 terms and not - allowed for partial match. - full_match (bool): - Whether this is supposed to be a full or - partial match. - """ - - value = proto.Field( - proto.STRING, - number=1, - ) - full_match = proto.Field( - proto.BOOL, - number=2, - ) - - class TimeRange(proto.Message): - r"""Used for time-dependent conditions. - Example: Want to have rule applied for week long sale. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start of time range. Range is inclusive. - end_time (google.protobuf.timestamp_pb2.Timestamp): - End of time range. Range is inclusive. - """ - - start_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - query_terms = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=QueryTerm, - ) - active_time_range = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=TimeRange, - ) - - -class Rule(proto.Message): - r"""A rule is a condition-action pair - - - A condition defines when a rule is to be triggered. - - An action specifies what occurs on that trigger. Currently only - boost rules are supported. Currently only supported by the search - endpoint. - - 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: - boost_action (google.cloud.retail_v2beta.types.Rule.BoostAction): - A boost action. - - This field is a member of `oneof`_ ``action``. - redirect_action (google.cloud.retail_v2beta.types.Rule.RedirectAction): - Redirects a shopper to a specific page. - - This field is a member of `oneof`_ ``action``. - oneway_synonyms_action (google.cloud.retail_v2beta.types.Rule.OnewaySynonymsAction): - Treats specific term as a synonym with a - group of terms. Group of terms will not be - treated as synonyms with the specific term. - - This field is a member of `oneof`_ ``action``. - do_not_associate_action (google.cloud.retail_v2beta.types.Rule.DoNotAssociateAction): - Prevents term from being associated with - other terms. - - This field is a member of `oneof`_ ``action``. - replacement_action (google.cloud.retail_v2beta.types.Rule.ReplacementAction): - Replaces specific terms in the query. - - This field is a member of `oneof`_ ``action``. - ignore_action (google.cloud.retail_v2beta.types.Rule.IgnoreAction): - Ignores specific terms from query during - search. - - This field is a member of `oneof`_ ``action``. - filter_action (google.cloud.retail_v2beta.types.Rule.FilterAction): - Filters results. - - This field is a member of `oneof`_ ``action``. - twoway_synonyms_action (google.cloud.retail_v2beta.types.Rule.TwowaySynonymsAction): - Treats a set of terms as synonyms of one - another. - - This field is a member of `oneof`_ ``action``. - condition (google.cloud.retail_v2beta.types.Condition): - Required. The condition that triggers the - rule. If the condition is empty, the rule will - always apply. - """ - - class BoostAction(proto.Message): - r"""A boost action to apply to results matching condition - specified above. - - Attributes: - boost (float): - Strength of the condition boost, which must be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - products_filter (str): - The filter can have a max size of 5000 characters. An - expression which specifies which products to apply an action - to. The syntax and supported fields are the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": *(id: - ANY("product_1", "product_2"))* *AND* *(colorFamilies: - ANY("Red", "Blue"))* - """ - - boost = proto.Field( - proto.FLOAT, - number=1, - ) - products_filter = proto.Field( - proto.STRING, - number=2, - ) - - class FilterAction(proto.Message): - r"""- Rule Condition: - - - No [Condition][query_terms] provided is a global match. - - 1 or more [Condition][query_terms] provided is combined with - OR operator. - - - Action Input: The request query and filter that will be applied - to the retrieved products, in addition to any filters already - provided with the SearchRequest. The AND operator is used to - combine the query's existing filters with the filter rule(s). - NOTE: May result in 0 results when filters conflict. - - Action Result: Filters the returned objects to be ONLY those that - passed the filter. - - Attributes: - filter (str): - A filter to apply on the matching condition results. - Supported features: - - - [filter][google.cloud.retail.v2beta.Rule.FilterAction.filter] - must be set. - - Filter syntax is identical to - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter]. - See more details at the Retail Search `user - guide `__. - - To filter products with product ID "product_1" or - "product_2", and color "Red" or "Blue": *(id: - ANY("product_1", "product_2"))* *AND* *(colorFamilies: - ANY("Red", "Blue"))* - """ - - filter = proto.Field( - proto.STRING, - number=1, - ) - - class RedirectAction(proto.Message): - r"""Redirects a shopper to a specific page. - - - Rule Condition: - - - Must specify [Condition][query_terms]. - - - Action Input: Request Query - - Action Result: Redirects shopper to provided uri. - - Attributes: - redirect_uri (str): - URL must have length equal or less than 2000 - characters. - """ - - redirect_uri = proto.Field( - proto.STRING, - number=1, - ) - - class TwowaySynonymsAction(proto.Message): - r"""Creates a set of terms that will be treated as synonyms of each - other. Example: synonyms of "sneakers" and "shoes". - - - "sneakers" will use a synonym of "shoes". - - "shoes" will use a synonym of "sneakers". - - Attributes: - synonyms (Sequence[str]): - Defines a set of synonyms. - Can specify up to 100 synonyms. - Must specify at least 2 synonyms. - """ - - synonyms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class OnewaySynonymsAction(proto.Message): - r"""Maps a set of terms to a set of synonyms. Set of synonyms will be - treated as synonyms of each query term only. ``query_terms`` will - not be treated as synonyms of each other. Example: "sneakers" will - use a synonym of "shoes". "shoes" will not use a synonym of - "sneakers". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. - Will treat synonyms as their synonyms. - Not themselves synonyms of the synonyms. - Can specify up to 100 terms. - synonyms (Sequence[str]): - Defines a set of synonyms. - Cannot contain duplicates. - Can specify up to 100 synonyms. - oneway_terms (Sequence[str]): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=3, - ) - synonyms = proto.RepeatedField( - proto.STRING, - number=4, - ) - oneway_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class DoNotAssociateAction(proto.Message): - r"""Prevents ``query_term`` from being associated with specified terms - during search. Example: Don't associate "gShoe" and "cheap". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. Will not consider - do_not_associate_terms for search if in search query. Can - specify up to 100 terms. - do_not_associate_terms (Sequence[str]): - Cannot contain duplicates or the query term. - Can specify up to 100 terms. - terms (Sequence[str]): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - do_not_associate_terms = proto.RepeatedField( - proto.STRING, - number=3, - ) - terms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class ReplacementAction(proto.Message): - r"""Replaces a term in the query. Multiple replacement candidates can be - specified. All ``query_terms`` will be replaced with the replacement - term. Example: Replace "gShoe" with "google shoe". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. - Will be replaced by replacement term. - Can specify up to 100 terms. - replacement_term (str): - Term that will be used for replacement. - term (str): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - replacement_term = proto.Field( - proto.STRING, - number=3, - ) - term = proto.Field( - proto.STRING, - number=1, - ) - - class IgnoreAction(proto.Message): - r"""Prevents a term in the query from being used in search. - Example: Don't search for "shoddy". - - Attributes: - ignore_terms (Sequence[str]): - Terms to ignore in the search query. - """ - - ignore_terms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - boost_action = proto.Field( - proto.MESSAGE, - number=2, - oneof='action', - message=BoostAction, - ) - redirect_action = proto.Field( - proto.MESSAGE, - number=3, - oneof='action', - message=RedirectAction, - ) - oneway_synonyms_action = proto.Field( - proto.MESSAGE, - number=6, - oneof='action', - message=OnewaySynonymsAction, - ) - do_not_associate_action = proto.Field( - proto.MESSAGE, - number=7, - oneof='action', - message=DoNotAssociateAction, - ) - replacement_action = proto.Field( - proto.MESSAGE, - number=8, - oneof='action', - message=ReplacementAction, - ) - ignore_action = proto.Field( - proto.MESSAGE, - number=9, - oneof='action', - message=IgnoreAction, - ) - filter_action = proto.Field( - proto.MESSAGE, - number=10, - oneof='action', - message=FilterAction, - ) - twoway_synonyms_action = proto.Field( - proto.MESSAGE, - number=11, - oneof='action', - message=TwowaySynonymsAction, - ) - condition = proto.Field( - proto.MESSAGE, - number=1, - message='Condition', - ) - - -class Audience(proto.Message): - r"""An intended audience of the - [Product][google.cloud.retail.v2beta.Product] for whom it's sold. - - Attributes: - genders (Sequence[str]): - The genders of the audience. Strongly encouraged to use the - standard values: "male", "female", "unisex". - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `gender `__. - Schema.org property - `Product.audience.suggestedGender `__. - age_groups (Sequence[str]): - The age groups of the audience. Strongly encouraged to use - the standard values: "newborn" (up to 3 months old), - "infant" (3–12 months old), "toddler" (1–5 years old), - "kids" (5–13 years old), "adult" (typically teens or older). - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `age_group `__. - Schema.org property - `Product.audience.suggestedMinAge `__ - and - `Product.audience.suggestedMaxAge `__. - """ - - genders = proto.RepeatedField( - proto.STRING, - number=1, - ) - age_groups = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class ColorInfo(proto.Message): - r"""The color information of a - [Product][google.cloud.retail.v2beta.Product]. - - Attributes: - color_families (Sequence[str]): - The standard color families. Strongly recommended to use the - following standard color groups: "Red", "Pink", "Orange", - "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", - "White", "Gray", "Black" and "Mixed". Normally it is - expected to have only 1 color family. May consider using - single "Mixed" instead of multiple values. - - A maximum of 5 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - colors (Sequence[str]): - The color display names, which may be different from - standard color family names, such as the color aliases used - in the website frontend. Normally it is expected to have - only 1 color. May consider using single "Mixed" instead of - multiple values. - - A maximum of 25 colors are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - """ - - color_families = proto.RepeatedField( - proto.STRING, - number=1, - ) - colors = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class CustomAttribute(proto.Message): - r"""A custom attribute that is not explicitly modeled in - [Product][google.cloud.retail.v2beta.Product]. - - Attributes: - text (Sequence[str]): - The textual values of this custom attribute. For example, - ``["yellow", "green"]`` when the key is "color". - - Empty string is not allowed. Otherwise, an INVALID_ARGUMENT - error is returned. - - Exactly one of - [text][google.cloud.retail.v2beta.CustomAttribute.text] or - [numbers][google.cloud.retail.v2beta.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - numbers (Sequence[float]): - The numerical values of this custom attribute. For example, - ``[2.3, 15.4]`` when the key is "lengths_cm". - - Exactly one of - [text][google.cloud.retail.v2beta.CustomAttribute.text] or - [numbers][google.cloud.retail.v2beta.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - searchable (bool): - This field will only be used when - [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] - of the [Catalog][google.cloud.retail.v2beta.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are searchable by text queries in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2beta.UserEvent]. - - Only set if type - [text][google.cloud.retail.v2beta.CustomAttribute.text] is - set. Otherwise, a INVALID_ARGUMENT error is returned. - - This field is a member of `oneof`_ ``_searchable``. - indexable (bool): - This field will only be used when - [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] - of the [Catalog][google.cloud.retail.v2beta.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are indexed, so that it can be filtered, faceted or - boosted in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2beta.UserEvent]. - - See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter], - [SearchRequest.facet_specs][google.cloud.retail.v2beta.SearchRequest.facet_specs] - and - [SearchRequest.boost_spec][google.cloud.retail.v2beta.SearchRequest.boost_spec] - for more details. - - This field is a member of `oneof`_ ``_indexable``. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - numbers = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - searchable = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - indexable = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - -class FulfillmentInfo(proto.Message): - r"""Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - Attributes: - type_ (str): - The fulfillment type, including commonly used types (such as - pickup in store and same day delivery), and custom types. - Customers have to map custom types to their display names - before rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - place_ids (Sequence[str]): - The IDs for this - [type][google.cloud.retail.v2beta.FulfillmentInfo.type], - such as the store IDs for - [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2beta.FulfillmentInfo.type] - or the region IDs for - [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2beta.FulfillmentInfo.type]. - - A maximum of 3000 values are allowed. Each value must be a - string with a length limit of 30 characters, matching the - pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". - Otherwise, an INVALID_ARGUMENT error is returned. - """ - - type_ = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class Image(proto.Message): - r"""[Product][google.cloud.retail.v2beta.Product] image. Recommendations - AI and Retail Search do not use product images to improve prediction - and search results. However, product images can be returned in - results, and are shown in prediction or search previews in the - console. - - Attributes: - uri (str): - Required. URI of the image. - - This field must be a valid UTF-8 encoded URI with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - height (int): - Height of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - width (int): - Width of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - height = proto.Field( - proto.INT32, - number=2, - ) - width = proto.Field( - proto.INT32, - number=3, - ) - - -class Interval(proto.Message): - r"""A floating point interval. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - minimum (float): - Inclusive lower bound. - - This field is a member of `oneof`_ ``min``. - exclusive_minimum (float): - Exclusive lower bound. - - This field is a member of `oneof`_ ``min``. - maximum (float): - Inclusive upper bound. - - This field is a member of `oneof`_ ``max``. - exclusive_maximum (float): - Exclusive upper bound. - - This field is a member of `oneof`_ ``max``. - """ - - minimum = proto.Field( - proto.DOUBLE, - number=1, - oneof='min', - ) - exclusive_minimum = proto.Field( - proto.DOUBLE, - number=2, - oneof='min', - ) - maximum = proto.Field( - proto.DOUBLE, - number=3, - oneof='max', - ) - exclusive_maximum = proto.Field( - proto.DOUBLE, - number=4, - oneof='max', - ) - - -class PriceInfo(proto.Message): - r"""The price information of a - [Product][google.cloud.retail.v2beta.Product]. - - Attributes: - currency_code (str): - The 3-letter currency code defined in `ISO - 4217 `__. - - If this field is an unrecognizable currency code, an - INVALID_ARGUMENT error is returned. - - The - [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s with the same - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] - must share the same - [currency_code][google.cloud.retail.v2beta.PriceInfo.currency_code]. - Otherwise, a FAILED_PRECONDITION error is returned. - price (float): - Price of the product. - - Google Merchant Center property - `price `__. - Schema.org property - `Offer.price `__. - original_price (float): - Price of the product without any discount. If zero, by - default set to be the - [price][google.cloud.retail.v2beta.PriceInfo.price]. - cost (float): - The costs associated with the sale of a particular product. - Used for gross profit reporting. - - - Profit = - [price][google.cloud.retail.v2beta.PriceInfo.price] - - [cost][google.cloud.retail.v2beta.PriceInfo.cost] - - Google Merchant Center property - `cost_of_goods_sold `__. - price_effective_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2beta.PriceInfo.price] starts - to be effective. This can be set as a future timestamp, and - the [price][google.cloud.retail.v2beta.PriceInfo.price] is - only used for search after - [price_effective_time][google.cloud.retail.v2beta.PriceInfo.price_effective_time]. - If so, the - [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - is used before - [price_effective_time][google.cloud.retail.v2beta.PriceInfo.price_effective_time]. - - Do not set if - [price][google.cloud.retail.v2beta.PriceInfo.price] is - always effective because it will cause additional latency - during search. - price_expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2beta.PriceInfo.price] stops to - be effective. The - [price][google.cloud.retail.v2beta.PriceInfo.price] is used - for search before - [price_expire_time][google.cloud.retail.v2beta.PriceInfo.price_expire_time]. - If this field is set, the - [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - is used after - [price_expire_time][google.cloud.retail.v2beta.PriceInfo.price_expire_time]. - - Do not set if - [price][google.cloud.retail.v2beta.PriceInfo.price] is - always effective because it will cause additional latency - during search. - price_range (google.cloud.retail_v2beta.types.PriceInfo.PriceRange): - Output only. The price range of all the child - [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s grouped - together on the - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]. Only - populated for - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct]. - Do not set this field in API requests. - """ - - class PriceRange(proto.Message): - r"""The price range of all - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. - - Attributes: - price (google.cloud.retail_v2beta.types.Interval): - The inclusive - [Product.pricing_info.price][google.cloud.retail.v2beta.PriceInfo.price] - interval of all - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] having the - same - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. - original_price (google.cloud.retail_v2beta.types.Interval): - The inclusive - [Product.pricing_info.original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - internal of all - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] having the - same - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. - """ - - price = proto.Field( - proto.MESSAGE, - number=1, - message='Interval', - ) - original_price = proto.Field( - proto.MESSAGE, - number=2, - message='Interval', - ) - - currency_code = proto.Field( - proto.STRING, - number=1, - ) - price = proto.Field( - proto.FLOAT, - number=2, - ) - original_price = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - price_effective_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - price_expire_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - price_range = proto.Field( - proto.MESSAGE, - number=7, - message=PriceRange, - ) - - -class Rating(proto.Message): - r"""The rating of a [Product][google.cloud.retail.v2beta.Product]. - - Attributes: - rating_count (int): - The total number of ratings. This value is independent of - the value of - [rating_histogram][google.cloud.retail.v2beta.Rating.rating_histogram]. - - This value must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - average_rating (float): - The average rating of the - [Product][google.cloud.retail.v2beta.Product]. - - The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT - error is returned. - rating_histogram (Sequence[int]): - List of rating counts per rating value (index = rating - 1). - The list is empty if there is no rating. If the list is - non-empty, its size is always 5. Otherwise, an - INVALID_ARGUMENT error is returned. - - For example, [41, 14, 13, 47, 303]. It means that the - [Product][google.cloud.retail.v2beta.Product] got 41 ratings - with 1 star, 14 ratings with 2 star, and so on. - """ - - rating_count = proto.Field( - proto.INT32, - number=1, - ) - average_rating = proto.Field( - proto.FLOAT, - number=2, - ) - rating_histogram = proto.RepeatedField( - proto.INT32, - number=3, - ) - - -class UserInfo(proto.Message): - r"""Information of an end user. - - Attributes: - user_id (str): - Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. - - Always use a hashed value for this ID. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - ip_address (str): - The end user's IP address. This field is used to extract - location information for personalization. - - This field must be either an IPv4 address (e.g. - "104.133.9.80") or an IPv6 address (e.g. - "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an - INVALID_ARGUMENT error is returned. - - This should not be set when: - - - setting - [SearchRequest.user_info][google.cloud.retail.v2beta.SearchRequest.user_info]. - - using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2beta.UserInfo.direct_user_request] - is set. - user_agent (str): - User agent as included in the HTTP header. Required for - getting - [SearchResponse.sponsored_results][google.cloud.retail.v2beta.SearchResponse.sponsored_results]. - - The field must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This should not be set when using the client side event - reporting with GTM or JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2beta.UserInfo.direct_user_request] - is set. - direct_user_request (bool): - True if the request is made directly from the end user, in - which case the - [ip_address][google.cloud.retail.v2beta.UserInfo.ip_address] - and - [user_agent][google.cloud.retail.v2beta.UserInfo.user_agent] - can be populated from the HTTP request. This flag should be - set only if the API request is made directly from the end - user such as a mobile app (and not if a gateway or a server - is processing and pushing the user events). - - This should not be set when using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent]. - """ - - user_id = proto.Field( - proto.STRING, - number=1, - ) - ip_address = proto.Field( - proto.STRING, - number=2, - ) - user_agent = proto.Field( - proto.STRING, - number=3, - ) - direct_user_request = proto.Field( - proto.BOOL, - number=4, - ) - - -class LocalInventory(proto.Message): - r"""The inventory information at a place (e.g. a store) - identified by a place ID. - - Attributes: - place_id (str): - The place ID for the current set of inventory - information. - price_info (google.cloud.retail_v2beta.types.PriceInfo): - Product price and cost information. - - Google Merchant Center property - `price `__. - attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): - Additional local inventory attributes, for example, store - name, promotion tags, etc. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - At most 30 attributes are allowed. - - The key must be a UTF-8 encoded string with a length - limit of 32 characters. - - The key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis - or KEY_1_LIKE_THIS. - - The attribute values must be of the same type (text or - number). - - Only 1 value is allowed for each attribute. - - For text values, the length limit is 256 UTF-8 - characters. - - The attribute does not support search. The ``searchable`` - field should be unset or set to false. - - The max summed total bytes of custom attribute keys and - values per product is 5MiB. - fulfillment_types (Sequence[str]): - Input only. Supported fulfillment types. Valid fulfillment - type values include commonly used types (such as pickup in - store and same day delivery), and custom types. Customers - have to map custom types to their display names before - rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - All the elements must be distinct. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - place_id = proto.Field( - proto.STRING, - number=1, - ) - price_info = proto.Field( - proto.MESSAGE, - number=2, - message='PriceInfo', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='CustomAttribute', - ) - fulfillment_types = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py deleted file mode 100644 index 47e39772..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'CompleteQueryRequest', - 'CompleteQueryResponse', - }, -) - - -class CompleteQueryRequest(proto.Message): - r"""Auto-complete parameters. - - Attributes: - catalog (str): - Required. Catalog for which the completion is performed. - - Full resource name of catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - query (str): - Required. The query used to generate - suggestions. - The maximum number of allowed characters is 255. - visitor_id (str): - Required field. A unique identifier for tracking visitors. - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - language_codes (Sequence[str]): - The language filters applied to the output suggestions. If - set, it should contain the language of the query. If not - set, suggestions are returned without considering language - restrictions. This is the BCP-47 language code, such as - "en-US" or "sr-Latn". For more information, see `Tags for - Identifying - Languages `__. The - maximum number of language codes is 3. - device_type (str): - The device type context for completion suggestions. It is - useful to apply different suggestions on different device - types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the - suggestions are across all device types. - - Supported formats: - - - ``UNKNOWN_DEVICE_TYPE`` - - - ``DESKTOP`` - - - ``MOBILE`` - - - A customized string starts with ``OTHER_``, e.g. - ``OTHER_IPHONE``. - dataset (str): - Determines which dataset to use for fetching completion. - "user-data" will use the imported dataset through - [CompletionService.ImportCompletionData][google.cloud.retail.v2beta.CompletionService.ImportCompletionData]. - "cloud-retail" will use the dataset generated by cloud - retail based on user events. If leave empty, it will use the - "user-data". - - Current supported values: - - - user-data - - - cloud-retail This option requires additional - allowlisting. Before using cloud-retail, contact Cloud - Retail support team first. - max_suggestions (int): - Completion max suggestions. If left unset or set to 0, then - will fallback to the configured value - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions]. - - The maximum allowed max suggestions is 20. If it is set - higher, it will be capped by 20. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - visitor_id = proto.Field( - proto.STRING, - number=7, - ) - language_codes = proto.RepeatedField( - proto.STRING, - number=3, - ) - device_type = proto.Field( - proto.STRING, - number=4, - ) - dataset = proto.Field( - proto.STRING, - number=6, - ) - max_suggestions = proto.Field( - proto.INT32, - number=5, - ) - - -class CompleteQueryResponse(proto.Message): - r"""Response of the auto-complete query. - - Attributes: - completion_results (Sequence[google.cloud.retail_v2beta.types.CompleteQueryResponse.CompletionResult]): - Results of the matching suggestions. The - result list is ordered and the first result is - top suggestion. - attribution_token (str): - A unique complete token. This should be included in the - [UserEvent.completion_detail][google.cloud.retail.v2beta.UserEvent.completion_detail] - for search events resulting from this completion, which - enables accurate attribution of complete model performance. - recent_search_results (Sequence[google.cloud.retail_v2beta.types.CompleteQueryResponse.RecentSearchResult]): - Matched recent searches of this user. The maximum number of - recent searches is 10. This field is a restricted feature. - Contact Retail Search support team if you are interested in - enabling it. - - This feature is only available when - [CompleteQueryRequest.visitor_id][google.cloud.retail.v2beta.CompleteQueryRequest.visitor_id] - field is set and - [UserEvent][google.cloud.retail.v2beta.UserEvent] is - imported. The recent searches satisfy the follow rules: - - - They are ordered from latest to oldest. - - They are matched with - [CompleteQueryRequest.query][google.cloud.retail.v2beta.CompleteQueryRequest.query] - case insensitively. - - They are transformed to lower cases. - - They are UTF-8 safe. - - Recent searches are deduplicated. More recent searches will - be reserved when duplication happens. - """ - - class CompletionResult(proto.Message): - r"""Resource that represents completion results. - - Attributes: - suggestion (str): - The suggestion for the query. - attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): - Custom attributes for the suggestion term. - - - For "user-data", the attributes are additional custom - attributes ingested through BigQuery. - - For "cloud-retail", the attributes are product attributes - generated by Cloud Retail. - """ - - suggestion = proto.Field( - proto.STRING, - number=1, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=common.CustomAttribute, - ) - - class RecentSearchResult(proto.Message): - r"""Recent search of this user. - - Attributes: - recent_search (str): - The recent search query. - """ - - recent_search = proto.Field( - proto.STRING, - number=1, - ) - - completion_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=CompletionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - recent_search_results = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=RecentSearchResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py deleted file mode 100644 index 0c7cdc3d..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'Control', - }, -) - - -class Control(proto.Message): - r"""Configures dynamic serving time metadata that is used to pre - and post process search/recommendation model results. - - 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: - facet_spec (google.cloud.retail_v2beta.types.SearchRequest.FacetSpec): - A facet specification to perform faceted - search. - - This field is a member of `oneof`_ ``control``. - rule (google.cloud.retail_v2beta.types.Rule): - A rule control - a condition-action pair. - Enacts a set action when the condition is - triggered. For example: Boost "gShoe" when query - full matches "Running Shoes". - - This field is a member of `oneof`_ ``control``. - name (str): - Immutable. Fully qualified name - projects/\ */locations/global/catalogs/*/controls/\* - display_name (str): - Required. The human readable control display name. Used in - Retail UI. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is thrown. - associated_serving_config_ids (Sequence[str]): - Output only. List of serving configuration - ids that that are associated with this control. - Note the association is managed via the - ServingConfig, this is an output only - denormalizeed view. Assumed to be in the same - catalog. - solution_types (Sequence[google.cloud.retail_v2beta.types.SolutionType]): - Required. Immutable. The solution types that the serving - config is used for. Currently we support setting only one - type of solution at creation time. - - Only ``SOLUTION_TYPE_SEARCH`` value is supported at the - moment. If no solution type is provided at creation time, - will default to SOLUTION_TYPE_SEARCH. - """ - - facet_spec = proto.Field( - proto.MESSAGE, - number=3, - oneof='control', - message=search_service.SearchRequest.FacetSpec, - ) - rule = proto.Field( - proto.MESSAGE, - number=4, - oneof='control', - message=common.Rule, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - associated_serving_config_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - solution_types = proto.RepeatedField( - proto.ENUM, - number=6, - enum=common.SolutionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py deleted file mode 100644 index 17120bb5..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py +++ /dev/null @@ -1,197 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import control as gcr_control -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'CreateControlRequest', - 'UpdateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - }, -) - - -class CreateControlRequest(proto.Message): - r"""Request for CreateControl method. - - Attributes: - parent (str): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - control (google.cloud.retail_v2beta.types.Control): - Required. The Control to create. - control_id (str): - Required. The ID to use for the Control, which will become - the final component of the Control's resource name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-_/. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - control = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_control.Control, - ) - control_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateControlRequest(proto.Message): - r"""Request for UpdateControl method. - - Attributes: - control (google.cloud.retail_v2beta.types.Control): - Required. The Control to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Control][google.cloud.retail.v2beta.Control] to update. The - following are NOT supported: - - - [Control.name][google.cloud.retail.v2beta.Control.name] - - If not set or empty, all supported fields are updated. - """ - - control = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_control.Control, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteControlRequest(proto.Message): - r"""Request for DeleteControl method. - - Attributes: - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetControlRequest(proto.Message): - r"""Request for GetControl method. - - Attributes: - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListControlsRequest(proto.Message): - r"""Request for ListControls method. - - Attributes: - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - page_size (int): - Optional. Maximum number of results to - return. If unspecified, defaults to 50. Max - allowed value is 1000. - page_token (str): - Optional. A page token, received from a previous - ``ListControls`` call. Provide this to retrieve the - subsequent page. - filter (str): - Optional. A filter to apply on the list results. Supported - features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2beta.ListControlsRequest.filter] - is unset. - - List controls that are used in a single ServingConfig: - 'serving_config = "boosted_home_page_cvr"' - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListControlsResponse(proto.Message): - r"""Response for ListControls method. - - Attributes: - controls (Sequence[google.cloud.retail_v2beta.types.Control]): - All the Controls for a given catalog. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - controls = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_control.Control, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py deleted file mode 100644 index b020964a..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py +++ /dev/null @@ -1,134 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - }, -) - - -class ExportErrorsConfig(proto.Message): - r"""Configuration of destination for Export related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage path for import errors. This must be an - empty, existing Cloud Storage bucket. Export errors will be - written to a file in this bucket, one per line, as a - JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ExportMetadata(proto.Message): - r"""Metadata related to the progress of the Export operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class ExportProductsResponse(proto.Message): - r"""Response of the ExportProductsRequest. If the long running - operation is done, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2beta.types.ExportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExportErrorsConfig', - ) - - -class ExportUserEventsResponse(proto.Message): - r"""Response of the ExportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2beta.types.ExportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExportErrorsConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py deleted file mode 100644 index a32de943..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py +++ /dev/null @@ -1,691 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import user_event -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'GcsSource', - 'BigQuerySource', - 'ProductInlineSource', - 'UserEventInlineSource', - 'ImportErrorsConfig', - 'ImportProductsRequest', - 'ImportUserEventsRequest', - 'ImportCompletionDataRequest', - 'ProductInputConfig', - 'UserEventInputConfig', - 'CompletionDataInputConfig', - 'ImportMetadata', - 'ImportProductsResponse', - 'ImportUserEventsResponse', - 'UserEventImportSummary', - 'ImportCompletionDataResponse', - }, -) - - -class GcsSource(proto.Message): - r"""Google Cloud Storage location for input content. - format. - - Attributes: - input_uris (Sequence[str]): - Required. Google Cloud Storage URIs to input files. URI can - be up to 2000 characters long. URIs can match the full - object path (for example, - ``gs://bucket/directory/object.json``) or a pattern matching - one or more files, such as ``gs://bucket/directory/*.json``. - A request can contain at most 100 files, and each file can - be up to 2 GB. See `Importing product - information `__ - for the expected file format and setup instructions. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2beta.Product] per line. - Each product must have a valid - [Product.id][google.cloud.retail.v2beta.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2beta.UserEvent] per - line. - - ``user_event_ga360``: Using - https://support.google.com/analytics/answer/3437719. - - Supported values for control imports: - - - 'control' (default): One JSON - [Control][google.cloud.retail.v2beta.Control] per line. - - Supported values for catalog attribute imports: - - - 'catalog_attribute' (default): One CSV - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - per line. - """ - - input_uris = proto.RepeatedField( - proto.STRING, - number=1, - ) - data_schema = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""BigQuery source import data from. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - partition_date (google.type.date_pb2.Date): - BigQuery time partitioned table's \_PARTITIONDATE in - YYYY-MM-DD format. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2beta.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - - This field is a member of `oneof`_ ``partition``. - project_id (str): - The project ID (can be project # or ID) that - the BigQuery source is in with a length limit of - 128 characters. If not specified, inherits the - project ID from the parent request. - dataset_id (str): - Required. The BigQuery data set to copy the - data from with a length limit of 1,024 - characters. - table_id (str): - Required. The BigQuery table to copy the data - from with a length limit of 1,024 characters. - gcs_staging_dir (str): - Intermediate Cloud Storage directory used for - the import with a length limit of 2,000 - characters. Can be specified if one wants to - have the BigQuery export to a specific Cloud - Storage directory. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2beta.Product] per line. - Each product must have a valid - [Product.id][google.cloud.retail.v2beta.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2beta.UserEvent] per - line. - - ``user_event_ga360``: The schema is available here: - https://support.google.com/analytics/answer/3437719. - - ``user_event_ga4``: This feature is in private preview. - Please contact the support team for importing Google - Analytics 4 events. The schema is available here: - https://support.google.com/analytics/answer/7029846. - - Supported values for auto-completion imports: - - - ``suggestions`` (default): One JSON completion suggestion - per line. - - ``denylist``: One JSON deny suggestion per line. - - ``allowlist``: One JSON allow suggestion per line. - """ - - partition_date = proto.Field( - proto.MESSAGE, - number=6, - oneof='partition', - message=date_pb2.Date, - ) - project_id = proto.Field( - proto.STRING, - number=5, - ) - dataset_id = proto.Field( - proto.STRING, - number=1, - ) - table_id = proto.Field( - proto.STRING, - number=2, - ) - gcs_staging_dir = proto.Field( - proto.STRING, - number=3, - ) - data_schema = proto.Field( - proto.STRING, - number=4, - ) - - -class ProductInlineSource(proto.Message): - r"""The inline source for the input config for ImportProducts - method. - - Attributes: - products (Sequence[google.cloud.retail_v2beta.types.Product]): - Required. A list of products to update/create. Each product - must have a valid - [Product.id][google.cloud.retail.v2beta.Product.id]. - Recommended max of 100 items. - """ - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=product.Product, - ) - - -class UserEventInlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (Sequence[google.cloud.retail_v2beta.types.UserEvent]): - Required. A list of user events to import. - Recommended max of 10k items. - """ - - user_events = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - -class ImportErrorsConfig(proto.Message): - r"""Configuration of destination for Import related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage prefix for import errors. This must be - an empty, existing Cloud Storage directory. Import errors - will be written to sharded files in this directory, one per - line, as a JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportProductsRequest(proto.Message): - r"""Request message for Import methods. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` - - If no updateMask is specified, requires products.create - permission. If updateMask is specified, requires - products.update permission. - request_id (str): - Deprecated. This field has no effect. - input_config (google.cloud.retail_v2beta.types.ProductInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - imported 'products' to update. If not set, will - by default update all fields. - reconciliation_mode (google.cloud.retail_v2beta.types.ImportProductsRequest.ReconciliationMode): - The mode of reconciliation between existing products and the - products to be imported. Defaults to - [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2beta.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2beta.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - """ - class ReconciliationMode(proto.Enum): - r"""Indicates how imported products are reconciled with the - existing products created or imported before. - """ - RECONCILIATION_MODE_UNSPECIFIED = 0 - INCREMENTAL = 1 - FULL = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - request_id = proto.Field( - proto.STRING, - number=6, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='ProductInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - reconciliation_mode = proto.Field( - proto.ENUM, - number=5, - enum=ReconciliationMode, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=7, - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog`` - input_config (google.cloud.retail_v2beta.types.UserEventInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. Cannot be set for inline user - event imports. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='UserEventInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - - -class ImportCompletionDataRequest(proto.Message): - r"""Request message for ImportCompletionData methods. - - Attributes: - parent (str): - Required. The catalog which the suggestions dataset belongs - to. - - Format: - ``projects/1234/locations/global/catalogs/default_catalog``. - input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): - Required. The desired input location of the - data. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='CompletionDataInputConfig', - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=3, - ) - - -class ProductInputConfig(proto.Message): - r"""The input config source for products. - - 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: - product_inline_source (google.cloud.retail_v2beta.types.ProductInlineSource): - The Inline source for the input content for - products. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2beta.types.GcsSource): - Google Cloud Storage location for the input - content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - product_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='ProductInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class UserEventInputConfig(proto.Message): - r"""The input config source for user events. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - user_event_inline_source (google.cloud.retail_v2beta.types.UserEventInlineSource): - Required. The Inline source for the input - content for UserEvents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2beta.types.GcsSource): - Required. Google Cloud Storage location for - the input content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): - Required. BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - user_event_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='UserEventInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class CompletionDataInputConfig(proto.Message): - r"""The input config source for completion data. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): - Required. BigQuery input source. - Add the IAM permission "BigQuery Data Viewer" - for - cloud-retail-customer-data-access@system.gserviceaccount.com - before using this feature otherwise an error is - thrown. - - This field is a member of `oneof`_ ``source``. - """ - - big_query_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='BigQuerySource', - ) - - -class ImportMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - request_id (str): - Deprecated. This field is never set. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=3, - ) - failure_count = proto.Field( - proto.INT64, - number=4, - ) - request_id = proto.Field( - proto.STRING, - number=5, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=6, - ) - - -class ImportProductsResponse(proto.Message): - r"""Response of the - [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. - If the long running operation is done, then this message is returned - by the google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - import_summary (google.cloud.retail_v2beta.types.UserEventImportSummary): - Aggregated statistics of user event import - status. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - import_summary = proto.Field( - proto.MESSAGE, - number=3, - message='UserEventImportSummary', - ) - - -class UserEventImportSummary(proto.Message): - r"""A summary of import result. The UserEventImportSummary - summarizes the import status for user events. - - Attributes: - joined_events_count (int): - Count of user events imported with complete - existing catalog information. - unjoined_events_count (int): - Count of user events imported, but with - catalog information not found in the imported - catalog. - """ - - joined_events_count = proto.Field( - proto.INT64, - number=1, - ) - unjoined_events_count = proto.Field( - proto.INT64, - number=2, - ) - - -class ImportCompletionDataResponse(proto.Message): - r"""Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. - 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 (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py deleted file mode 100644 index f31ba819..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import user_event as gcr_user_event -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'PredictRequest', - 'PredictResponse', - }, -) - - -class PredictRequest(proto.Message): - r"""Request message for Predict method. - - Attributes: - placement (str): - Required. Full resource name of the format: - {name=projects/*/locations/global/catalogs/default_catalog/placements/*} - The ID of the Recommendations AI placement. Before you can - request predictions from your model, you must create at - least one placement for it. For more information, see - `Managing - placements `__. - - The full list of available placements can be seen at - https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements - user_event (google.cloud.retail_v2beta.types.UserEvent): - Required. Context about the user, what they - are looking at and what action they took to - trigger the predict request. Note that this user - event detail won't be ingested to userEvent - logs. Thus, a separate userEvent write request - is required for event logging. - page_size (int): - Maximum number of results to return per page. - Set this property to the number of prediction - results needed. If zero, the service will choose - a reasonable default. The maximum allowed value - is 100. Values above 100 will be coerced to 100. - page_token (str): - The previous PredictResponse.next_page_token. - filter (str): - Filter for restricting prediction results with a length - limit of 5,000 characters. Accepts values for tags and the - ``filterOutOfStockItems`` flag. - - - Tag expressions. Restricts predictions to products that - match all of the specified tags. Boolean operators ``OR`` - and ``NOT`` are supported if the expression is enclosed - in parentheses, and must be separated from the tag values - by a space. ``-"tagA"`` is also supported and is - equivalent to ``NOT "tagA"``. Tag values must be double - quoted UTF-8 encoded strings with a size limit of 1,000 - characters. - - Note: "Recently viewed" models don't support tag - filtering at the moment. - - - filterOutOfStockItems. Restricts predictions to products - that do not have a stockState value of OUT_OF_STOCK. - - Examples: - - - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT - "promotional") - - filterOutOfStockItems tag=(-"promotional") - - filterOutOfStockItems - - If your filter blocks all prediction results, the API will - return generic (unfiltered) popular products. If you only - want results strictly matching the filters, set - ``strictFiltering`` to True in ``PredictRequest.params`` to - receive empty results instead. Note that the API will never - return items with storageStatus of "EXPIRED" or "DELETED" - regardless of filter choices. - validate_only (bool): - Use validate only mode for this prediction - query. If set to true, a dummy model will be - used that returns arbitrary products. Note that - the validate only mode should only be used for - testing the API, or if the model is not ready. - params (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional domain specific parameters for the predictions. - - Allowed values: - - - ``returnProduct``: Boolean. If set to true, the - associated product object will be returned in the - ``results.metadata`` field in the prediction response. - - ``returnScore``: Boolean. If set to true, the prediction - 'score' corresponding to each returned product will be - set in the ``results.metadata`` field in the prediction - response. The given 'score' indicates the probability of - an product being clicked/purchased given the user's - context and history. - - ``strictFiltering``: Boolean. True by default. If set to - false, the service will return generic (unfiltered) - popular products instead of empty if your filter blocks - all prediction results. - - ``priceRerankLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of - {'no-price-reranking', 'low-price-reranking', - 'medium-price-reranking', 'high-price-reranking'}. This - gives request-level control and adjusts prediction - results based on product price. - - ``diversityLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of {'no-diversity', - 'low-diversity', 'medium-diversity', 'high-diversity', - 'auto-diversity'}. This gives request-level control and - adjusts prediction results based on product category. - labels (Mapping[str, str]): - The labels applied to a resource must meet the following - requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters, and cannot be empty. Values can - be empty, and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - """ - - placement = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - validate_only = proto.Field( - proto.BOOL, - number=6, - ) - params = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class PredictResponse(proto.Message): - r"""Response message for predict method. - - Attributes: - results (Sequence[google.cloud.retail_v2beta.types.PredictResponse.PredictionResult]): - A list of recommended products. The order - represents the ranking (from the most relevant - product to the least). - attribution_token (str): - A unique attribution token. This should be included in the - [UserEvent][google.cloud.retail.v2beta.UserEvent] logs - resulting from this recommendation, which enables accurate - attribution of recommendation model performance. - missing_ids (Sequence[str]): - IDs of products in the request that were - missing from the inventory. - validate_only (bool): - True if the validateOnly property was set in - the request. - """ - - class PredictionResult(proto.Message): - r"""PredictionResult represents the recommendation prediction - results. - - Attributes: - id (str): - ID of the recommended product - metadata (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional product metadata / annotations. - - Possible values: - - - ``product``: JSON representation of the product. Will be - set if ``returnProduct`` is set to true in - ``PredictRequest.params``. - - ``score``: Prediction score in double value. Will be set - if ``returnScore`` is set to true in - ``PredictRequest.params``. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - metadata = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=PredictionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - missing_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py deleted file mode 100644 index bd0de773..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py +++ /dev/null @@ -1,705 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'Product', - }, -) - - -class Product(proto.Message): - r"""Product captures all metadata information of items to be - recommended or searched. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this product becomes unavailable for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - If it is set, the - [Product][google.cloud.retail.v2beta.Product] is not - available for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - after - [expire_time][google.cloud.retail.v2beta.Product.expire_time]. - However, the product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - [expire_time][google.cloud.retail.v2beta.Product.expire_time] - must be later than - [available_time][google.cloud.retail.v2beta.Product.available_time] - and - [publish_time][google.cloud.retail.v2beta.Product.publish_time], - otherwise an INVALID_ARGUMENT error is thrown. - - Corresponding properties: Google Merchant Center property - `expiration_date `__. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Input only. The TTL (time to live) of the product. - - If it is set, it must be a non-negative value, and - [expire_time][google.cloud.retail.v2beta.Product.expire_time] - is set as current timestamp plus - [ttl][google.cloud.retail.v2beta.Product.ttl]. The derived - [expire_time][google.cloud.retail.v2beta.Product.expire_time] - is returned in the output and - [ttl][google.cloud.retail.v2beta.Product.ttl] is left blank - when retrieving the - [Product][google.cloud.retail.v2beta.Product]. - - If it is set, the product is not available for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - after current timestamp plus - [ttl][google.cloud.retail.v2beta.Product.ttl]. However, the - product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This field is a member of `oneof`_ ``expiration``. - name (str): - Immutable. Full resource name of the product, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. - id (str): - Immutable. [Product][google.cloud.retail.v2beta.Product] - identifier, which is the final component of - [name][google.cloud.retail.v2beta.Product.name]. For - example, this field is "id_1", if - [name][google.cloud.retail.v2beta.Product.name] is - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `id `__. - Schema.org property - `Product.sku `__. - type_ (google.cloud.retail_v2beta.types.Product.Type): - Immutable. The type of the product. Default to - [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2beta.ProductLevelConfig.ingestion_product_type] - if unset. - primary_product_id (str): - Variant group identifier. Must be an - [id][google.cloud.retail.v2beta.Product.id], with the same - parent branch with this product. Otherwise, an error is - thrown. - - For - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]s, this field - can only be empty or set to the same value as - [id][google.cloud.retail.v2beta.Product.id]. - - For VARIANT [Product][google.cloud.retail.v2beta.Product]s, - this field cannot be empty. A maximum of 2,000 products are - allowed to share the same - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `item_group_id `__. - Schema.org property - `Product.inProductGroupWithID `__. - collection_member_ids (Sequence[str]): - The [id][google.cloud.retail.v2beta.Product.id] of the - collection members when - [type][google.cloud.retail.v2beta.Product.type] is - [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION]. - - Non-existent product ids are allowed. The - [type][google.cloud.retail.v2beta.Product.type] of the - members must be either - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - or - [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - otherwise and INVALID_ARGUMENT error is thrown. Should not - set it for other types. A maximum of 1000 values are - allowed. Otherwise, an INVALID_ARGUMENT error is return. - gtin (str): - The Global Trade Item Number (GTIN) of the product. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This field must be a Unigram. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `gtin `__. - Schema.org property - `Product.isbn `__, - `Product.gtin8 `__, - `Product.gtin12 `__, - `Product.gtin13 `__, or - `Product.gtin14 `__. - - If the value is not a valid GTIN, an INVALID_ARGUMENT error - is returned. - categories (Sequence[str]): - Product categories. This field is repeated for supporting - one product belonging to several parallel categories. - Strongly recommended using the full path for better search / - recommendation quality. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - For example, if a shoes product belongs to both ["Shoes & - Accessories" -> "Shoes"] and ["Sports & Fitness" -> - "Athletic Clothing" -> "Shoes"], it could be represented as: - - :: - - "categories": [ - "Shoes & Accessories > Shoes", - "Sports & Fitness > Athletic Clothing > Shoes" - ] - - Must be set for - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] otherwise an - INVALID_ARGUMENT error is returned. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2beta.Product]. Empty values - are not allowed. Each value must be a UTF-8 encoded string - with a length limit of 5,000 characters. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `google_product_category `__. - Schema.org property [Product.category] - (https://schema.org/category). - title (str): - Required. Product title. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `title `__. - Schema.org property - `Product.name `__. - brands (Sequence[str]): - The brands of the product. - - A maximum of 30 brands are allowed. Each brand must be a - UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `brand `__. - Schema.org property - `Product.brand `__. - description (str): - Product description. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `description `__. - Schema.org property - `Product.description `__. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. - - For product prediction, this field is ignored and the model - automatically detects the text language. The - [Product][google.cloud.retail.v2beta.Product] can include - text in different languages, but duplicating - [Product][google.cloud.retail.v2beta.Product]s to provide - text in multiple languages can result in degraded model - performance. - - For product search this field is in use. It defaults to - "en-US" if unset. - attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): - Highly encouraged. Extra product attributes to be included. - For example, for products, this could include the store - name, vendor, style, color, etc. These are very strong - signals for recommendation model, thus we highly recommend - providing the attributes here. - - Features that can take on one of a limited number of - possible values. Two types of features can be set are: - - Textual features. some examples would be the brand/maker of - a product, or country of a customer. Numerical features. - Some examples would be the height/weight of a product, or - age of a customer. - - For example: - ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - Max entries count: 200. - - The key must be a UTF-8 encoded string with a length - limit of 128 characters. - - For indexable attribute, the key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, - ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a - non-empty UTF-8 encoded string with a length limit of 256 - characters. - - For number attributes, at most 400 values are allowed. - tags (Sequence[str]): - Custom tags associated with the product. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2beta.Product]. This value - must be a UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This tag can be used for filtering recommendation results by - passing the tag as part of the - [PredictRequest.filter][google.cloud.retail.v2beta.PredictRequest.filter]. - - Corresponding properties: Google Merchant Center property - `custom_label_0–4 `__. - price_info (google.cloud.retail_v2beta.types.PriceInfo): - Product price and cost information. - - Corresponding properties: Google Merchant Center property - `price `__. - rating (google.cloud.retail_v2beta.types.Rating): - The rating of this product. - available_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this - [Product][google.cloud.retail.v2beta.Product] becomes - available for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - availability (google.cloud.retail_v2beta.types.Product.Availability): - The online availability of the - [Product][google.cloud.retail.v2beta.Product]. Default to - [Availability.IN_STOCK][google.cloud.retail.v2beta.Product.Availability.IN_STOCK]. - - Corresponding properties: Google Merchant Center property - `availability `__. - Schema.org property - `Offer.availability `__. - available_quantity (google.protobuf.wrappers_pb2.Int32Value): - The available quantity of the item. - fulfillment_info (Sequence[google.cloud.retail_v2beta.types.FulfillmentInfo]): - Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - All the elements must have distinct - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type]. - Otherwise, an INVALID_ARGUMENT error is returned. - uri (str): - Canonical URL directly linking to the product detail page. - - It is strongly recommended to provide a valid uri for the - product, otherwise the service performance could be - significantly degraded. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `link `__. - Schema.org property `Offer.url `__. - images (Sequence[google.cloud.retail_v2beta.types.Image]): - Product images for the product. We highly recommend putting - the main image first. - - A maximum of 300 images are allowed. - - Corresponding properties: Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - audience (google.cloud.retail_v2beta.types.Audience): - The target group associated with a given - audience (e.g. male, veterans, car owners, - musicians, etc.) of the product. - color_info (google.cloud.retail_v2beta.types.ColorInfo): - The color of the product. - - Corresponding properties: Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - sizes (Sequence[str]): - The size of the product. To represent different size systems - or size types, consider using this format: - [[[size_system:]size_type:]size_value]. - - For example, in "US:MENS:M", "US" represents size system; - "MENS" represents size type; "M" represents size value. In - "GIRLS:27", size system is empty; "GIRLS" represents size - type; "27" represents size value. In "32 inches", both size - system and size type are empty, while size value is "32 - inches". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2beta.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `size `__, - `size_type `__, - and - `size_system `__. - Schema.org property - `Product.size `__. - materials (Sequence[str]): - The material of the product. For example, "leather", - "wooden". - - A maximum of 20 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 200 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `material `__. - Schema.org property - `Product.material `__. - patterns (Sequence[str]): - The pattern or graphic print of the product. For example, - "striped", "polka dot", "paisley". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2beta.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `pattern `__. - Schema.org property - `Product.pattern `__. - conditions (Sequence[str]): - The condition of the product. Strongly encouraged to use the - standard values: "new", "refurbished", "used". - - A maximum of 1 value is allowed per - [Product][google.cloud.retail.v2beta.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `condition `__. - Schema.org property - `Offer.itemCondition `__. - promotions (Sequence[google.cloud.retail_v2beta.types.Promotion]): - The promotions applied to the product. A maximum of 10 - values are allowed per - [Product][google.cloud.retail.v2beta.Product]. Only - [Promotion.promotion_id][google.cloud.retail.v2beta.Promotion.promotion_id] - will be used, other fields will be ignored if set. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the product is published by the retailer - for the first time, which indicates the freshness of the - products. Note that this field is different from - [available_time][google.cloud.retail.v2beta.Product.available_time], - given it purely describes product freshness regardless of - when it is available on search and recommendation. - retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the - [Product][google.cloud.retail.v2beta.Product]s are returned - in - [SearchResponse][google.cloud.retail.v2beta.SearchResponse]. - - Supported fields for all - [type][google.cloud.retail.v2beta.Product.type]s: - - - [audience][google.cloud.retail.v2beta.Product.audience] - - [availability][google.cloud.retail.v2beta.Product.availability] - - [brands][google.cloud.retail.v2beta.Product.brands] - - [color_info][google.cloud.retail.v2beta.Product.color_info] - - [conditions][google.cloud.retail.v2beta.Product.conditions] - - [gtin][google.cloud.retail.v2beta.Product.gtin] - - [materials][google.cloud.retail.v2beta.Product.materials] - - [name][google.cloud.retail.v2beta.Product.name] - - [patterns][google.cloud.retail.v2beta.Product.patterns] - - [price_info][google.cloud.retail.v2beta.Product.price_info] - - [rating][google.cloud.retail.v2beta.Product.rating] - - [sizes][google.cloud.retail.v2beta.Product.sizes] - - [title][google.cloud.retail.v2beta.Product.title] - - [uri][google.cloud.retail.v2beta.Product.uri] - - Supported fields only for - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION]: - - - [categories][google.cloud.retail.v2beta.Product.categories] - - [description][google.cloud.retail.v2beta.Product.description] - - [images][google.cloud.retail.v2beta.Product.images] - - Supported fields only for - [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT]: - - - Only the first image in - [images][google.cloud.retail.v2beta.Product.images] - - To mark - [attributes][google.cloud.retail.v2beta.Product.attributes] - as retrievable, include paths of the form "attributes.key" - where "key" is the key of a custom attribute, as specified - in - [attributes][google.cloud.retail.v2beta.Product.attributes]. - - For - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION], - the following fields are always returned in - [SearchResponse][google.cloud.retail.v2beta.SearchResponse] - by default: - - - [name][google.cloud.retail.v2beta.Product.name] - - For - [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT], - the following fields are always returned in by default: - - - [name][google.cloud.retail.v2beta.Product.name] - - [color_info][google.cloud.retail.v2beta.Product.color_info] - - Maximum number of paths is 30. Otherwise, an - INVALID_ARGUMENT error is returned. - - Note: Returning more fields in - [SearchResponse][google.cloud.retail.v2beta.SearchResponse] - may increase response payload size and serving latency. - variants (Sequence[google.cloud.retail_v2beta.types.Product]): - Output only. Product variants grouped together on primary - product which share similar product attributes. It's - automatically grouped by - [primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] - for all the product variants. Only populated for - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct]. - Do not set this field in API requests. - """ - class Type(proto.Enum): - r"""The type of this product.""" - TYPE_UNSPECIFIED = 0 - PRIMARY = 1 - VARIANT = 2 - COLLECTION = 3 - - class Availability(proto.Enum): - r"""Product availability. If this field is unspecified, the - product is assumed to be in stock. - """ - AVAILABILITY_UNSPECIFIED = 0 - IN_STOCK = 1 - OUT_OF_STOCK = 2 - PREORDER = 3 - BACKORDER = 4 - - expire_time = proto.Field( - proto.MESSAGE, - number=16, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl = proto.Field( - proto.MESSAGE, - number=17, - oneof='expiration', - message=duration_pb2.Duration, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - type_ = proto.Field( - proto.ENUM, - number=3, - enum=Type, - ) - primary_product_id = proto.Field( - proto.STRING, - number=4, - ) - collection_member_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - gtin = proto.Field( - proto.STRING, - number=6, - ) - categories = proto.RepeatedField( - proto.STRING, - number=7, - ) - title = proto.Field( - proto.STRING, - number=8, - ) - brands = proto.RepeatedField( - proto.STRING, - number=9, - ) - description = proto.Field( - proto.STRING, - number=10, - ) - language_code = proto.Field( - proto.STRING, - number=11, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=12, - message=common.CustomAttribute, - ) - tags = proto.RepeatedField( - proto.STRING, - number=13, - ) - price_info = proto.Field( - proto.MESSAGE, - number=14, - message=common.PriceInfo, - ) - rating = proto.Field( - proto.MESSAGE, - number=15, - message=common.Rating, - ) - available_time = proto.Field( - proto.MESSAGE, - number=18, - message=timestamp_pb2.Timestamp, - ) - availability = proto.Field( - proto.ENUM, - number=19, - enum=Availability, - ) - available_quantity = proto.Field( - proto.MESSAGE, - number=20, - message=wrappers_pb2.Int32Value, - ) - fulfillment_info = proto.RepeatedField( - proto.MESSAGE, - number=21, - message=common.FulfillmentInfo, - ) - uri = proto.Field( - proto.STRING, - number=22, - ) - images = proto.RepeatedField( - proto.MESSAGE, - number=23, - message=common.Image, - ) - audience = proto.Field( - proto.MESSAGE, - number=24, - message=common.Audience, - ) - color_info = proto.Field( - proto.MESSAGE, - number=25, - message=common.ColorInfo, - ) - sizes = proto.RepeatedField( - proto.STRING, - number=26, - ) - materials = proto.RepeatedField( - proto.STRING, - number=27, - ) - patterns = proto.RepeatedField( - proto.STRING, - number=28, - ) - conditions = proto.RepeatedField( - proto.STRING, - number=29, - ) - promotions = proto.RepeatedField( - proto.MESSAGE, - number=34, - message=promotion.Promotion, - ) - publish_time = proto.Field( - proto.MESSAGE, - number=33, - message=timestamp_pb2.Timestamp, - ) - retrievable_fields = proto.Field( - proto.MESSAGE, - number=30, - message=field_mask_pb2.FieldMask, - ) - variants = proto.RepeatedField( - proto.MESSAGE, - number=31, - message='Product', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py deleted file mode 100644 index 06a23d13..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py +++ /dev/null @@ -1,844 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'CreateProductRequest', - 'GetProductRequest', - 'UpdateProductRequest', - 'DeleteProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'SetInventoryRequest', - 'SetInventoryMetadata', - 'SetInventoryResponse', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesResponse', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesResponse', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesResponse', - }, -) - - -class CreateProductRequest(proto.Message): - r"""Request message for [CreateProduct][] method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - product (google.cloud.retail_v2beta.types.Product): - Required. The [Product][google.cloud.retail.v2beta.Product] - to create. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2beta.Product], which will - become the final component of the - [Product.name][google.cloud.retail.v2beta.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2beta.Product]s with the same - [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - product_id = proto.Field( - proto.STRING, - number=3, - ) - - -class GetProductRequest(proto.Message): - r"""Request message for [GetProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested - [Product][google.cloud.retail.v2beta.Product] does not - exist, a NOT_FOUND error is returned. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateProductRequest(proto.Message): - r"""Request message for [UpdateProduct][] method. - - Attributes: - product (google.cloud.retail_v2beta.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Product][google.cloud.retail.v2beta.Product] to update. The - immutable and output only fields are NOT supported. If not - set, all supported fields (the fields that are neither - immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - a new [Product][google.cloud.retail.v2beta.Product] will be - created. In this situation, ``update_mask`` is ignored. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteProductRequest(proto.Message): - r"""Request message for [DeleteProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2beta.Product] to delete - can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] with more than - one - [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2beta.Product] will be - deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProductsRequest(proto.Message): - r"""Request message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - - Attributes: - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list products - under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2beta.Product]s under this - branch, regardless of whether or not this branch exists, a - PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of - [Product][google.cloud.retail.v2beta.Product]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 - [ListProductsResponse.next_page_token][google.cloud.retail.v2beta.ListProductsResponse.next_page_token], - received from a previous - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - filter (str): - A filter to apply on the list results. Supported features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2beta.ListProductsRequest.filter] - is unset. - - List - [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s sharing - the same - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]. For - example: ``primary_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2beta.Product]s - bundled in a - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product]. For - example: ``collection_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2beta.Product]s with - a partibular type. For example: ``type = "PRIMARY"`` - ``type = "VARIANT"`` ``type = "COLLECTION"`` - - If the field is unrecognizable, an INVALID_ARGUMENT error is - returned. - - If the specified - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] or - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product] does not - exist, a NOT_FOUND error is returned. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields of [Product][google.cloud.retail.v2beta.Product] - to return in the responses. If not set or empty, the - following fields are returned: - - - [Product.name][google.cloud.retail.v2beta.Product.name] - - [Product.id][google.cloud.retail.v2beta.Product.id] - - [Product.title][google.cloud.retail.v2beta.Product.title] - - [Product.uri][google.cloud.retail.v2beta.Product.uri] - - [Product.images][google.cloud.retail.v2beta.Product.images] - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.brands][google.cloud.retail.v2beta.Product.brands] - - If "*" is provided, all fields are returned. - [Product.name][google.cloud.retail.v2beta.Product.name] is - always returned no matter what mask is set. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class ListProductsResponse(proto.Message): - r"""Response message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - - Attributes: - products (Sequence[google.cloud.retail_v2beta.types.Product]): - The [Product][google.cloud.retail.v2beta.Product]s. - next_page_token (str): - A token that can be sent as - [ListProductsRequest.page_token][google.cloud.retail.v2beta.ListProductsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class SetInventoryRequest(proto.Message): - r"""Request message for [SetInventory][] method. - - Attributes: - inventory (google.cloud.retail_v2beta.types.Product): - Required. The inventory information to update. The allowable - fields to update are: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product] named in - [Product.name][google.cloud.retail.v2beta.Product.name], - regardless of whether or not it exists, a PERMISSION_DENIED - error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2beta.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting the - last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of fulfillment - types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear in - [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types have - empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following inventory - fields: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - - If a full overwrite of inventory information while ignoring - timestamps is needed, [UpdateProduct][] should be invoked - instead. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2beta.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the request is issued, used to - prevent out-of-order updates on inventory fields - with the last update time recorded. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] with name - [Product.name][google.cloud.retail.v2beta.Product.name] is - not found, the inventory update will still be processed and - retained for at most 1 day until the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - inventory = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - set_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - set_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=4, - ) - - -class SetInventoryMetadata(proto.Message): - r"""Metadata related to the progress of the SetInventory operation. - Currently empty because there is no meaningful metadata populated - from the [SetInventory][] method. - - """ - - -class SetInventoryResponse(proto.Message): - r"""Response of the SetInventoryRequest. Currently empty because there - is no meaningful response populated from the [SetInventory][] - method. - - """ - - -class AddFulfillmentPlacesRequest(proto.Message): - r"""Request message for [AddFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery" to be added for this - [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type]. - Duplicate IDs will be automatically ignored. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If the total number of place IDs exceeds 2000 for this - [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type] - after adding, then the update will be rejected. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - the fulfillment information will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - add_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class AddFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the AddFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [AddFulfillmentPlaces][] method. - - """ - - -class AddFulfillmentPlacesResponse(proto.Message): - r"""Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - - -class AddLocalInventoriesRequest(proto.Message): - r"""Request message for [AddLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - local_inventories (Sequence[google.cloud.retail_v2beta.types.LocalInventory]): - Required. A list of inventory information at - difference places. Each place is identified by - its place ID. At most 3000 inventories are - allowed per request. - add_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided list of - [LocalInventory][google.cloud.retail.v2beta.LocalInventory] - to update. The field is updated to the provided value. - - If a field is set while the place does not have a previous - local inventory, the local inventory at that store is - created. - - If a field is set while the value of that field is not - provided, the original field value, if it exists, is - deleted. - - If the mask is not set or set with empty paths, all - inventory fields will be updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory updates are - issued. Used to prevent out-of-order updates on - local inventory fields. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - the local inventory will still be processed and retained for - at most 1 day and processed once the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - local_inventories = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.LocalInventory, - ) - add_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - add_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=6, - ) - - -class AddLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the AddLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [AddLocalInventories][] method. - - """ - - -class AddLocalInventoriesResponse(proto.Message): - r"""Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesRequest(proto.Message): - r"""Request message for [RemoveLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - place_ids (Sequence[str]): - Required. A list of place IDs to have their - inventory deleted. At most 3000 place IDs are - allowed per request. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory deletions are - issued. Used to prevent out-of-order updates and - deletions on local inventory fields. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - the local inventory removal request will still be processed - and retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class RemoveLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesResponse(proto.Message): - r"""Response of the [RemoveLocalInventories][] API. Currently empty - because there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - - -class RemoveFulfillmentPlacesRequest(proto.Message): - r"""Request message for [RemoveFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2beta.RemoveFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery", to be removed for this - [type][google.cloud.retail.v2beta.RemoveFulfillmentPlacesRequest.type]. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - the fulfillment information will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class RemoveFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveFulfillmentPlaces][] method. - - """ - - -class RemoveFulfillmentPlacesResponse(proto.Message): - r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty - because there is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py deleted file mode 100644 index be192a70..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'Promotion', - }, -) - - -class Promotion(proto.Message): - r"""Promotion information. - - Attributes: - promotion_id (str): - ID of the promotion. For example, "free gift". - - The value must be a UTF-8 encoded string with a length limit - of 128 characters, and match the pattern: - ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or - ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is - returned. - - Google Merchant Center property - `promotion `__. - """ - - promotion_id = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py deleted file mode 100644 index 95c99126..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py +++ /dev/null @@ -1,107 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - }, -) - - -class PurgeMetadata(proto.Message): - r"""Metadata related to the progress of the Purge operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - """ - - -class PurgeUserEventsRequest(proto.Message): - r"""Request message for PurgeUserEvents method. - - Attributes: - parent (str): - Required. The resource name of the catalog under which the - events are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}`` - filter (str): - Required. The filter string to specify the events to be - deleted with a length limit of 5,000 characters. Empty - string filter is not allowed. The eligible fields for - filtering are: - - - ``eventType``: Double quoted - [UserEvent.event_type][google.cloud.retail.v2beta.UserEvent.event_type] - string. - - ``eventTime``: in ISO 8601 "zulu" format. - - ``visitorId``: Double quoted string. Specifying this will - delete all events associated with a visitor. - - ``userId``: Double quoted string. Specifying this will - delete all events associated with a user. - - Examples: - - - Deleting all events in a time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - - Deleting specific eventType in time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` - - Deleting all events for a specific visitor: - ``visitorId = "visitor1024"`` - - The filtering fields are assumed to have an implicit AND. - force (bool): - Actually perform the purge. If ``force`` is set to false, - the method will return the expected purge count without - deleting any user events. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeUserEventsResponse(proto.Message): - r"""Response of the PurgeUserEventsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purged_events_count (int): - The total count of events purged as a result - of the operation. - """ - - purged_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py deleted file mode 100644 index 21447a27..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py +++ /dev/null @@ -1,1074 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'SearchRequest', - 'SearchResponse', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - - Attributes: - placement (str): - Required. The resource name of the search engine placement, - such as - ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` - This field is used to identify the serving configuration - name and the set of models that will be used to make the - search. - branch (str): - The branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - - Use "default_branch" as the branch ID or leave this field - empty, to search products under the default branch. - query (str): - Raw search query. - visitor_id (str): - Required. A unique identifier for tracking visitors. For - example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - This should be the same identifier as - [UserEvent.visitor_id][google.cloud.retail.v2beta.UserEvent.visitor_id]. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2beta.types.UserInfo): - User information. - page_size (int): - Maximum number of - [Product][google.cloud.retail.v2beta.Product]s to return. If - unspecified, defaults to a reasonable value. The maximum - allowed value is 120. Values above 120 will be coerced to - 120. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [SearchResponse.next_page_token][google.cloud.retail.v2beta.SearchResponse.next_page_token], - received from a previous - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - offset (int): - A 0-indexed integer that specifies the current offset (that - is, starting result location, amongst the - [Product][google.cloud.retail.v2beta.Product]s deemed by the - API as relevant) in search results. This field is only - considered if - [page_token][google.cloud.retail.v2beta.SearchRequest.page_token] - is unset. - - If this field is negative, an INVALID_ARGUMENT is returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. Filter expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - canonical_filter (str): - The default filter that is applied when a user performs a - search without checking any filters on the search page. - - The filter applied to every search request when quality - improvement such as query expansion is needed. For example, - if a query does not have enough results, an expanded query - with - [SearchRequest.canonical_filter][google.cloud.retail.v2beta.SearchRequest.canonical_filter] - will be returned as a supplement of the original query. This - field is strongly recommended to achieve high search - quality. - - See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for more details about filter syntax. - order_by (str): - The order in which products are returned. Products can be - ordered by a field in an - [Product][google.cloud.retail.v2beta.Product] object. Leave - it unset if ordered by relevance. OrderBy expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - facet_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.FacetSpec]): - Facet specifications for faceted search. If empty, no facets - are returned. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - dynamic_facet_spec (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec): - Deprecated. Refer to - https://cloud.google.com/retail/docs/configs#dynamic - to enable dynamic facets. Do not set this field. - The specification for dynamically generated - facets. Notice that only textual facets can be - dynamically generated. - boost_spec (google.cloud.retail_v2beta.types.SearchRequest.BoostSpec): - Boost specification to boost certain products. See more - details at this `user - guide `__. - - Notice that if both - [ServingConfig.boost_control_ids][google.cloud.retail.v2beta.ServingConfig.boost_control_ids] - and [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. - query_expansion_spec (google.cloud.retail_v2beta.types.SearchRequest.QueryExpansionSpec): - The query expansion specification that specifies the - conditions under which query expansion will occur. See more - details at this `user - guide `__. - variant_rollup_keys (Sequence[str]): - The keys to fetch and rollup the matching - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s attributes, - [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo] - or - [LocalInventory][google.cloud.retail.v2beta.LocalInventory]s - attributes. The attributes from all the matching - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s or - [LocalInventory][google.cloud.retail.v2beta.LocalInventory]s - are merged and de-duplicated. Notice that rollup attributes - will lead to extra query latency. Maximum number of keys is - 30. - - For - [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], - a fulfillment type and a fulfillment ID must be provided in - the format of "fulfillmentType.fulfillmentId". E.g., in - "pickupInStore.store123", "pickupInStore" is fulfillment - type and "store123" is the store ID. - - Supported keys are: - - - colorFamilies - - price - - originalPrice - - discount - - variantId - - inventory(place_id,price) - - inventory(place_id,original_price) - - inventory(place_id,attributes.key), where key is any key - in the [Product.inventories.attributes][] map. - - attributes.key, where key is any key in the - [Product.attributes][google.cloud.retail.v2beta.Product.attributes] - map. - - pickupInStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "pickup-in-store". - - shipToStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "ship-to-store". - - sameDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "same-day-delivery". - - nextDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "next-day-delivery". - - customFulfillment1.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-1". - - customFulfillment2.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-2". - - customFulfillment3.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-3". - - customFulfillment4.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-4". - - customFulfillment5.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-5". - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. Required for - category navigation queries to achieve good search quality. - The format should be the same as - [UserEvent.page_categories][google.cloud.retail.v2beta.UserEvent.page_categories]; - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - search_mode (google.cloud.retail_v2beta.types.SearchRequest.SearchMode): - The search mode of the search request. If not - specified, a single search request triggers both - product search and faceted search. - personalization_spec (google.cloud.retail_v2beta.types.SearchRequest.PersonalizationSpec): - The specification for personalization. - """ - class SearchMode(proto.Enum): - r"""The search mode of each search request.""" - SEARCH_MODE_UNSPECIFIED = 0 - PRODUCT_SEARCH_ONLY = 1 - FACETED_SEARCH_ONLY = 2 - - class FacetSpec(proto.Message): - r"""A facet specification to perform faceted search. - - Attributes: - facet_key (google.cloud.retail_v2beta.types.SearchRequest.FacetSpec.FacetKey): - Required. The facet key specification. - limit (int): - Maximum of facet values that should be returned for this - facet. If unspecified, defaults to 20. The maximum allowed - value is 300. Values above 300 will be coerced to 300. - - If this field is negative, an INVALID_ARGUMENT is returned. - excluded_filter_keys (Sequence[str]): - List of keys to exclude when faceting. - - By default, - [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] - is not excluded from the filter unless it is listed in this - field. - - For example, suppose there are 100 products with color facet - "Red" and 200 products with color facet "Blue". A query - containing the filter "colorFamilies:ANY("Red")" and have - "colorFamilies" as - [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] - will by default return the "Red" with count 100. - - If this field contains "colorFamilies", then the query - returns both the "Red" with count 100 and "Blue" with count - 200, because the "colorFamilies" key is now excluded from - the filter. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - enable_dynamic_position (bool): - Enables dynamic position for this facet. If set to true, the - position of this facet among all facets in the response is - determined by Google Retail Search. It will be ordered - together with dynamic facets if dynamic facets is enabled. - If set to false, the position of this facet in the response - will be the same as in the request, and it will be ranked - before the facets with dynamic position enable and all - dynamic facets. - - For example, you may always want to have rating facet - returned in the response, but it's not necessarily to always - display the rating facet at the top. In that case, you can - set enable_dynamic_position to true so that the position of - rating facet in response will be determined by Google Retail - Search. - - Another example, assuming you have the following facets in - the request: - - - "rating", enable_dynamic_position = true - - - "price", enable_dynamic_position = false - - - "brands", enable_dynamic_position = false - - And also you have a dynamic facets enable, which will - generate a facet 'gender'. Then the final order of the - facets in the response can be ("price", "brands", "rating", - "gender") or ("price", "brands", "gender", "rating") depends - on how Google Retail Search orders "gender" and "rating" - facets. However, notice that "price" and "brands" will - always be ranked at 1st and 2nd position since their - enable_dynamic_position are false. - """ - - class FacetKey(proto.Message): - r"""Specifies how a facet is computed. - - Attributes: - key (str): - Required. Supported textual and numerical facet keys in - [Product][google.cloud.retail.v2beta.Product] object, over - which the facet values are computed. Facet key is - case-sensitive. - - Allowed facet keys when - [FacetKey.query][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.query] - is not specified: - - - textual_field = - - - "brands" - - "categories" - - "genders" - - "ageGroups" - - "availability" - - "colorFamilies" - - "colors" - - "sizes" - - "materials" - - "patterns" - - "conditions" - - "attributes.key" - - "pickupInStore" - - "shipToStore" - - "sameDayDelivery" - - "nextDayDelivery" - - "customFulfillment1" - - "customFulfillment2" - - "customFulfillment3" - - "customFulfillment4" - - "customFulfillment5" - - "inventory(place_id,attributes.key)" - - - numerical_field = - - - "price" - - "discount" - - "rating" - - "ratingCount" - - "attributes.key" - - "inventory(place_id,price)" - - "inventory(place_id,original_price)" - - "inventory(place_id,attributes.key)". - intervals (Sequence[google.cloud.retail_v2beta.types.Interval]): - Set only if values should be bucketized into - intervals. Must be set for facets with numerical - values. Must not be set for facet with text - values. Maximum number of intervals is 30. - restricted_values (Sequence[str]): - Only get facet for the given restricted values. For example, - when using "pickupInStore" as key and set restricted values - to ["store123", "store456"], only facets for "store123" and - "store456" are returned. Only supported on textual fields - and fulfillments. Maximum is 20. - - Must be set for the fulfillment facet keys: - - - pickupInStore - - - shipToStore - - - sameDayDelivery - - - nextDayDelivery - - - customFulfillment1 - - - customFulfillment2 - - - customFulfillment3 - - - customFulfillment4 - - - customFulfillment5 - prefixes (Sequence[str]): - Only get facet values that start with the - given string prefix. For example, suppose - "categories" has three values "Women > Shoe", - "Women > Dress" and "Men > Shoe". If set - "prefixes" to "Women", the "categories" facet - will give only "Women > Shoe" and "Women > - Dress". Only supported on textual fields. - Maximum is 10. - contains (Sequence[str]): - Only get facet values that contains the given - strings. For example, suppose "categories" has - three values "Women > Shoe", "Women > Dress" and - "Men > Shoe". If set "contains" to "Shoe", the - "categories" facet will give only "Women > Shoe" - and "Men > Shoe". Only supported on textual - fields. Maximum is 10. - order_by (str): - The order in which [Facet.values][] are returned. - - Allowed values are: - - - "count desc", which means order by - [Facet.FacetValue.count][] descending. - - - "value desc", which means order by - [Facet.FacetValue.value][] descending. Only applies to - textual facets. - - If not set, textual values are sorted in `natural - order `__; - numerical intervals are sorted in the order given by - [FacetSpec.FacetKey.intervals][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.intervals]; - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - are sorted in the order given by - [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.restricted_values]. - query (str): - The query that is used to compute facet for the given facet - key. When provided, it will override the default behavior of - facet computation. The query syntax is the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for detail syntax and limitations. Notice that there is no - limitation on - [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] - when query is specified. - - In the response, [FacetValue.value][] will be always "1" and - [FacetValue.count][] will be the number of results that - matches the query. - - For example, you can set a customized facet for - "shipToStore", where - [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] - is "customizedShipToStore", and - [FacetKey.query][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.query] - is "availability: ANY("IN_STOCK") AND shipToStore: - ANY("123")". Then the facet will count the products that are - both in stock and ship to store "123". - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - intervals = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Interval, - ) - restricted_values = proto.RepeatedField( - proto.STRING, - number=3, - ) - prefixes = proto.RepeatedField( - proto.STRING, - number=8, - ) - contains = proto.RepeatedField( - proto.STRING, - number=9, - ) - order_by = proto.Field( - proto.STRING, - number=4, - ) - query = proto.Field( - proto.STRING, - number=5, - ) - - facet_key = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.FacetSpec.FacetKey', - ) - limit = proto.Field( - proto.INT32, - number=2, - ) - excluded_filter_keys = proto.RepeatedField( - proto.STRING, - number=3, - ) - enable_dynamic_position = proto.Field( - proto.BOOL, - number=4, - ) - - class DynamicFacetSpec(proto.Message): - r"""The specifications of dynamically generated facets. - - Attributes: - mode (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec.Mode): - Mode of the DynamicFacet feature. Defaults to - [Mode.DISABLED][google.cloud.retail.v2beta.SearchRequest.DynamicFacetSpec.Mode.DISABLED] - if it's unset. - """ - class Mode(proto.Enum): - r"""Enum to control DynamicFacet mode""" - MODE_UNSPECIFIED = 0 - DISABLED = 1 - ENABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.DynamicFacetSpec.Mode', - ) - - class BoostSpec(proto.Message): - r"""Boost specification to boost certain items. - - Attributes: - condition_boost_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - Condition boost specifications. If a product - matches multiple conditions in the - specifictions, boost scores from these - specifications are all applied and combined in a - non-linear way. Maximum number of specifications - is 10. - skip_boost_spec_validation (bool): - Whether to skip boostspec validation. If this field is set - to true, invalid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] - will be ignored and valid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] - will still be applied. - - This field is a member of `oneof`_ ``_skip_boost_spec_validation``. - """ - - class ConditionBoostSpec(proto.Message): - r"""Boost applies to products which match a condition. - - Attributes: - condition (str): - An expression which specifies a boost condition. The syntax - and supported fields are the same as a filter expression. - See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": - - - (id: ANY("product_1", "product_2")) AND - (colorFamilies: ANY("Red","Blue")) - boost (float): - Strength of the condition boost, which should be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - """ - - condition = proto.Field( - proto.STRING, - number=1, - ) - boost = proto.Field( - proto.FLOAT, - number=2, - ) - - condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - skip_boost_spec_validation = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - - class QueryExpansionSpec(proto.Message): - r"""Specification to determine under which conditions query - expansion should occur. - - Attributes: - condition (google.cloud.retail_v2beta.types.SearchRequest.QueryExpansionSpec.Condition): - The condition under which query expansion should occur. - Default to - [Condition.DISABLED][google.cloud.retail.v2beta.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - pin_unexpanded_results (bool): - Whether to pin unexpanded results. If this - field is set to true, unexpanded products are - always at the top of the search results, - followed by the expanded results. - """ - class Condition(proto.Enum): - r"""Enum describing under which condition query expansion should - occur. - """ - CONDITION_UNSPECIFIED = 0 - DISABLED = 1 - AUTO = 3 - - condition = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.QueryExpansionSpec.Condition', - ) - pin_unexpanded_results = proto.Field( - proto.BOOL, - number=2, - ) - - class PersonalizationSpec(proto.Message): - r"""The specification for personalization. - - Attributes: - mode (google.cloud.retail_v2beta.types.SearchRequest.PersonalizationSpec.Mode): - Defaults to - [Mode.AUTO][google.cloud.retail.v2beta.SearchRequest.PersonalizationSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""The personalization mode of each search request.""" - MODE_UNSPECIFIED = 0 - AUTO = 1 - DISABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.PersonalizationSpec.Mode', - ) - - placement = proto.Field( - proto.STRING, - number=1, - ) - branch = proto.Field( - proto.STRING, - number=2, - ) - query = proto.Field( - proto.STRING, - number=3, - ) - visitor_id = proto.Field( - proto.STRING, - number=4, - ) - user_info = proto.Field( - proto.MESSAGE, - number=5, - message=common.UserInfo, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - offset = proto.Field( - proto.INT32, - number=9, - ) - filter = proto.Field( - proto.STRING, - number=10, - ) - canonical_filter = proto.Field( - proto.STRING, - number=28, - ) - order_by = proto.Field( - proto.STRING, - number=11, - ) - facet_specs = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=FacetSpec, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=21, - message=DynamicFacetSpec, - ) - boost_spec = proto.Field( - proto.MESSAGE, - number=13, - message=BoostSpec, - ) - query_expansion_spec = proto.Field( - proto.MESSAGE, - number=14, - message=QueryExpansionSpec, - ) - variant_rollup_keys = proto.RepeatedField( - proto.STRING, - number=17, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=23, - ) - search_mode = proto.Field( - proto.ENUM, - number=31, - enum=SearchMode, - ) - personalization_spec = proto.Field( - proto.MESSAGE, - number=32, - message=PersonalizationSpec, - ) - - -class SearchResponse(proto.Message): - r"""Response message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - - Attributes: - results (Sequence[google.cloud.retail_v2beta.types.SearchResponse.SearchResult]): - A list of matched items. The order represents - the ranking. - facets (Sequence[google.cloud.retail_v2beta.types.SearchResponse.Facet]): - Results of facets requested by user. - total_size (int): - The estimated total count of matched items irrespective of - pagination. The count of - [results][google.cloud.retail.v2beta.SearchResponse.results] - returned by pagination may be less than the - [total_size][google.cloud.retail.v2beta.SearchResponse.total_size] - that matches. - corrected_query (str): - If spell correction applies, the corrected - query. Otherwise, empty. - attribution_token (str): - A unique search token. This should be included in the - [UserEvent][google.cloud.retail.v2beta.UserEvent] logs - resulting from this search, which enables accurate - attribution of search model performance. - next_page_token (str): - A token that can be sent as - [SearchRequest.page_token][google.cloud.retail.v2beta.SearchRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - query_expansion_info (google.cloud.retail_v2beta.types.SearchResponse.QueryExpansionInfo): - Query expansion information for the returned - results. - redirect_uri (str): - The URI of a customer-defined redirect page. If redirect - action is triggered, no search will be performed, and only - [redirect_uri][google.cloud.retail.v2beta.SearchResponse.redirect_uri] - and - [attribution_token][google.cloud.retail.v2beta.SearchResponse.attribution_token] - will be set in the response. - applied_controls (Sequence[str]): - The fully qualified resource name of applied - `controls `__. - invalid_condition_boost_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - The invalid - [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] - that are not applied during serving. - """ - - class SearchResult(proto.Message): - r"""Represents the search results. - - Attributes: - id (str): - [Product.id][google.cloud.retail.v2beta.Product.id] of the - searched [Product][google.cloud.retail.v2beta.Product]. - product (google.cloud.retail_v2beta.types.Product): - The product data snippet in the search response. Only - [Product.name][google.cloud.retail.v2beta.Product.name] is - guaranteed to be populated. - - [Product.variants][google.cloud.retail.v2beta.Product.variants] - contains the product variants that match the search query. - If there are multiple product variants matching the query, - top 5 most relevant product variants are returned and - ordered by relevancy. - - If relevancy can be deternmined, use - [matching_variant_fields][google.cloud.retail.v2beta.SearchResponse.SearchResult.matching_variant_fields] - to look up matched product variants fields. If relevancy - cannot be determined, e.g. when searching "shoe" all - products in a shoe product can be a match, 5 product - variants are returned but order is meaningless. - matching_variant_count (int): - The count of matched - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s. - matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): - If a - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] matches the - search query, this map indicates which - [Product][google.cloud.retail.v2beta.Product] fields are - matched. The key is the - [Product.name][google.cloud.retail.v2beta.Product.name], the - value is a field mask of the matched - [Product][google.cloud.retail.v2beta.Product] fields. If - matched attributes cannot be determined, this map will be - empty. - - For example, a key "sku1" with field mask - "products.color_info" indicates there is a match between - "sku1" [ColorInfo][google.cloud.retail.v2beta.ColorInfo] and - the query. - variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): - The rollup matching - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] attributes. - The key is one of the - [SearchRequest.variant_rollup_keys][google.cloud.retail.v2beta.SearchRequest.variant_rollup_keys]. - The values are the merged and de-duplicated - [Product][google.cloud.retail.v2beta.Product] attributes. - Notice that the rollup values are respect filter. For - example, when filtering by "colorFamilies:ANY("red")" and - rollup "colorFamilies", only "red" is returned. - - For textual and numerical attributes, the rollup values is a - list of string or double values with type - [google.protobuf.ListValue][google.protobuf.ListValue]. For - example, if there are two variants with colors "red" and - "blue", the rollup values are - - :: - - { key: "colorFamilies" - value { - list_value { - values { string_value: "red" } - values { string_value: "blue" } - } - } - } - - For - [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], - the rollup values is a double value with type - [google.protobuf.Value][google.protobuf.Value]. For example, - ``{key: "pickupInStore.store1" value { number_value: 10 }}`` - means a there are 10 variants in this product are available - in the store "store1". - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - matching_variant_count = proto.Field( - proto.INT32, - number=3, - ) - matching_variant_fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - variant_rollup_values = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - - class Facet(proto.Message): - r"""A facet result. - - Attributes: - key (str): - The key for this facet. E.g., "colorFamilies" - or "price" or "attributes.attr1". - values (Sequence[google.cloud.retail_v2beta.types.SearchResponse.Facet.FacetValue]): - The facet values for this field. - dynamic_facet (bool): - Whether the facet is dynamically generated. - """ - - class FacetValue(proto.Message): - r"""A facet value which contains value names and their count. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Text value of a facet, such as "Black" for - facet "colorFamilies". - - This field is a member of `oneof`_ ``facet_value``. - interval (google.cloud.retail_v2beta.types.Interval): - Interval value for a facet, such as [10, 20) for facet - "price". - - This field is a member of `oneof`_ ``facet_value``. - count (int): - Number of items that have this facet value. - """ - - value = proto.Field( - proto.STRING, - number=1, - oneof='facet_value', - ) - interval = proto.Field( - proto.MESSAGE, - number=2, - oneof='facet_value', - message=common.Interval, - ) - count = proto.Field( - proto.INT64, - number=3, - ) - - key = proto.Field( - proto.STRING, - number=1, - ) - values = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SearchResponse.Facet.FacetValue', - ) - dynamic_facet = proto.Field( - proto.BOOL, - number=3, - ) - - class QueryExpansionInfo(proto.Message): - r"""Information describing query expansion including whether - expansion has occurred. - - Attributes: - expanded_query (bool): - Bool describing whether query expansion has - occurred. - pinned_result_count (int): - Number of pinned results. This field will only be set when - expansion happens and - [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2beta.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] - is set to true. - """ - - expanded_query = proto.Field( - proto.BOOL, - number=1, - ) - pinned_result_count = proto.Field( - proto.INT64, - number=2, - ) - - @property - def raw_page(self): - return self - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=SearchResult, - ) - facets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Facet, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - corrected_query = proto.Field( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - next_page_token = proto.Field( - proto.STRING, - number=6, - ) - query_expansion_info = proto.Field( - proto.MESSAGE, - number=7, - message=QueryExpansionInfo, - ) - redirect_uri = proto.Field( - proto.STRING, - number=10, - ) - applied_controls = proto.RepeatedField( - proto.STRING, - number=12, - ) - invalid_condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py deleted file mode 100644 index f8b78591..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py +++ /dev/null @@ -1,309 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'ServingConfig', - }, -) - - -class ServingConfig(proto.Message): - r"""Configures metadata that is used to generate serving time results - (e.g. search results or recommendation predictions). The - ServingConfig is passed in the search and predict request and - together with the Catalog.default_branch, generates results. - - Attributes: - name (str): - Immutable. Fully qualified name - projects/\ */locations/global/catalogs/*/servingConfig/\* - display_name (str): - Required. The human readable serving config display name. - Used in Retail UI. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - model_id (str): - The id of the model to use at serving time. Currently only - RecommendationModels are supported: - https://cloud.google.com/retail/recommendations-ai/docs/create-models - Can be changed but only to a compatible model (e.g. - others-you-may-like CTR to others-you-may-like CVR). - - Required when - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - price_reranking_level (str): - How much price ranking we want in serving results. Price - reranking causes product items with a similar recommendation - probability to be ordered by price, with the highest-priced - items first. This setting could result in a decrease in - click-through and conversion rates. Allowed values are: - - - 'no-price-reranking' - - 'low-price-raranking' - - 'medium-price-reranking' - - 'high-price-reranking' - - If not specified, we choose default based on model type. - Default value: 'no-price-reranking'. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - facet_control_ids (Sequence[str]): - Facet specifications for faceted search. If empty, no facets - are returned. The ids refer to the ids of - [Control][google.cloud.retail.v2beta.Control] resources with - only the Facet control set. These controls are assumed to be - in the same [Catalog][google.cloud.retail.v2beta.Catalog] as - the - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]. A - maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - dynamic_facet_spec (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec): - The specification for dynamically generated facets. Notice - that only textual facets can be dynamically generated. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - boost_control_ids (Sequence[str]): - Condition boost specifications. If a product matches - multiple conditions in the specifications, boost scores from - these specifications are all applied and combined in a - non-linear way. Maximum number of specifications is 100. - - Notice that if both - [ServingConfig.boost_control_ids][google.cloud.retail.v2beta.ServingConfig.boost_control_ids] - and [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - filter_control_ids (Sequence[str]): - Condition filter specifications. If a product matches - multiple conditions in the specifications, filters from - these specifications are all applied and combined via the - AND operator. Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - redirect_control_ids (Sequence[str]): - Condition redirect specifications. Only the first triggered - redirect action is applied, even if multiple apply. Maximum - number of specifications is 1000. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - twoway_synonyms_control_ids (Sequence[str]): - Condition synonyms specifications. If multiple syonyms - conditions match, all matching synonyms control in the list - will execute. Order of controls in the list will not matter. - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - oneway_synonyms_control_ids (Sequence[str]): - Condition oneway synonyms specifications. If multiple oneway - synonyms conditions match, all matching oneway synonyms - controls in the list will execute. Order of controls in the - list will not matter. Maximum number of specifications is - 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - do_not_associate_control_ids (Sequence[str]): - Condition do not associate specifications. If multiple do - not associate conditions match, all matching do not - associate controls in the list will execute. - - - Order does not matter. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - replacement_control_ids (Sequence[str]): - Condition replacement specifications. - - - Applied according to the order in the list. - - A previously replaced term can not be re-replaced. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - ignore_control_ids (Sequence[str]): - Condition ignore specifications. If multiple ignore - conditions match, all matching ignore controls in the list - will execute. - - - Order does not matter. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - diversity_level (str): - How much diversity to use in recommendation model results - e.g. 'medium-diversity' or 'high-diversity'. Currently - supported values: - - - 'no-diversity' - - 'low-diversity' - - 'medium-diversity' - - 'high-diversity' - - 'auto-diversity' - - If not specified, we choose default based on recommendation - model type. Default value: 'no-diversity'. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - enable_category_filter_level (str): - Whether to add additional category filters on the - 'similar-items' model. If not specified, we enable it by - default. Allowed values are: - - - 'no-category-match': No additional filtering of original - results from the model and the customer's filters. - - 'relaxed-category-match': Only keep results with - categories that match at least one item categories in the - PredictRequests's context item. - - - If customer also sends filters in the PredictRequest, - then the results will satisfy both conditions (user - given and category match). - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - solution_types (Sequence[google.cloud.retail_v2beta.types.SolutionType]): - Required. Immutable. Specifies the solution - types that a serving config can be associated - with. Currently we support setting only one type - of solution. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - model_id = proto.Field( - proto.STRING, - number=3, - ) - price_reranking_level = proto.Field( - proto.STRING, - number=4, - ) - facet_control_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=6, - message=search_service.SearchRequest.DynamicFacetSpec, - ) - boost_control_ids = proto.RepeatedField( - proto.STRING, - number=7, - ) - filter_control_ids = proto.RepeatedField( - proto.STRING, - number=9, - ) - redirect_control_ids = proto.RepeatedField( - proto.STRING, - number=10, - ) - twoway_synonyms_control_ids = proto.RepeatedField( - proto.STRING, - number=18, - ) - oneway_synonyms_control_ids = proto.RepeatedField( - proto.STRING, - number=12, - ) - do_not_associate_control_ids = proto.RepeatedField( - proto.STRING, - number=13, - ) - replacement_control_ids = proto.RepeatedField( - proto.STRING, - number=14, - ) - ignore_control_ids = proto.RepeatedField( - proto.STRING, - number=15, - ) - diversity_level = proto.Field( - proto.STRING, - number=8, - ) - enable_category_filter_level = proto.Field( - proto.STRING, - number=16, - ) - solution_types = proto.RepeatedField( - proto.ENUM, - number=19, - enum=common.SolutionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py deleted file mode 100644 index 20edced0..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py +++ /dev/null @@ -1,234 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'CreateServingConfigRequest', - 'UpdateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'AddControlRequest', - 'RemoveControlRequest', - }, -) - - -class CreateServingConfigRequest(proto.Message): - r"""Request for CreateServingConfig method. - - Attributes: - parent (str): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - serving_config (google.cloud.retail_v2beta.types.ServingConfig): - Required. The ServingConfig to create. - serving_config_id (str): - Required. The ID to use for the ServingConfig, which will - become the final component of the ServingConfig's resource - name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-_/. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - serving_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_serving_config.ServingConfig, - ) - serving_config_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateServingConfigRequest(proto.Message): - r"""Request for UpdateServingConfig method. - - Attributes: - serving_config (google.cloud.retail_v2beta.types.ServingConfig): - Required. The ServingConfig to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [ServingConfig][google.cloud.retail.v2beta.ServingConfig] to - update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] - - If not set, all supported fields are updated. - """ - - serving_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_serving_config.ServingConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteServingConfigRequest(proto.Message): - r"""Request for DeleteServingConfig method. - - Attributes: - name (str): - Required. The resource name of the ServingConfig to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetServingConfigRequest(proto.Message): - r"""Request for GetServingConfig method. - - Attributes: - name (str): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListServingConfigsRequest(proto.Message): - r"""Request for ListServingConfigs method. - - Attributes: - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - page_size (int): - Optional. Maximum number of results to - return. If unspecified, defaults to 100. If a - value greater than 100 is provided, at most 100 - results are returned. - page_token (str): - Optional. A page token, received from a previous - ``ListServingConfigs`` call. Provide this to retrieve the - subsequent page. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListServingConfigsResponse(proto.Message): - r"""Response for ListServingConfigs method. - - Attributes: - serving_configs (Sequence[google.cloud.retail_v2beta.types.ServingConfig]): - All the ServingConfigs for a given catalog. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - serving_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_serving_config.ServingConfig, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class AddControlRequest(proto.Message): - r"""Request for AddControl method. - - Attributes: - serving_config (str): - Required. The source ServingConfig resource name . Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - control_id (str): - Required. The id of the control to apply. Assumed to be in - the same catalog as the serving config - if id is not found - a NOT_FOUND error is returned. - """ - - serving_config = proto.Field( - proto.STRING, - number=1, - ) - control_id = proto.Field( - proto.STRING, - number=2, - ) - - -class RemoveControlRequest(proto.Message): - r"""Request for RemoveControl method. - - Attributes: - serving_config (str): - Required. The source ServingConfig resource name . Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - control_id (str): - Required. The id of the control to apply. - Assumed to be in the same catalog as the serving - config. - """ - - serving_config = proto.Field( - proto.STRING, - number=1, - ) - control_id = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py deleted file mode 100644 index bf1b1aee..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py +++ /dev/null @@ -1,507 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import product as gcr_product -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'UserEvent', - 'ProductDetail', - 'CompletionDetail', - 'PurchaseTransaction', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information Retail API needs - to know about how end users interact with customers' website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - - ``add-to-cart``: Products being added to cart. - - ``category-page-view``: Special pages such as sale or - promotion pages viewed. - - ``detail-page-view``: Products detail page viewed. - - ``home-page-view``: Homepage viewed. - - ``promotion-offered``: Promotion is offered to a user. - - ``promotion-not-offered``: Promotion is not offered to a - user. - - ``purchase-complete``: User finishing a purchase. - - ``search``: Product search. - - ``shopping-cart-page-view``: User viewing a shopping - cart. - visitor_id (str): - Required. A unique identifier for tracking visitors. - - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor log in/out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - The field should not contain PII or user-data. We recommend - to use Google Analystics `Client - ID `__ - for this field. - session_id (str): - A unique identifier for tracking a visitor session with a - length limit of 128 bytes. A session is an aggregation of an - end user behavior in a time span. - - A general guideline to populate the sesion_id: - - 1. If user has no activity for 30 min, a new session_id - should be assigned. - 2. The session_id should be unique across users, suggest use - uuid or add visitor_id as prefix. - event_time (google.protobuf.timestamp_pb2.Timestamp): - Only required for - [UserEventService.ImportUserEvents][google.cloud.retail.v2beta.UserEventService.ImportUserEvents] - method. Timestamp of when the user event happened. - experiment_ids (Sequence[str]): - A list of identifiers for the independent - experiment groups this user event belongs to. - This is used to distinguish between user events - associated with different experiment setups - (e.g. using Retail API, using different - recommendation models). - attribution_token (str): - Highly recommended for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2beta.PredictionService.Predict]. - This field enables accurate attribution of recommendation - model performance. - - The value must be a valid - [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] - for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2beta.PredictionService.Predict]. - The value must be a valid - [SearchResponse.attribution_token][google.cloud.retail.v2beta.SearchResponse.attribution_token] - for user events that are the result of - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - This token enables us to accurately attribute page view or - purchase back to the event and the particular predict - response containing this clicked/purchased product. If user - clicks on product K in the recommendation results, pass - [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] - as a URL parameter to product K's page. When recording - events on product K's page, log the - [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] - to this field. - product_details (Sequence[google.cloud.retail_v2beta.types.ProductDetail]): - The main product details related to the event. - - This field is required for the following event types: - - - ``add-to-cart`` - - ``detail-page-view`` - - ``purchase-complete`` - - ``search`` - - In a ``search`` event, this field represents the products - returned to the end user on the current page (the end user - may have not finished browsing the whole page yet). When a - new page is returned to the end user, after - pagination/filtering/ordering even for the same query, a new - ``search`` event with different - [product_details][google.cloud.retail.v2beta.UserEvent.product_details] - is desired. The end user may have not finished browsing the - whole page yet. - completion_detail (google.cloud.retail_v2beta.types.CompletionDetail): - The main auto-completion details related to the event. - - This field should be set for ``search`` event when - autocomplete function is enabled and the user clicks a - suggestion for search. - attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): - Extra user event features to include in the recommendation - model. - - If you provide custom attributes for ingested user events, - also include them in the user events that you associate with - prediction requests. Custom attribute formatting must be - consistent between imported events and events provided with - prediction requests. This lets the Retail API use those - custom attributes when training models and serving - predictions, which helps improve recommendation quality. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - The key must be a UTF-8 encoded string with a length - limit of 5,000 characters. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a UTF-8 - encoded string with a length limit of 256 characters. - - For number attributes, at most 400 values are allowed. - - For product recommendations, an example of extra user - information is traffic_channel, which is how a user arrives - at the site. Users can arrive at the site by coming to the - site directly, coming through Google search, or in other - ways. - cart_id (str): - The ID or name of the associated shopping cart. This ID is - used to associate multiple items added or present in the - cart before purchase. - - This can only be set for ``add-to-cart``, - ``purchase-complete``, or ``shopping-cart-page-view`` - events. - purchase_transaction (google.cloud.retail_v2beta.types.PurchaseTransaction): - A transaction represents the entire purchase transaction. - - Required for ``purchase-complete`` events. Other event types - should not set this field. Otherwise, an INVALID_ARGUMENT - error is returned. - search_query (str): - The user's search query. - - See - [SearchRequest.query][google.cloud.retail.v2beta.SearchRequest.query] - for definition. - - The value must be a UTF-8 encoded string with a length limit - of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - At least one of - [search_query][google.cloud.retail.v2beta.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2beta.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. - - See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - order_by (str): - The order in which products are returned. - - See - [SearchRequest.order_by][google.cloud.retail.v2beta.SearchRequest.order_by] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - offset (int): - An integer that specifies the current offset for pagination - (the 0-indexed starting location, amongst the products - deemed by the API as relevant). - - See - [SearchRequest.offset][google.cloud.retail.v2beta.SearchRequest.offset] - for definition. - - If this field is negative, an INVALID_ARGUMENT is returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - - Required for ``category-page-view`` events. At least one of - [search_query][google.cloud.retail.v2beta.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2beta.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2beta.types.UserInfo): - User information. - uri (str): - Complete URL (window.location.href) of the - user's current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. Maximum length - 5,000 characters. - referrer_uri (str): - The referrer URL of the current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. - page_view_id (str): - A unique ID of a web page view. - - This should be kept the same for all user events triggered - from the same pageview. For example, an item detail page - view could trigger multiple events as the user is browsing - the page. The ``pageViewId`` property should be kept the - same for all these events so that they can be grouped - together properly. - - When using the client side event reporting with JavaScript - pixel and Google Tag Manager, this value is filled in - automatically. - """ - - event_type = proto.Field( - proto.STRING, - number=1, - ) - visitor_id = proto.Field( - proto.STRING, - number=2, - ) - session_id = proto.Field( - proto.STRING, - number=21, - ) - event_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - experiment_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - product_details = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='ProductDetail', - ) - completion_detail = proto.Field( - proto.MESSAGE, - number=22, - message='CompletionDetail', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=common.CustomAttribute, - ) - cart_id = proto.Field( - proto.STRING, - number=8, - ) - purchase_transaction = proto.Field( - proto.MESSAGE, - number=9, - message='PurchaseTransaction', - ) - search_query = proto.Field( - proto.STRING, - number=10, - ) - filter = proto.Field( - proto.STRING, - number=16, - ) - order_by = proto.Field( - proto.STRING, - number=17, - ) - offset = proto.Field( - proto.INT32, - number=18, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=11, - ) - user_info = proto.Field( - proto.MESSAGE, - number=12, - message=common.UserInfo, - ) - uri = proto.Field( - proto.STRING, - number=13, - ) - referrer_uri = proto.Field( - proto.STRING, - number=14, - ) - page_view_id = proto.Field( - proto.STRING, - number=15, - ) - - -class ProductDetail(proto.Message): - r"""Detailed product information associated with a user event. - - Attributes: - product (google.cloud.retail_v2beta.types.Product): - Required. [Product][google.cloud.retail.v2beta.Product] - information. - - Required field(s): - - - [Product.id][google.cloud.retail.v2beta.Product.id] - - Optional override field(s): - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - If any supported optional fields are provided, we will treat - them as a full override when looking up product information - from the catalog. Thus, it is important to ensure that the - overriding fields are accurate and complete. - - All other product fields are ignored and instead populated - via catalog lookup after event ingestion. - quantity (google.protobuf.wrappers_pb2.Int32Value): - Quantity of the product associated with the user event. - - For example, this field will be 2 if two products are added - to the shopping cart for ``purchase-complete`` event. - Required for ``add-to-cart`` and ``purchase-complete`` event - types. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - quantity = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -class CompletionDetail(proto.Message): - r"""Detailed completion information including completion - attribution token and clicked completion info. - - Attributes: - completion_attribution_token (str): - Completion attribution token in - [CompleteQueryResponse.attribution_token][google.cloud.retail.v2beta.CompleteQueryResponse.attribution_token]. - selected_suggestion (str): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2beta.CompleteQueryResponse.CompletionResult.suggestion]. - selected_position (int): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2beta.CompleteQueryResponse.CompletionResult.suggestion] - position, starting from 0. - """ - - completion_attribution_token = proto.Field( - proto.STRING, - number=1, - ) - selected_suggestion = proto.Field( - proto.STRING, - number=2, - ) - selected_position = proto.Field( - proto.INT32, - number=3, - ) - - -class PurchaseTransaction(proto.Message): - r"""A transaction represents the entire purchase transaction. - - Attributes: - id (str): - The transaction ID with a length limit of 128 - characters. - revenue (float): - Required. Total non-zero revenue or grand - total associated with the transaction. This - value include shipping, tax, or other - adjustments to total revenue that you want to - include as part of your revenue calculations. - tax (float): - All the taxes associated with the - transaction. - cost (float): - All the costs associated with the products. These can be - manufacturing costs, shipping expenses not borne by the end - user, or any other costs, such that: - - - Profit = - [revenue][google.cloud.retail.v2beta.PurchaseTransaction.revenue] - - - [tax][google.cloud.retail.v2beta.PurchaseTransaction.tax] - - - [cost][google.cloud.retail.v2beta.PurchaseTransaction.cost] - currency_code (str): - Required. Currency code. Use three-character - ISO-4217 code. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - revenue = proto.Field( - proto.FLOAT, - number=2, - ) - tax = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - currency_code = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py deleted file mode 100644 index 990180c4..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import user_event as gcr_user_event - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'WriteUserEventRequest', - 'CollectUserEventRequest', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'RejoinUserEventsMetadata', - }, -) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (google.cloud.retail_v2beta.types.UserEvent): - Required. User event to write. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (str): - Required. URL encoded UserEvent proto with a - length limit of 2,000,000 characters. - uri (str): - The URL including cgi-parameters but - excluding the hash fragment with a length limit - of 5,000 characters. This is often more useful - than the referer URL, because many browsers only - send the domain for 3rd party requests. - ets (int): - The event timestamp in milliseconds. This - prevents browser caching of otherwise identical - get requests. The name is abbreviated to reduce - the payload bytes. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.STRING, - number=2, - ) - uri = proto.Field( - proto.STRING, - number=3, - ) - ets = proto.Field( - proto.INT64, - number=4, - ) - - -class RejoinUserEventsRequest(proto.Message): - r"""Request message for RejoinUserEvents method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event_rejoin_scope (google.cloud.retail_v2beta.types.RejoinUserEventsRequest.UserEventRejoinScope): - The type of the user event rejoin to define the scope and - range of the user events to be rejoined with the latest - product catalog. Defaults to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not - set, or set to an invalid integer value. - """ - class UserEventRejoinScope(proto.Enum): - r"""The scope of user events to be rejoined with the latest product - catalog. If the rejoining aims at reducing number of unjoined - events, set UserEventRejoinScope to UNJOINED_EVENTS. If the - rejoining aims at correcting product catalog information in joined - events, set UserEventRejoinScope to JOINED_EVENTS. If all events - needs to be rejoined, set UserEventRejoinScope to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. - """ - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 - JOINED_EVENTS = 1 - UNJOINED_EVENTS = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event_rejoin_scope = proto.Field( - proto.ENUM, - number=2, - enum=UserEventRejoinScope, - ) - - -class RejoinUserEventsResponse(proto.Message): - r"""Response message for RejoinUserEvents method. - - Attributes: - rejoined_user_events_count (int): - Number of user events that were joined with - latest product catalog. - """ - - rejoined_user_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -class RejoinUserEventsMetadata(proto.Message): - r"""Metadata for RejoinUserEvents method. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/mypy.ini b/owl-bot-staging/v2beta/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v2beta/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2beta/noxfile.py b/owl-bot-staging/v2beta/noxfile.py deleted file mode 100644 index 5abd48a4..00000000 --- a/owl-bot-staging/v2beta/noxfile.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.6", - "3.7", - "3.8", - "3.9", - "3.10", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==19.10b0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.9" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/retail_v2beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py deleted file mode 100644 index 09847366..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_AddCatalogAttribute_async] -from google.cloud import retail_v2beta - - -async def sample_add_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_AddCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py deleted file mode 100644 index 4f05ae26..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync] -from google.cloud import retail_v2beta - - -def sample_add_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py deleted file mode 100644 index 637bfe3a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetAttributesConfig_async] -from google.cloud import retail_v2beta - - -async def sample_get_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetAttributesConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py deleted file mode 100644 index c347bee2..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetAttributesConfig_sync] -from google.cloud import retail_v2beta - - -def sample_get_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetAttributesConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py deleted file mode 100644 index 2133e940..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetCompletionConfig_async] -from google.cloud import retail_v2beta - - -async def sample_get_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetCompletionConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py deleted file mode 100644 index bb9bf00d..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetCompletionConfig_sync] -from google.cloud import retail_v2beta - - -def sample_get_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetCompletionConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py deleted file mode 100644 index e598ec09..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetDefaultBranch_async] -from google.cloud import retail_v2beta - - -async def sample_get_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py deleted file mode 100644 index 6adcb072..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetDefaultBranch_sync] -from google.cloud import retail_v2beta - - -def sample_get_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py deleted file mode 100644 index b4e3df0e..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_ListCatalogs_async] -from google.cloud import retail_v2beta - - -async def sample_list_catalogs(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py deleted file mode 100644 index d938f3ae..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_ListCatalogs_sync] -from google.cloud import retail_v2beta - - -def sample_list_catalogs(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py deleted file mode 100644 index 032fb3c6..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async] -from google.cloud import retail_v2beta - - -async def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = await client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py deleted file mode 100644 index f1ecc22b..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync] -from google.cloud import retail_v2beta - - -def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py deleted file mode 100644 index 8a87262f..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReplaceCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async] -from google.cloud import retail_v2beta - - -async def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py deleted file mode 100644 index 24b38d05..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReplaceCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync] -from google.cloud import retail_v2beta - - -def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py deleted file mode 100644 index 6eec0779..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_SetDefaultBranch_async] -from google.cloud import retail_v2beta - - -async def sample_set_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - -# [END retail_v2beta_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py deleted file mode 100644 index a3deb8fd..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_SetDefaultBranch_sync] -from google.cloud import retail_v2beta - - -def sample_set_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - -# [END retail_v2beta_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py deleted file mode 100644 index b4a235ec..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async] -from google.cloud import retail_v2beta - - -async def sample_update_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - attributes_config = retail_v2beta.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2beta.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = await client.update_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py deleted file mode 100644 index 8f82ee5d..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync] -from google.cloud import retail_v2beta - - -def sample_update_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - attributes_config = retail_v2beta.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2beta.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = client.update_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py deleted file mode 100644 index 772504ff..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateCatalog_async] -from google.cloud import retail_v2beta - - -async def sample_update_catalog(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2beta.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2beta.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py deleted file mode 100644 index ed59d356..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateCatalog_sync] -from google.cloud import retail_v2beta - - -def sample_update_catalog(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2beta.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2beta.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py deleted file mode 100644 index 377166a7..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async] -from google.cloud import retail_v2beta - - -async def sample_update_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - completion_config = retail_v2beta.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2beta.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = await client.update_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py deleted file mode 100644 index f641f121..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync] -from google.cloud import retail_v2beta - - -def sample_update_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - completion_config = retail_v2beta.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2beta.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = client.update_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py deleted file mode 100644 index 96fdc6a6..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CompletionService_CompleteQuery_async] -from google.cloud import retail_v2beta - - -async def sample_complete_query(): - # Create a client - client = retail_v2beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py deleted file mode 100644 index afb0ba7d..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CompletionService_CompleteQuery_sync] -from google.cloud import retail_v2beta - - -def sample_complete_query(): - # Create a client - client = retail_v2beta.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py deleted file mode 100644 index 912753e9..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CompletionService_ImportCompletionData_async] -from google.cloud import retail_v2beta - - -async def sample_import_completion_data(): - # Create a client - client = retail_v2beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2beta.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py deleted file mode 100644 index 2cbd277d..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CompletionService_ImportCompletionData_sync] -from google.cloud import retail_v2beta - - -def sample_import_completion_data(): - # Create a client - client = retail_v2beta.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2beta.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py deleted file mode 100644 index 51e0cb4f..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_CreateControl_async] -from google.cloud import retail_v2beta - - -async def sample_create_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = await client.create_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_CreateControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py deleted file mode 100644 index 8d16b152..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_CreateControl_sync] -from google.cloud import retail_v2beta - - -def sample_create_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = client.create_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_CreateControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py deleted file mode 100644 index cb18f6ba..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_DeleteControl_async] -from google.cloud import retail_v2beta - - -async def sample_delete_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteControlRequest( - name="name_value", - ) - - # Make the request - await client.delete_control(request=request) - - -# [END retail_v2beta_generated_ControlService_DeleteControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py deleted file mode 100644 index 8a0d4f56..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_DeleteControl_sync] -from google.cloud import retail_v2beta - - -def sample_delete_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteControlRequest( - name="name_value", - ) - - # Make the request - client.delete_control(request=request) - - -# [END retail_v2beta_generated_ControlService_DeleteControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py deleted file mode 100644 index f9eeb9fd..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_GetControl_async] -from google.cloud import retail_v2beta - - -async def sample_get_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetControlRequest( - name="name_value", - ) - - # Make the request - response = await client.get_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_GetControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py deleted file mode 100644 index ee0de08a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_GetControl_sync] -from google.cloud import retail_v2beta - - -def sample_get_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetControlRequest( - name="name_value", - ) - - # Make the request - response = client.get_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_GetControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py deleted file mode 100644 index 9a645706..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListControls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_ListControls_async] -from google.cloud import retail_v2beta - - -async def sample_list_controls(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_ControlService_ListControls_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py deleted file mode 100644 index 97c8ba62..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListControls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_ListControls_sync] -from google.cloud import retail_v2beta - - -def sample_list_controls(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_ControlService_ListControls_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py deleted file mode 100644 index 9a42018c..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_UpdateControl_async] -from google.cloud import retail_v2beta - - -async def sample_update_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateControlRequest( - control=control, - ) - - # Make the request - response = await client.update_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_UpdateControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py deleted file mode 100644 index 2a306202..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_UpdateControl_sync] -from google.cloud import retail_v2beta - - -def sample_update_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateControlRequest( - control=control, - ) - - # Make the request - response = client.update_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_UpdateControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py deleted file mode 100644 index fd37548f..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_PredictionService_Predict_async] -from google.cloud import retail_v2beta - - -async def sample_predict(): - # Create a client - client = retail_v2beta.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py deleted file mode 100644 index 6975056e..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_PredictionService_Predict_sync] -from google.cloud import retail_v2beta - - -def sample_predict(): - # Create a client - client = retail_v2beta.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py deleted file mode 100644 index 92a7a7e1..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async] -from google.cloud import retail_v2beta - - -async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py deleted file mode 100644 index d828edde..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync] -from google.cloud import retail_v2beta - - -def sample_add_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py deleted file mode 100644 index ebcf5c80..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_AddLocalInventories_async] -from google.cloud import retail_v2beta - - -async def sample_add_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py deleted file mode 100644 index 9d3d9ab0..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_AddLocalInventories_sync] -from google.cloud import retail_v2beta - - -def sample_add_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py deleted file mode 100644 index 2bba20c0..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_CreateProduct_async] -from google.cloud import retail_v2beta - - -async def sample_create_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py deleted file mode 100644 index 32bd03e2..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_CreateProduct_sync] -from google.cloud import retail_v2beta - - -def sample_create_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py deleted file mode 100644 index 8f9591fa..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_DeleteProduct_async] -from google.cloud import retail_v2beta - - -async def sample_delete_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - -# [END retail_v2beta_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py deleted file mode 100644 index 56630734..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_DeleteProduct_sync] -from google.cloud import retail_v2beta - - -def sample_delete_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - -# [END retail_v2beta_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py deleted file mode 100644 index f8dcfc01..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_GetProduct_async] -from google.cloud import retail_v2beta - - -async def sample_get_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py deleted file mode 100644 index ab5cd918..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_GetProduct_sync] -from google.cloud import retail_v2beta - - -def sample_get_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py deleted file mode 100644 index aa4256cc..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_ImportProducts_async] -from google.cloud import retail_v2beta - - -async def sample_import_products(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2beta.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py deleted file mode 100644 index b4bc8314..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_ImportProducts_sync] -from google.cloud import retail_v2beta - - -def sample_import_products(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2beta.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py deleted file mode 100644 index e259ecd6..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_ListProducts_async] -from google.cloud import retail_v2beta - - -async def sample_list_products(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py deleted file mode 100644 index 5cb40315..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_ListProducts_sync] -from google.cloud import retail_v2beta - - -def sample_list_products(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py deleted file mode 100644 index 1b18eb50..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async] -from google.cloud import retail_v2beta - - -async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py deleted file mode 100644 index f430e360..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync] -from google.cloud import retail_v2beta - - -def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py deleted file mode 100644 index 55fba819..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_RemoveLocalInventories_async] -from google.cloud import retail_v2beta - - -async def sample_remove_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py deleted file mode 100644 index 31d1e58e..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_RemoveLocalInventories_sync] -from google.cloud import retail_v2beta - - -def sample_remove_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py deleted file mode 100644 index 9b467025..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_SetInventory_async] -from google.cloud import retail_v2beta - - -async def sample_set_inventory(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2beta.Product() - inventory.title = "title_value" - - request = retail_v2beta.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py deleted file mode 100644 index d1061827..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_SetInventory_sync] -from google.cloud import retail_v2beta - - -def sample_set_inventory(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2beta.Product() - inventory.title = "title_value" - - request = retail_v2beta.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py deleted file mode 100644 index 8d9590cd..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_UpdateProduct_async] -from google.cloud import retail_v2beta - - -async def sample_update_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py deleted file mode 100644 index fc614e58..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_UpdateProduct_sync] -from google.cloud import retail_v2beta - - -def sample_update_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py deleted file mode 100644 index 967c9102..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_SearchService_Search_async] -from google.cloud import retail_v2beta - - -async def sample_search(): - # Create a client - client = retail_v2beta.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py deleted file mode 100644 index 1e6a5045..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_SearchService_Search_sync] -from google.cloud import retail_v2beta - - -def sample_search(): - # Create a client - client = retail_v2beta.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py deleted file mode 100644 index d6554386..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_AddControl_async] -from google.cloud import retail_v2beta - - -async def sample_add_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.add_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_AddControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py deleted file mode 100644 index e61e4e2a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_AddControl_sync] -from google.cloud import retail_v2beta - - -def sample_add_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.add_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_AddControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py deleted file mode 100644 index b09fadf2..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_CreateServingConfig_async] -from google.cloud import retail_v2beta - - -async def sample_create_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = await client.create_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_CreateServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py deleted file mode 100644 index 5d4c0993..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync] -from google.cloud import retail_v2beta - - -def sample_create_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = client.create_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py deleted file mode 100644 index c0b03659..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async] -from google.cloud import retail_v2beta - - -async def sample_delete_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_serving_config(request=request) - - -# [END retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py deleted file mode 100644 index 1db19c0a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync] -from google.cloud import retail_v2beta - - -def sample_delete_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_serving_config(request=request) - - -# [END retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py deleted file mode 100644 index 64f6aeef..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_GetServingConfig_async] -from google.cloud import retail_v2beta - - -async def sample_get_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_GetServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py deleted file mode 100644 index 1cfab934..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_GetServingConfig_sync] -from google.cloud import retail_v2beta - - -def sample_get_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_GetServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py deleted file mode 100644 index 7ad0a3aa..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServingConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_ListServingConfigs_async] -from google.cloud import retail_v2beta - - -async def sample_list_serving_configs(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_ServingConfigService_ListServingConfigs_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py deleted file mode 100644 index 6a3e7e2a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServingConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync] -from google.cloud import retail_v2beta - - -def sample_list_serving_configs(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py deleted file mode 100644 index c9994a00..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_RemoveControl_async] -from google.cloud import retail_v2beta - - -async def sample_remove_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.remove_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_RemoveControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py deleted file mode 100644 index db6dfa93..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_RemoveControl_sync] -from google.cloud import retail_v2beta - - -def sample_remove_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.remove_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_RemoveControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py deleted file mode 100644 index 2a6bd3a0..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async] -from google.cloud import retail_v2beta - - -async def sample_update_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = await client.update_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py deleted file mode 100644 index f6441e46..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync] -from google.cloud import retail_v2beta - - -def sample_update_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = client.update_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py deleted file mode 100644 index ce80fabf..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_CollectUserEvent_async] -from google.cloud import retail_v2beta - - -async def sample_collect_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py deleted file mode 100644 index ff7df192..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_CollectUserEvent_sync] -from google.cloud import retail_v2beta - - -def sample_collect_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py deleted file mode 100644 index 259c3424..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_ImportUserEvents_async] -from google.cloud import retail_v2beta - - -async def sample_import_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2beta.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py deleted file mode 100644 index 89e0ec02..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_ImportUserEvents_sync] -from google.cloud import retail_v2beta - - -def sample_import_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2beta.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py deleted file mode 100644 index 6f97cab1..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_PurgeUserEvents_async] -from google.cloud import retail_v2beta - - -async def sample_purge_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py deleted file mode 100644 index 212d2693..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_PurgeUserEvents_sync] -from google.cloud import retail_v2beta - - -def sample_purge_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py deleted file mode 100644 index 8a95e668..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_RejoinUserEvents_async] -from google.cloud import retail_v2beta - - -async def sample_rejoin_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py deleted file mode 100644 index ebd635b8..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_RejoinUserEvents_sync] -from google.cloud import retail_v2beta - - -def sample_rejoin_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py deleted file mode 100644 index 71317cac..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_WriteUserEvent_async] -from google.cloud import retail_v2beta - - -async def sample_write_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py deleted file mode 100644 index e93e4df4..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_WriteUserEvent_sync] -from google.cloud import retail_v2beta - - -def sample_write_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json b/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json deleted file mode 100644 index 591f20ca..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json +++ /dev/null @@ -1,6913 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.retail.v2beta", - "version": "v2beta" - } - ], - "language": "PYTHON", - "name": "google-cloud-retail" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.add_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "AddCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "add_catalog_attribute" - }, - "description": "Sample for AddCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_AddCatalogAttribute_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.add_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "AddCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "add_catalog_attribute" - }, - "description": "Sample for AddCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetAttributesConfigRequest" - }, - { - "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.retail_v2beta.types.AttributesConfig", - "shortName": "get_attributes_config" - }, - "description": "Sample for GetAttributesConfig", - "file": "retail_v2beta_generated_catalog_service_get_attributes_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetAttributesConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_attributes_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetAttributesConfigRequest" - }, - { - "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.retail_v2beta.types.AttributesConfig", - "shortName": "get_attributes_config" - }, - "description": "Sample for GetAttributesConfig", - "file": "retail_v2beta_generated_catalog_service_get_attributes_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetAttributesConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_attributes_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_completion_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetCompletionConfigRequest" - }, - { - "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.retail_v2beta.types.CompletionConfig", - "shortName": "get_completion_config" - }, - "description": "Sample for GetCompletionConfig", - "file": "retail_v2beta_generated_catalog_service_get_completion_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetCompletionConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_completion_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_completion_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetCompletionConfigRequest" - }, - { - "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.retail_v2beta.types.CompletionConfig", - "shortName": "get_completion_config" - }, - "description": "Sample for GetCompletionConfig", - "file": "retail_v2beta_generated_catalog_service_get_completion_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetCompletionConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_completion_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2beta_generated_catalog_service_get_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetDefaultBranch_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2beta_generated_catalog_service_get_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetDefaultBranch_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListCatalogsRequest" - }, - { - "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.retail_v2beta.services.catalog_service.pagers.ListCatalogsAsyncPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2beta_generated_catalog_service_list_catalogs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_ListCatalogs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_list_catalogs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListCatalogsRequest" - }, - { - "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.retail_v2beta.services.catalog_service.pagers.ListCatalogsPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2beta_generated_catalog_service_list_catalogs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_ListCatalogs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_list_catalogs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.remove_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "RemoveCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "remove_catalog_attribute" - }, - "description": "Sample for RemoveCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.remove_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "RemoveCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "remove_catalog_attribute" - }, - "description": "Sample for RemoveCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.replace_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ReplaceCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "replace_catalog_attribute" - }, - "description": "Sample for ReplaceCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.replace_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ReplaceCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "replace_catalog_attribute" - }, - "description": "Sample for ReplaceCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2beta_generated_catalog_service_set_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_SetDefaultBranch_async", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_set_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2beta_generated_catalog_service_set_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_SetDefaultBranch_sync", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_set_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest" - }, - { - "name": "attributes_config", - "type": "google.cloud.retail_v2beta.types.AttributesConfig" - }, - { - "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.retail_v2beta.types.AttributesConfig", - "shortName": "update_attributes_config" - }, - "description": "Sample for UpdateAttributesConfig", - "file": "retail_v2beta_generated_catalog_service_update_attributes_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_attributes_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest" - }, - { - "name": "attributes_config", - "type": "google.cloud.retail_v2beta.types.AttributesConfig" - }, - { - "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.retail_v2beta.types.AttributesConfig", - "shortName": "update_attributes_config" - }, - "description": "Sample for UpdateAttributesConfig", - "file": "retail_v2beta_generated_catalog_service_update_attributes_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_attributes_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2beta.types.Catalog" - }, - { - "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.retail_v2beta.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2beta_generated_catalog_service_update_catalog_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateCatalog_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_catalog_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2beta.types.Catalog" - }, - { - "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.retail_v2beta.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2beta_generated_catalog_service_update_catalog_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateCatalog_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_catalog_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_completion_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest" - }, - { - "name": "completion_config", - "type": "google.cloud.retail_v2beta.types.CompletionConfig" - }, - { - "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.retail_v2beta.types.CompletionConfig", - "shortName": "update_completion_config" - }, - "description": "Sample for UpdateCompletionConfig", - "file": "retail_v2beta_generated_catalog_service_update_completion_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_completion_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_completion_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest" - }, - { - "name": "completion_config", - "type": "google.cloud.retail_v2beta.types.CompletionConfig" - }, - { - "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.retail_v2beta.types.CompletionConfig", - "shortName": "update_completion_config" - }, - "description": "Sample for UpdateCompletionConfig", - "file": "retail_v2beta_generated_catalog_service_update_completion_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_completion_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2beta.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2beta_generated_completion_service_complete_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CompletionService_CompleteQuery_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_completion_service_complete_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CompletionServiceClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2beta.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2beta_generated_completion_service_complete_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CompletionService_CompleteQuery_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_completion_service_complete_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2beta.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2beta_generated_completion_service_import_completion_data_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CompletionService_ImportCompletionData_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_completion_service_import_completion_data_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CompletionServiceClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2beta.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2beta_generated_completion_service_import_completion_data_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CompletionService_ImportCompletionData_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_completion_service_import_completion_data_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.create_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.CreateControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "CreateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateControlRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "control", - "type": "google.cloud.retail_v2beta.types.Control" - }, - { - "name": "control_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.retail_v2beta.types.Control", - "shortName": "create_control" - }, - "description": "Sample for CreateControl", - "file": "retail_v2beta_generated_control_service_create_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_CreateControl_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_create_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.create_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.CreateControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "CreateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateControlRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "control", - "type": "google.cloud.retail_v2beta.types.Control" - }, - { - "name": "control_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.retail_v2beta.types.Control", - "shortName": "create_control" - }, - "description": "Sample for CreateControl", - "file": "retail_v2beta_generated_control_service_create_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_CreateControl_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_create_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.delete_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.DeleteControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "DeleteControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteControlRequest" - }, - { - "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_control" - }, - "description": "Sample for DeleteControl", - "file": "retail_v2beta_generated_control_service_delete_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_DeleteControl_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_delete_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.delete_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.DeleteControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "DeleteControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteControlRequest" - }, - { - "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_control" - }, - "description": "Sample for DeleteControl", - "file": "retail_v2beta_generated_control_service_delete_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_DeleteControl_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_delete_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.get_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.GetControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "GetControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetControlRequest" - }, - { - "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.retail_v2beta.types.Control", - "shortName": "get_control" - }, - "description": "Sample for GetControl", - "file": "retail_v2beta_generated_control_service_get_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_GetControl_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_get_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.get_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.GetControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "GetControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetControlRequest" - }, - { - "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.retail_v2beta.types.Control", - "shortName": "get_control" - }, - "description": "Sample for GetControl", - "file": "retail_v2beta_generated_control_service_get_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_GetControl_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_get_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.list_controls", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.ListControls", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "ListControls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListControlsRequest" - }, - { - "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.retail_v2beta.services.control_service.pagers.ListControlsAsyncPager", - "shortName": "list_controls" - }, - "description": "Sample for ListControls", - "file": "retail_v2beta_generated_control_service_list_controls_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_ListControls_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_list_controls_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.list_controls", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.ListControls", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "ListControls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListControlsRequest" - }, - { - "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.retail_v2beta.services.control_service.pagers.ListControlsPager", - "shortName": "list_controls" - }, - "description": "Sample for ListControls", - "file": "retail_v2beta_generated_control_service_list_controls_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_ListControls_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_list_controls_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.update_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.UpdateControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "UpdateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateControlRequest" - }, - { - "name": "control", - "type": "google.cloud.retail_v2beta.types.Control" - }, - { - "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.retail_v2beta.types.Control", - "shortName": "update_control" - }, - "description": "Sample for UpdateControl", - "file": "retail_v2beta_generated_control_service_update_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_UpdateControl_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_update_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.update_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.UpdateControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "UpdateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateControlRequest" - }, - { - "name": "control", - "type": "google.cloud.retail_v2beta.types.Control" - }, - { - "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.retail_v2beta.types.Control", - "shortName": "update_control" - }, - "description": "Sample for UpdateControl", - "file": "retail_v2beta_generated_control_service_update_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_UpdateControl_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_update_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.PredictionServiceAsyncClient", - "shortName": "PredictionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.PredictionServiceAsyncClient.predict", - "method": { - "fullName": "google.cloud.retail.v2beta.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2beta.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2beta_generated_prediction_service_predict_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_PredictionService_Predict_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_prediction_service_predict_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.PredictionServiceClient", - "shortName": "PredictionServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.PredictionServiceClient.predict", - "method": { - "fullName": "google.cloud.retail.v2beta.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2beta.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2beta_generated_prediction_service_predict_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_PredictionService_Predict_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_prediction_service_predict_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2beta_generated_product_service_add_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_add_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2beta_generated_product_service_add_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_add_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2beta_generated_product_service_add_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_AddLocalInventories_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_add_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2beta_generated_product_service_add_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_AddLocalInventories_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_add_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "name": "product_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.retail_v2beta.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2beta_generated_product_service_create_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_CreateProduct_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_create_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "name": "product_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.retail_v2beta.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2beta_generated_product_service_create_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_CreateProduct_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_create_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2beta_generated_product_service_delete_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_DeleteProduct_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_delete_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2beta_generated_product_service_delete_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_DeleteProduct_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_delete_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetProductRequest" - }, - { - "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.retail_v2beta.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2beta_generated_product_service_get_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_GetProduct_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_get_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetProductRequest" - }, - { - "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.retail_v2beta.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2beta_generated_product_service_get_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_GetProduct_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_get_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2beta_generated_product_service_import_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_ImportProducts_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_import_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2beta_generated_product_service_import_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_ImportProducts_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_import_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListProductsRequest" - }, - { - "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.retail_v2beta.services.product_service.pagers.ListProductsAsyncPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2beta_generated_product_service_list_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_ListProducts_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_list_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListProductsRequest" - }, - { - "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.retail_v2beta.services.product_service.pagers.ListProductsPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2beta_generated_product_service_list_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_ListProducts_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_list_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2beta_generated_product_service_remove_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_remove_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2beta_generated_product_service_remove_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_RemoveLocalInventories_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_remove_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2beta_generated_product_service_remove_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_RemoveLocalInventories_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_remove_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2beta_generated_product_service_set_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_SetInventory_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_set_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2beta_generated_product_service_set_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_SetInventory_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_set_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "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.retail_v2beta.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2beta_generated_product_service_update_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_UpdateProduct_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_update_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "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.retail_v2beta.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2beta_generated_product_service_update_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_UpdateProduct_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_update_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.SearchServiceAsyncClient.search", - "method": { - "fullName": "google.cloud.retail.v2beta.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2beta.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2beta_generated_search_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_SearchService_Search_async", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_search_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.SearchServiceClient", - "shortName": "SearchServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.SearchServiceClient.search", - "method": { - "fullName": "google.cloud.retail.v2beta.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2beta.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.services.search_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2beta_generated_search_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_SearchService_Search_sync", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_search_service_search_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.add_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.AddControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "AddControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "add_control" - }, - "description": "Sample for AddControl", - "file": "retail_v2beta_generated_serving_config_service_add_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_AddControl_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_add_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.add_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.AddControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "AddControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "add_control" - }, - "description": "Sample for AddControl", - "file": "retail_v2beta_generated_serving_config_service_add_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_AddControl_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_add_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.create_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.CreateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "CreateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateServingConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2beta.types.ServingConfig" - }, - { - "name": "serving_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "create_serving_config" - }, - "description": "Sample for CreateServingConfig", - "file": "retail_v2beta_generated_serving_config_service_create_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_CreateServingConfig_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_create_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.create_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.CreateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "CreateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateServingConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2beta.types.ServingConfig" - }, - { - "name": "serving_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "create_serving_config" - }, - "description": "Sample for CreateServingConfig", - "file": "retail_v2beta_generated_serving_config_service_create_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_create_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.delete_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.DeleteServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "DeleteServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteServingConfigRequest" - }, - { - "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_serving_config" - }, - "description": "Sample for DeleteServingConfig", - "file": "retail_v2beta_generated_serving_config_service_delete_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_delete_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.delete_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.DeleteServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "DeleteServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteServingConfigRequest" - }, - { - "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_serving_config" - }, - "description": "Sample for DeleteServingConfig", - "file": "retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.get_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.GetServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "GetServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetServingConfigRequest" - }, - { - "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.retail_v2beta.types.ServingConfig", - "shortName": "get_serving_config" - }, - "description": "Sample for GetServingConfig", - "file": "retail_v2beta_generated_serving_config_service_get_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_GetServingConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_get_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.get_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.GetServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "GetServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetServingConfigRequest" - }, - { - "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.retail_v2beta.types.ServingConfig", - "shortName": "get_serving_config" - }, - "description": "Sample for GetServingConfig", - "file": "retail_v2beta_generated_serving_config_service_get_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_GetServingConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_get_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.list_serving_configs", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.ListServingConfigs", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "ListServingConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListServingConfigsRequest" - }, - { - "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.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager", - "shortName": "list_serving_configs" - }, - "description": "Sample for ListServingConfigs", - "file": "retail_v2beta_generated_serving_config_service_list_serving_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_ListServingConfigs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_list_serving_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.list_serving_configs", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.ListServingConfigs", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "ListServingConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListServingConfigsRequest" - }, - { - "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.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsPager", - "shortName": "list_serving_configs" - }, - "description": "Sample for ListServingConfigs", - "file": "retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.remove_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.RemoveControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "RemoveControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "remove_control" - }, - "description": "Sample for RemoveControl", - "file": "retail_v2beta_generated_serving_config_service_remove_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_RemoveControl_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_remove_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.remove_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.RemoveControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "RemoveControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "remove_control" - }, - "description": "Sample for RemoveControl", - "file": "retail_v2beta_generated_serving_config_service_remove_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_RemoveControl_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_remove_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.update_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.UpdateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "UpdateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2beta.types.ServingConfig" - }, - { - "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.retail_v2beta.types.ServingConfig", - "shortName": "update_serving_config" - }, - "description": "Sample for UpdateServingConfig", - "file": "retail_v2beta_generated_serving_config_service_update_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_update_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.update_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.UpdateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "UpdateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2beta.types.ServingConfig" - }, - { - "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.retail_v2beta.types.ServingConfig", - "shortName": "update_serving_config" - }, - "description": "Sample for UpdateServingConfig", - "file": "retail_v2beta_generated_serving_config_service_update_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_update_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2beta_generated_user_event_service_collect_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_CollectUserEvent_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_collect_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2beta_generated_user_event_service_collect_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_CollectUserEvent_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_collect_user_event_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2beta_generated_user_event_service_import_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_ImportUserEvents_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_import_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2beta_generated_user_event_service_import_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_ImportUserEvents_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_import_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2beta_generated_user_event_service_purge_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_PurgeUserEvents_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_purge_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2beta_generated_user_event_service_purge_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_PurgeUserEvents_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_purge_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2beta_generated_user_event_service_rejoin_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_RejoinUserEvents_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_rejoin_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_RejoinUserEvents_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2beta_generated_user_event_service_write_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_WriteUserEvent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_write_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2beta_generated_user_event_service_write_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_WriteUserEvent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_write_user_event_sync.py" - } - ] -} diff --git a/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py b/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py deleted file mode 100644 index dbd16de7..00000000 --- a/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py +++ /dev/null @@ -1,218 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class retailCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_catalog_attribute': ('attributes_config', 'catalog_attribute', ), - 'add_control': ('serving_config', 'control_id', ), - 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), - 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), - 'create_control': ('parent', 'control', 'control_id', ), - 'create_product': ('parent', 'product', 'product_id', ), - 'create_serving_config': ('parent', 'serving_config', 'serving_config_id', ), - 'delete_control': ('name', ), - 'delete_product': ('name', ), - 'delete_serving_config': ('name', ), - 'get_attributes_config': ('name', ), - 'get_completion_config': ('name', ), - 'get_control': ('name', ), - 'get_default_branch': ('catalog', ), - 'get_product': ('name', ), - 'get_serving_config': ('name', ), - 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), - 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), - 'import_user_events': ('parent', 'input_config', 'errors_config', ), - 'list_catalogs': ('parent', 'page_size', 'page_token', ), - 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', ), - 'list_serving_configs': ('parent', 'page_size', 'page_token', ), - 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), - 'purge_user_events': ('parent', 'filter', 'force', ), - 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), - 'remove_catalog_attribute': ('attributes_config', 'key', ), - 'remove_control': ('serving_config', 'control_id', ), - 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), - 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), - 'replace_catalog_attribute': ('attributes_config', 'catalog_attribute', 'update_mask', ), - 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), - 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), - 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), - 'update_attributes_config': ('attributes_config', 'update_mask', ), - 'update_catalog': ('catalog', 'update_mask', ), - 'update_completion_config': ('completion_config', 'update_mask', ), - 'update_control': ('control', 'update_mask', ), - 'update_product': ('product', 'update_mask', 'allow_missing', ), - 'update_serving_config': ('serving_config', 'update_mask', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=retailCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the retail client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2beta/setup.py b/owl-bot-staging/v2beta/setup.py deleted file mode 100644 index 3d49d09f..00000000 --- a/owl-bot-staging/v2beta/setup.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-retail', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-retail", - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.31.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'googleapis-common-protos >= 1.55.0, <2.0.0dev', - 'proto-plus >= 1.19.7', - ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v2beta/tests/__init__.py b/owl-bot-staging/v2beta/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/tests/unit/__init__.py b/owl-bot-staging/v2beta/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py b/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py deleted file mode 100644 index ea836f42..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py +++ /dev/null @@ -1,3793 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.catalog_service import CatalogServiceAsyncClient -from google.cloud.retail_v2beta.services.catalog_service import CatalogServiceClient -from google.cloud.retail_v2beta.services.catalog_service import pagers -from google.cloud.retail_v2beta.services.catalog_service import transports -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CatalogServiceClient._get_default_mtls_endpoint(None) is None - assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CatalogServiceGrpcTransport, "grpc"), - (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_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", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_catalog_service_client_get_transport_class(): - transport = CatalogServiceClient.get_transport_class() - available_transports = [ - transports.CatalogServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CatalogServiceClient.get_transport_class("grpc") - assert transport == transports.CatalogServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - CatalogServiceClient, CatalogServiceAsyncClient -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_catalog_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CatalogServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ListCatalogsRequest, - dict, -]) -def test_list_catalogs(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalogs), - '__call__') as call: - client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - -@pytest.mark.asyncio -async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_catalogs_async_from_dict(): - await test_list_catalogs_async(request_type=dict) - - -def test_list_catalogs_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = catalog_service.ListCatalogsResponse() - client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_catalogs( - 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_catalogs_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_catalogs_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_catalogs( - 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_catalogs_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - - -def test_list_catalogs_pager(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_catalogs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, catalog.Catalog) - for i in results) -def test_list_catalogs_pages(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = list(client.list_catalogs(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_catalogs_async_pager(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_catalogs(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, catalog.Catalog) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_catalogs_async_pages(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCatalogRequest, - dict, -]) -def test_update_catalog(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - ) - response = client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_catalog_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalog), - '__call__') as call: - client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - -@pytest.mark.asyncio -async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_catalog_async_from_dict(): - await test_update_catalog_async(request_type=dict) - - -def test_update_catalog_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = gcr_catalog.Catalog() - client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_catalog_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -def test_update_catalog_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_catalog_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.SetDefaultBranchRequest, - dict, -]) -def test_set_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_set_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_set_default_branch_async_from_dict(): - await test_set_default_branch_async(request_type=dict) - - -def test_set_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = None - client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_set_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_set_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetDefaultBranchRequest, - dict, -]) -def test_get_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - ) - response = client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -def test_get_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_default_branch), - '__call__') as call: - client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - )) - response = await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -@pytest.mark.asyncio -async def test_get_default_branch_async_from_dict(): - await test_get_default_branch_async(request_type=dict) - - -def test_get_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = catalog_service.GetDefaultBranchResponse() - client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_get_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_get_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetCompletionConfigRequest, - dict, -]) -def test_get_completion_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - ) - response = client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -def test_get_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_completion_config), - '__call__') as call: - client.get_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - -@pytest.mark.asyncio -async def test_get_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCompletionConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - )) - response = await client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -@pytest.mark.asyncio -async def test_get_completion_config_async_from_dict(): - await test_get_completion_config_async(request_type=dict) - - -def test_get_completion_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCompletionConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - call.return_value = catalog.CompletionConfig() - client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_completion_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCompletionConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - await client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_completion_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_completion_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_completion_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_completion_config( - catalog_service.GetCompletionConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_completion_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_completion_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_completion_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_completion_config( - catalog_service.GetCompletionConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCompletionConfigRequest, - dict, -]) -def test_update_completion_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - ) - response = client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -def test_update_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_completion_config), - '__call__') as call: - client.update_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - -@pytest.mark.asyncio -async def test_update_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCompletionConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - )) - response = await client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -@pytest.mark.asyncio -async def test_update_completion_config_async_from_dict(): - await test_update_completion_config_async(request_type=dict) - - -def test_update_completion_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCompletionConfigRequest() - - request.completion_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - call.return_value = catalog.CompletionConfig() - client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'completion_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_completion_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCompletionConfigRequest() - - request.completion_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - await client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'completion_config.name=name_value', - ) in kw['metadata'] - - -def test_update_completion_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_completion_config( - completion_config=catalog.CompletionConfig(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].completion_config - mock_val = catalog.CompletionConfig(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_completion_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_completion_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_completion_config( - completion_config=catalog.CompletionConfig(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].completion_config - mock_val = catalog.CompletionConfig(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_completion_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetAttributesConfigRequest, - dict, -]) -def test_get_attributes_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_get_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_attributes_config), - '__call__') as call: - client.get_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - -@pytest.mark.asyncio -async def test_get_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetAttributesConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_get_attributes_config_async_from_dict(): - await test_get_attributes_config_async(request_type=dict) - - -def test_get_attributes_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetAttributesConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_attributes_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetAttributesConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_attributes_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_attributes_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_attributes_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_attributes_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_attributes_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_attributes_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateAttributesConfigRequest, - dict, -]) -def test_update_attributes_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_update_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_attributes_config), - '__call__') as call: - client.update_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - -@pytest.mark.asyncio -async def test_update_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateAttributesConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_update_attributes_config_async_from_dict(): - await test_update_attributes_config_async(request_type=dict) - - -def test_update_attributes_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateAttributesConfigRequest() - - request.attributes_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_attributes_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateAttributesConfigRequest() - - request.attributes_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config.name=name_value', - ) in kw['metadata'] - - -def test_update_attributes_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_attributes_config( - attributes_config=catalog.AttributesConfig(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].attributes_config - mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_attributes_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_attributes_config( - attributes_config=catalog.AttributesConfig(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].attributes_config - mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.AddCatalogAttributeRequest, - dict, -]) -def test_add_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_add_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - client.add_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_add_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.AddCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_add_catalog_attribute_async_from_dict(): - await test_add_catalog_attribute_async(request_type=dict) - - -def test_add_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.AddCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.AddCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - catalog_service.RemoveCatalogAttributeRequest, - dict, -]) -def test_remove_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_remove_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - client.remove_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.RemoveCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_async_from_dict(): - await test_remove_catalog_attribute_async(request_type=dict) - - -def test_remove_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.RemoveCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.RemoveCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ReplaceCatalogAttributeRequest, - dict, -]) -def test_replace_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_replace_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - client.replace_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ReplaceCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_async_from_dict(): - await test_replace_catalog_attribute_async(request_type=dict) - - -def test_replace_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ReplaceCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ReplaceCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CatalogServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.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 = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CatalogServiceGrpcTransport, - ) - -def test_catalog_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_catalog_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_catalogs', - 'update_catalog', - 'set_default_branch', - 'get_default_branch', - 'get_completion_config', - 'update_completion_config', - 'get_attributes_config', - 'update_attributes_config', - 'add_catalog_attribute', - 'remove_catalog_attribute', - 'replace_catalog_attribute', - ) - 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_catalog_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.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport( - 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_catalog_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.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport() - adc.assert_called_once() - - -def test_catalog_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) - CatalogServiceClient() - 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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -def test_catalog_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,grpc_helpers", - [ - (transports.CatalogServiceGrpcTransport, grpc_helpers), - (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_catalog_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_no_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_with_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_catalog_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcTransport( - 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_catalog_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcAsyncIOTransport( - 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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_attributes_config_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.attributes_config_path(project, location, catalog) - assert expected == actual - - -def test_parse_attributes_config_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CatalogServiceClient.attributes_config_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_attributes_config_path(path) - assert expected == actual - -def test_branch_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = CatalogServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "branch": "clam", - } - path = CatalogServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_branch_path(path) - assert expected == actual - -def test_catalog_path(): - project = "whelk" - location = "octopus" - catalog = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - } - path = CatalogServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_completion_config_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.completion_config_path(project, location, catalog) - assert expected == actual - - -def test_parse_completion_config_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - } - path = CatalogServiceClient.completion_config_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_completion_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CatalogServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = CatalogServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = CatalogServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = CatalogServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CatalogServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = CatalogServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = CatalogServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = CatalogServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = CatalogServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CatalogServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py deleted file mode 100644 index 6ba74e1e..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py +++ /dev/null @@ -1,1451 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.completion_service import CompletionServiceAsyncClient -from google.cloud.retail_v2beta.services.completion_service import CompletionServiceClient -from google.cloud.retail_v2beta.services.completion_service import transports -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CompletionServiceClient._get_default_mtls_endpoint(None) is None - assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CompletionServiceGrpcTransport, "grpc"), - (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_completion_service_client_get_transport_class(): - transport = CompletionServiceClient.get_transport_class() - available_transports = [ - transports.CompletionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CompletionServiceClient.get_transport_class("grpc") - assert transport == transports.CompletionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - CompletionServiceClient, CompletionServiceAsyncClient -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_completion_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CompletionServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - ) - response = client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - -@pytest.mark.asyncio -async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - )) - response = await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -@pytest.mark.asyncio -async def test_complete_query_async_from_dict(): - await test_complete_query_async(request_type=dict) - - -def test_complete_query_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = completion_service.CompleteQueryResponse() - client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_complete_query_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) - await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportCompletionDataRequest, - dict, -]) -def test_import_completion_data(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_completion_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - -@pytest.mark.asyncio -async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_completion_data_async_from_dict(): - await test_import_completion_data_async(request_type=dict) - - -def test_import_completion_data_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # 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_completion_data_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CompletionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CompletionServiceGrpcTransport, - ) - -def test_completion_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_completion_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'complete_query', - 'import_completion_data', - ) - 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_completion_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_completion_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport() - adc.assert_called_once() - - -def test_completion_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CompletionServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionServiceGrpcTransport, grpc_helpers), - (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_completion_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_no_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_with_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_completion_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_completion_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_completion_service_grpc_lro_client(): - client = CompletionServiceClient( - 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_completion_service_grpc_lro_async_client(): - client = CompletionServiceAsyncClient( - 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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CompletionServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CompletionServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CompletionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CompletionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = CompletionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CompletionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CompletionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CompletionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = CompletionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CompletionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CompletionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CompletionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CompletionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py deleted file mode 100644 index 0f0f4080..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py +++ /dev/null @@ -1,2554 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.control_service import ControlServiceAsyncClient -from google.cloud.retail_v2beta.services.control_service import ControlServiceClient -from google.cloud.retail_v2beta.services.control_service import pagers -from google.cloud.retail_v2beta.services.control_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.cloud.retail_v2beta.types import search_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ControlServiceClient._get_default_mtls_endpoint(None) is None - assert ControlServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ControlServiceClient, "grpc"), - (ControlServiceAsyncClient, "grpc_asyncio"), -]) -def test_control_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ControlServiceGrpcTransport, "grpc"), - (transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_control_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", [ - (ControlServiceClient, "grpc"), - (ControlServiceAsyncClient, "grpc_asyncio"), -]) -def test_control_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_control_service_client_get_transport_class(): - transport = ControlServiceClient.get_transport_class() - available_transports = [ - transports.ControlServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ControlServiceClient.get_transport_class("grpc") - assert transport == transports.ControlServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -def test_control_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(ControlServiceClient, '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(ControlServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "true"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "false"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_control_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - ControlServiceClient, ControlServiceAsyncClient -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -def test_control_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_control_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_control_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_control_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.control_service.transports.ControlServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ControlServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_control_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.CreateControlRequest, - dict, -]) -def test_create_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_create_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.create_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - -@pytest.mark.asyncio -async def test_create_control_async(transport: str = 'grpc_asyncio', request_type=control_service.CreateControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_create_control_async_from_dict(): - await test_create_control_async(request_type=dict) - - -def test_create_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.CreateControlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - call.return_value = gcr_control.Control() - client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.CreateControlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - await client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_control( - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) - assert arg == mock_val - arg = args[0].control_id - mock_val = 'control_id_value' - assert arg == mock_val - - -def test_create_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.CreateControlRequest(), - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_id_value', - ) - -@pytest.mark.asyncio -async def test_create_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_control( - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) - assert arg == mock_val - arg = args[0].control_id - mock_val = 'control_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.CreateControlRequest(), - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.DeleteControlRequest, - dict, -]) -def test_delete_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.delete_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - -@pytest.mark.asyncio -async def test_delete_control_async(transport: str = 'grpc_asyncio', request_type=control_service.DeleteControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_control_async_from_dict(): - await test_delete_control_async(request_type=dict) - - -def test_delete_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.DeleteControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__call__') as call: - call.return_value = None - client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.DeleteControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__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_control( - 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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.DeleteControlRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__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_control( - 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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.DeleteControlRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.UpdateControlRequest, - dict, -]) -def test_update_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_update_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.update_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - -@pytest.mark.asyncio -async def test_update_control_async(transport: str = 'grpc_asyncio', request_type=control_service.UpdateControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_update_control_async_from_dict(): - await test_update_control_async(request_type=dict) - - -def test_update_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.UpdateControlRequest() - - request.control.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - call.return_value = gcr_control.Control() - client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'control.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.UpdateControlRequest() - - request.control.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - await client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'control.name=name_value', - ) in kw['metadata'] - - -def test_update_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_control( - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_control( - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.GetControlRequest, - dict, -]) -def test_get_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_get_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.get_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - -@pytest.mark.asyncio -async def test_get_control_async(transport: str = 'grpc_asyncio', request_type=control_service.GetControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_get_control_async_from_dict(): - await test_get_control_async(request_type=dict) - - -def test_get_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.GetControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - call.return_value = control.Control() - client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.GetControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) - await client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_control( - 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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.GetControlRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_control( - 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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.GetControlRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.ListControlsRequest, - dict, -]) -def test_list_controls(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_controls_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_controls), - '__call__') as call: - client.list_controls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - -@pytest.mark.asyncio -async def test_list_controls_async(transport: str = 'grpc_asyncio', request_type=control_service.ListControlsRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_controls_async_from_dict(): - await test_list_controls_async(request_type=dict) - - -def test_list_controls_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.ListControlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - call.return_value = control_service.ListControlsResponse() - client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_controls_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.ListControlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) - await client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_controls_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_controls( - 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_controls_flattened_error(): - client = ControlServiceClient( - credentials=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_controls( - control_service.ListControlsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_controls_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_controls( - 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_controls_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_controls( - control_service.ListControlsRequest(), - parent='parent_value', - ) - - -def test_list_controls_pager(transport_name: str = "grpc"): - client = ControlServiceClient( - 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_controls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_controls(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, control.Control) - for i in results) -def test_list_controls_pages(transport_name: str = "grpc"): - client = ControlServiceClient( - 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_controls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - pages = list(client.list_controls(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_controls_async_pager(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_controls(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, control.Control) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_controls_async_pages(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_controls(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ControlServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ControlServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ControlServiceClient.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 = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ControlServiceGrpcTransport, - ) - -def test_control_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ControlServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_control_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.control_service.transports.ControlServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ControlServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_control', - 'delete_control', - 'update_control', - 'get_control', - 'list_controls', - ) - 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_control_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.retail_v2beta.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ControlServiceTransport( - 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_control_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.retail_v2beta.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ControlServiceTransport() - adc.assert_called_once() - - -def test_control_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) - ControlServiceClient() - 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.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - ], -) -def test_control_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,grpc_helpers", - [ - (transports.ControlServiceGrpcTransport, grpc_helpers), - (transports.ControlServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_control_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_control_service_host_no_port(transport_name): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_control_service_host_with_port(transport_name): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_control_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ControlServiceGrpcTransport( - 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_control_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ControlServiceGrpcAsyncIOTransport( - 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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = ControlServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = ControlServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_control_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - control = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) - actual = ControlServiceClient.control_path(project, location, catalog, control) - assert expected == actual - - -def test_parse_control_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "control": "clam", - } - path = ControlServiceClient.control_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_control_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ControlServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ControlServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ControlServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ControlServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ControlServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ControlServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ControlServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ControlServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.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 = ControlServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ControlServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.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.ControlServiceTransport, '_prep_wrapped_messages') as prep: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ControlServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ControlServiceClient.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 = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ControlServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ControlServiceClient( - 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", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py deleted file mode 100644 index 3115c5c9..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py +++ /dev/null @@ -1,1279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.prediction_service import PredictionServiceAsyncClient -from google.cloud.retail_v2beta.services.prediction_service import PredictionServiceClient -from google.cloud.retail_v2beta.services.prediction_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import prediction_service -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import promotion -from google.cloud.retail_v2beta.types import user_event -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PredictionServiceClient._get_default_mtls_endpoint(None) is None - assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PredictionServiceGrpcTransport, "grpc"), - (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_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", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_prediction_service_client_get_transport_class(): - transport = PredictionServiceClient.get_transport_class() - available_transports = [ - transports.PredictionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = PredictionServiceClient.get_transport_class("grpc") - assert transport == transports.PredictionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - PredictionServiceClient, PredictionServiceAsyncClient -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_prediction_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PredictionServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - prediction_service.PredictRequest, - dict, -]) -def test_predict(request_type, transport: str = 'grpc'): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - response = client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - -@pytest.mark.asyncio -async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - )) - response = await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -@pytest.mark.asyncio -async def test_predict_async_from_dict(): - await test_predict_async(request_type=dict) - - -def test_predict_field_headers(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = prediction_service.PredictResponse() - client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_predict_field_headers_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) - await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PredictionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PredictionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.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 = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, - ) - -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'predict', - ) - 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport( - 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport() - adc.assert_called_once() - - -def test_prediction_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) - PredictionServiceClient() - 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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -def test_prediction_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,grpc_helpers", - [ - (transports.PredictionServiceGrpcTransport, grpc_helpers), - (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_prediction_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_no_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_with_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_prediction_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcTransport( - 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_prediction_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcAsyncIOTransport( - 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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_product_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - product = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - "branch": "winkle", - "product": "nautilus", - } - path = PredictionServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PredictionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = PredictionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = PredictionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = PredictionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PredictionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = PredictionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = PredictionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = PredictionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = PredictionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PredictionServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py deleted file mode 100644 index 87547c3f..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py +++ /dev/null @@ -1,4085 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.product_service import ProductServiceAsyncClient -from google.cloud.retail_v2beta.services.product_service import ProductServiceClient -from google.cloud.retail_v2beta.services.product_service import pagers -from google.cloud.retail_v2beta.services.product_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.cloud.retail_v2beta.types import promotion -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ProductServiceClient._get_default_mtls_endpoint(None) is None - assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ProductServiceGrpcTransport, "grpc"), - (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_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", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_product_service_client_get_transport_class(): - transport = ProductServiceClient.get_transport_class() - available_transports = [ - transports.ProductServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ProductServiceClient.get_transport_class("grpc") - assert transport == transports.ProductServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_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(ProductServiceClient, '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(ProductServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - ProductServiceClient, ProductServiceAsyncClient -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_product_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProductServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.CreateProductRequest, - dict, -]) -def test_create_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_create_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - -@pytest.mark.asyncio -async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_create_product_async_from_dict(): - await test_create_product_async(request_type=dict) - - -def test_create_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - - -def test_create_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - -@pytest.mark.asyncio -async def test_create_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.GetProductRequest, - dict, -]) -def test_get_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_get_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - -@pytest.mark.asyncio -async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_get_product_async_from_dict(): - await test_get_product_async(request_type=dict) - - -def test_get_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = product.Product() - client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.GetProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.GetProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.ListProductsRequest, - dict, -]) -def test_list_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - -@pytest.mark.asyncio -async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_products_async_from_dict(): - await test_list_products_async(request_type=dict) - - -def test_list_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = product_service.ListProductsResponse() - client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_products( - 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_products_flattened_error(): - client = ProductServiceClient( - credentials=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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_products_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_products( - 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_products_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - - -def test_list_products_pager(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_products(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, product.Product) - for i in results) -def test_list_products_pages(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = list(client.list_products(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_products_async_pager(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_products(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, product.Product) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_products_async_pages(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_products(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - product_service.UpdateProductRequest, - dict, -]) -def test_update_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_update_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - -@pytest.mark.asyncio -async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_update_product_async_from_dict(): - await test_update_product_async(request_type=dict) - - -def test_update_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -def test_update_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.DeleteProductRequest, - dict, -]) -def test_delete_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - -@pytest.mark.asyncio -async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_product_async_from_dict(): - await test_delete_product_async(request_type=dict) - - -def test_delete_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = None - client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportProductsRequest, - dict, -]) -def test_import_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - -@pytest.mark.asyncio -async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__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_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_products_async_from_dict(): - await test_import_products_async(request_type=dict) - - -def test_import_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - product_service.SetInventoryRequest, - dict, -]) -def test_set_inventory(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_inventory_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - -@pytest.mark.asyncio -async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_inventory_async_from_dict(): - await test_set_inventory_async(request_type=dict) - - -def test_set_inventory_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_inventory_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -def test_set_inventory_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_set_inventory_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_set_inventory_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_inventory_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddFulfillmentPlacesRequest, - dict, -]) -def test_add_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async_from_dict(): - await test_add_fulfillment_places_async(request_type=dict) - - -def test_add_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveFulfillmentPlacesRequest, - dict, -]) -def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async_from_dict(): - await test_remove_fulfillment_places_async(request_type=dict) - - -def test_remove_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddLocalInventoriesRequest, - dict, -]) -def test_add_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_local_inventories_async_from_dict(): - await test_add_local_inventories_async(request_type=dict) - - -def test_add_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveLocalInventoriesRequest, - dict, -]) -def test_remove_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_local_inventories_async_from_dict(): - await test_remove_local_inventories_async(request_type=dict) - - -def test_remove_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProductServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ProductServiceClient.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 = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProductServiceGrpcTransport, - ) - -def test_product_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_product_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.product_service.transports.ProductServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_product', - 'get_product', - 'list_products', - 'update_product', - 'delete_product', - 'import_products', - 'set_inventory', - 'add_fulfillment_places', - 'remove_fulfillment_places', - 'add_local_inventories', - 'remove_local_inventories', - ) - 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_product_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.retail_v2beta.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport( - 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_product_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.retail_v2beta.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport() - adc.assert_called_once() - - -def test_product_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) - ProductServiceClient() - 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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - ], -) -def test_product_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,grpc_helpers", - [ - (transports.ProductServiceGrpcTransport, grpc_helpers), - (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_product_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_no_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_with_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_product_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcTransport( - 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_product_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcAsyncIOTransport( - 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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_product_service_grpc_lro_client(): - client = ProductServiceClient( - 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_product_service_grpc_lro_async_client(): - client = ProductServiceAsyncClient( - 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" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = ProductServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = ProductServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = ProductServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = ProductServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProductServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ProductServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProductServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ProductServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProductServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ProductServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ProductServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ProductServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ProductServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ProductServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ProductServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py deleted file mode 100644 index 9ee8f756..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py +++ /dev/null @@ -1,1496 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.search_service import SearchServiceAsyncClient -from google.cloud.retail_v2beta.services.search_service import SearchServiceClient -from google.cloud.retail_v2beta.services.search_service import pagers -from google.cloud.retail_v2beta.services.search_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SearchServiceClient._get_default_mtls_endpoint(None) is None - assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SearchServiceGrpcTransport, "grpc"), - (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_search_service_client_get_transport_class(): - transport = SearchServiceClient.get_transport_class() - available_transports = [ - transports.SearchServiceGrpcTransport, - ] - assert transport in available_transports - - transport = SearchServiceClient.get_transport_class("grpc") - assert transport == transports.SearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - SearchServiceClient, SearchServiceAsyncClient -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SearchServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - search_service.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - - -def test_search_field_headers(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = search_service.SearchResponse() - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_field_headers_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_search_pager(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('placement', ''), - )), - ) - pager = client.search(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_async_pager(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, - ) - -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_search_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_search_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport() - adc.assert_called_once() - - -def test_search_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SearchServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SearchServiceGrpcTransport, grpc_helpers), - (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_search_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_no_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_with_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_branch_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = SearchServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = SearchServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = SearchServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = SearchServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py deleted file mode 100644 index 071b0b17..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py +++ /dev/null @@ -1,3279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.serving_config_service import ServingConfigServiceAsyncClient -from google.cloud.retail_v2beta.services.serving_config_service import ServingConfigServiceClient -from google.cloud.retail_v2beta.services.serving_config_service import pagers -from google.cloud.retail_v2beta.services.serving_config_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ServingConfigServiceClient._get_default_mtls_endpoint(None) is None - assert ServingConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServingConfigServiceClient, "grpc"), - (ServingConfigServiceAsyncClient, "grpc_asyncio"), -]) -def test_serving_config_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ServingConfigServiceGrpcTransport, "grpc"), - (transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_serving_config_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", [ - (ServingConfigServiceClient, "grpc"), - (ServingConfigServiceAsyncClient, "grpc_asyncio"), -]) -def test_serving_config_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_serving_config_service_client_get_transport_class(): - transport = ServingConfigServiceClient.get_transport_class() - available_transports = [ - transports.ServingConfigServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ServingConfigServiceClient.get_transport_class("grpc") - assert transport == transports.ServingConfigServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -def test_serving_config_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(ServingConfigServiceClient, '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(ServingConfigServiceClient, '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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "true"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "false"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_serving_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - ServingConfigServiceClient, ServingConfigServiceAsyncClient -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -def test_serving_config_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_serving_config_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_serving_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_serving_config_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ServingConfigServiceClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_serving_config_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.CreateServingConfigRequest, - dict, -]) -def test_create_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_create_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.create_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - -@pytest.mark.asyncio -async def test_create_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.CreateServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_create_serving_config_async_from_dict(): - await test_create_serving_config_async(request_type=dict) - - -def test_create_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.CreateServingConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.CreateServingConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_serving_config( - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].serving_config - mock_val = gcr_serving_config.ServingConfig(name='name_value') - assert arg == mock_val - arg = args[0].serving_config_id - mock_val = 'serving_config_id_value' - assert arg == mock_val - - -def test_create_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.CreateServingConfigRequest(), - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_serving_config( - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].serving_config - mock_val = gcr_serving_config.ServingConfig(name='name_value') - assert arg == mock_val - arg = args[0].serving_config_id - mock_val = 'serving_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.CreateServingConfigRequest(), - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.DeleteServingConfigRequest, - dict, -]) -def test_delete_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.delete_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - -@pytest.mark.asyncio -async def test_delete_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.DeleteServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_serving_config_async_from_dict(): - await test_delete_serving_config_async(request_type=dict) - - -def test_delete_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.DeleteServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__call__') as call: - call.return_value = None - client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.DeleteServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__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_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.DeleteServingConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__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_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.DeleteServingConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.UpdateServingConfigRequest, - dict, -]) -def test_update_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_update_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.update_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - -@pytest.mark.asyncio -async def test_update_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.UpdateServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_update_serving_config_async_from_dict(): - await test_update_serving_config_async(request_type=dict) - - -def test_update_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.UpdateServingConfigRequest() - - request.serving_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.UpdateServingConfigRequest() - - request.serving_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config.name=name_value', - ) in kw['metadata'] - - -def test_update_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_serving_config( - serving_config=gcr_serving_config.ServingConfig(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].serving_config - mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_serving_config( - serving_config=gcr_serving_config.ServingConfig(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].serving_config - mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.GetServingConfigRequest, - dict, -]) -def test_get_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_get_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.get_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - -@pytest.mark.asyncio -async def test_get_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.GetServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_get_serving_config_async_from_dict(): - await test_get_serving_config_async(request_type=dict) - - -def test_get_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.GetServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - call.return_value = serving_config.ServingConfig() - client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.GetServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) - await client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.GetServingConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.GetServingConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.ListServingConfigsRequest, - dict, -]) -def test_list_serving_configs(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_serving_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_configs), - '__call__') as call: - client.list_serving_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - -@pytest.mark.asyncio -async def test_list_serving_configs_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.ListServingConfigsRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_serving_configs_async_from_dict(): - await test_list_serving_configs_async(request_type=dict) - - -def test_list_serving_configs_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.ListServingConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - call.return_value = serving_config_service.ListServingConfigsResponse() - client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_serving_configs_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.ListServingConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) - await client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_serving_configs_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_serving_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_serving_configs_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_serving_configs_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_serving_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_serving_configs_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent='parent_value', - ) - - -def test_list_serving_configs_pager(transport_name: str = "grpc"): - client = ServingConfigServiceClient( - 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_serving_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_serving_configs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, serving_config.ServingConfig) - for i in results) -def test_list_serving_configs_pages(transport_name: str = "grpc"): - client = ServingConfigServiceClient( - 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_serving_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_serving_configs(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_serving_configs_async_pager(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_serving_configs(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, serving_config.ServingConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_serving_configs_async_pages(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_serving_configs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - serving_config_service.AddControlRequest, - dict, -]) -def test_add_control(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_add_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - client.add_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - -@pytest.mark.asyncio -async def test_add_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.AddControlRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_add_control_async_from_dict(): - await test_add_control_async(request_type=dict) - - -def test_add_control_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.AddControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_control_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.AddControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_add_control_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.add_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - - -def test_add_control_flattened_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_control( - serving_config_service.AddControlRequest(), - serving_config='serving_config_value', - ) - -@pytest.mark.asyncio -async def test_add_control_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.add_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_control_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_control( - serving_config_service.AddControlRequest(), - serving_config='serving_config_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.RemoveControlRequest, - dict, -]) -def test_remove_control(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_remove_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - client.remove_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - -@pytest.mark.asyncio -async def test_remove_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.RemoveControlRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_remove_control_async_from_dict(): - await test_remove_control_async(request_type=dict) - - -def test_remove_control_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.RemoveControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_control_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.RemoveControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_remove_control_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.remove_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - - -def test_remove_control_flattened_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config='serving_config_value', - ) - -@pytest.mark.asyncio -async def test_remove_control_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.remove_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_control_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config='serving_config_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ServingConfigServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ServingConfigServiceClient.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 = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ServingConfigServiceGrpcTransport, - ) - -def test_serving_config_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ServingConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_serving_config_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ServingConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_serving_config', - 'delete_serving_config', - 'update_serving_config', - 'get_serving_config', - 'list_serving_configs', - 'add_control', - 'remove_control', - ) - 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_serving_config_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.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServingConfigServiceTransport( - 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_serving_config_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.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServingConfigServiceTransport() - adc.assert_called_once() - - -def test_serving_config_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) - ServingConfigServiceClient() - 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.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - ], -) -def test_serving_config_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,grpc_helpers", - [ - (transports.ServingConfigServiceGrpcTransport, grpc_helpers), - (transports.ServingConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_serving_config_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_serving_config_service_host_no_port(transport_name): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_serving_config_service_host_with_port(transport_name): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_serving_config_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServingConfigServiceGrpcTransport( - 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_serving_config_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( - 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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = ServingConfigServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = ServingConfigServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - serving_config = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, serving_config=serving_config, ) - actual = ServingConfigServiceClient.serving_config_path(project, location, catalog, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "serving_config": "clam", - } - path = ServingConfigServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ServingConfigServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ServingConfigServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ServingConfigServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ServingConfigServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ServingConfigServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ServingConfigServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ServingConfigServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ServingConfigServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.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 = ServingConfigServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ServingConfigServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.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.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ServingConfigServiceClient.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 = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ServingConfigServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ServingConfigServiceClient( - 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", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py deleted file mode 100644 index 0274310f..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py +++ /dev/null @@ -1,1988 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.retail_v2beta.services.user_event_service import UserEventServiceClient -from google.cloud.retail_v2beta.services.user_event_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import promotion -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, UserEventServiceAsyncClient -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - ) - response = client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = user_event.UserEvent() - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) - await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeUserEventsRequest, - dict, -]) -def test_purge_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - -@pytest.mark.asyncio -async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_user_events_async_from_dict(): - await test_purge_user_events_async(request_type=dict) - - -def test_purge_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_purge_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.RejoinUserEventsRequest, - dict, -]) -def test_rejoin_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_rejoin_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - -@pytest.mark.asyncio -async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_rejoin_user_events_async_from_dict(): - await test_rejoin_user_events_async(request_type=dict) - - -def test_rejoin_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_rejoin_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'purge_user_events', - 'import_user_events', - 'rejoin_user_events', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_user_event_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_user_event_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -def test_user_event_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - UserEventServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_no_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_with_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = UserEventServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = UserEventServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_product_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - product = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - "branch": "whelk", - "product": "octopus", - } - path = UserEventServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/scripts/fixup_retail_v2_keywords.py b/scripts/fixup_retail_v2_keywords.py index e4946a58..9ed9d278 100644 --- a/scripts/fixup_retail_v2_keywords.py +++ b/scripts/fixup_retail_v2_keywords.py @@ -57,7 +57,7 @@ class retailCallTransformer(cst.CSTTransformer): 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), - 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), + 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', 'labels', 'spell_correction_spec', ), 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), 'update_catalog': ('catalog', 'update_mask', ), From 8338a40f36372578870b1c32b837ade2655c74fe Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 23 Jun 2022 22:10:13 +0000 Subject: [PATCH 03/11] feat: add audience parameter PiperOrigin-RevId: 456827138 Source-Link: https://github.com/googleapis/googleapis/commit/23f1a157189581734c7a77cddfeb7c5bc1e440ae Source-Link: https://github.com/googleapis/googleapis-gen/commit/4075a8514f676691ec156688a5bbf183aa9893ce Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNDA3NWE4NTE0ZjY3NjY5MWVjMTU2Njg4YTViYmYxODNhYTk4OTNjZSJ9 --- owl-bot-staging/v2/.coveragerc | 17 + owl-bot-staging/v2/.flake8 | 33 + owl-bot-staging/v2/MANIFEST.in | 2 + owl-bot-staging/v2/README.rst | 49 + owl-bot-staging/v2/docs/conf.py | 376 + owl-bot-staging/v2/docs/index.rst | 7 + .../v2/docs/retail_v2/catalog_service.rst | 10 + .../v2/docs/retail_v2/completion_service.rst | 6 + .../v2/docs/retail_v2/prediction_service.rst | 6 + .../v2/docs/retail_v2/product_service.rst | 10 + .../v2/docs/retail_v2/search_service.rst | 10 + .../v2/docs/retail_v2/services.rst | 11 + owl-bot-staging/v2/docs/retail_v2/types.rst | 7 + .../v2/docs/retail_v2/user_event_service.rst | 6 + .../v2/google/cloud/retail/__init__.py | 193 + .../v2/google/cloud/retail/py.typed | 2 + .../v2/google/cloud/retail_v2/__init__.py | 194 + .../cloud/retail_v2/gapic_metadata.json | 333 + .../v2/google/cloud/retail_v2/py.typed | 2 + .../cloud/retail_v2/services/__init__.py | 15 + .../services/catalog_service/__init__.py | 22 + .../services/catalog_service/async_client.py | 653 ++ .../services/catalog_service/client.py | 862 ++ .../services/catalog_service/pagers.py | 140 + .../catalog_service/transports/__init__.py | 33 + .../catalog_service/transports/base.py | 198 + .../catalog_service/transports/grpc.py | 381 + .../transports/grpc_asyncio.py | 380 + .../services/completion_service/__init__.py | 22 + .../completion_service/async_client.py | 391 + .../services/completion_service/client.py | 593 ++ .../completion_service/transports/__init__.py | 33 + .../completion_service/transports/base.py | 176 + .../completion_service/transports/grpc.py | 325 + .../transports/grpc_asyncio.py | 324 + .../services/prediction_service/__init__.py | 22 + .../prediction_service/async_client.py | 279 + .../services/prediction_service/client.py | 480 ++ .../prediction_service/transports/__init__.py | 33 + .../prediction_service/transports/base.py | 154 + .../prediction_service/transports/grpc.py | 264 + .../transports/grpc_asyncio.py | 263 + .../services/product_service/__init__.py | 22 + .../services/product_service/async_client.py | 1701 ++++ .../services/product_service/client.py | 1904 +++++ .../services/product_service/pagers.py | 140 + .../product_service/transports/__init__.py | 33 + .../product_service/transports/base.py | 312 + .../product_service/transports/grpc.py | 680 ++ .../transports/grpc_asyncio.py | 679 ++ .../services/search_service/__init__.py | 22 + .../services/search_service/async_client.py | 303 + .../services/search_service/client.py | 513 ++ .../services/search_service/pagers.py | 139 + .../search_service/transports/__init__.py | 33 + .../search_service/transports/base.py | 154 + .../search_service/transports/grpc.py | 270 + .../search_service/transports/grpc_asyncio.py | 269 + .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 730 ++ .../services/user_event_service/client.py | 930 +++ .../user_event_service/transports/__init__.py | 33 + .../user_event_service/transports/base.py | 235 + .../user_event_service/transports/grpc.py | 417 + .../transports/grpc_asyncio.py | 416 + .../google/cloud/retail_v2/types/__init__.py | 194 + .../google/cloud/retail_v2/types/catalog.py | 131 + .../cloud/retail_v2/types/catalog_service.py | 248 + .../v2/google/cloud/retail_v2/types/common.py | 736 ++ .../retail_v2/types/completion_service.py | 229 + .../cloud/retail_v2/types/import_config.py | 697 ++ .../retail_v2/types/prediction_service.py | 275 + .../google/cloud/retail_v2/types/product.py | 701 ++ .../cloud/retail_v2/types/product_service.py | 858 ++ .../google/cloud/retail_v2/types/promotion.py | 50 + .../cloud/retail_v2/types/purge_config.py | 107 + .../cloud/retail_v2/types/search_service.py | 1150 +++ .../cloud/retail_v2/types/user_event.py | 508 ++ .../retail_v2/types/user_event_service.py | 154 + owl-bot-staging/v2/mypy.ini | 3 + owl-bot-staging/v2/noxfile.py | 180 + ...atalog_service_get_default_branch_async.py | 44 + ...catalog_service_get_default_branch_sync.py | 44 + ...ted_catalog_service_list_catalogs_async.py | 46 + ...ated_catalog_service_list_catalogs_sync.py | 46 + ...atalog_service_set_default_branch_async.py | 42 + ...catalog_service_set_default_branch_sync.py | 42 + ...ed_catalog_service_update_catalog_async.py | 49 + ...ted_catalog_service_update_catalog_sync.py | 49 + ...completion_service_complete_query_async.py | 46 + ..._completion_service_complete_query_sync.py | 46 + ...on_service_import_completion_data_async.py | 54 + ...ion_service_import_completion_data_sync.py | 54 + ...erated_prediction_service_predict_async.py | 50 + ...nerated_prediction_service_predict_sync.py | 50 + ...ct_service_add_fulfillment_places_async.py | 51 + ...uct_service_add_fulfillment_places_sync.py | 51 + ...uct_service_add_local_inventories_async.py | 49 + ...duct_service_add_local_inventories_sync.py | 49 + ...ed_product_service_create_product_async.py | 50 + ...ted_product_service_create_product_sync.py | 50 + ...ed_product_service_delete_product_async.py | 43 + ...ted_product_service_delete_product_sync.py | 43 + ...rated_product_service_get_product_async.py | 45 + ...erated_product_service_get_product_sync.py | 45 + ...d_product_service_import_products_async.py | 53 + ...ed_product_service_import_products_sync.py | 53 + ...ted_product_service_list_products_async.py | 46 + ...ated_product_service_list_products_sync.py | 46 + ...service_remove_fulfillment_places_async.py | 51 + ..._service_remove_fulfillment_places_sync.py | 51 + ..._service_remove_local_inventories_async.py | 50 + ...t_service_remove_local_inventories_sync.py | 50 + ...ted_product_service_set_inventory_async.py | 52 + ...ated_product_service_set_inventory_sync.py | 52 + ...ed_product_service_update_product_async.py | 48 + ...ted_product_service_update_product_sync.py | 48 + ...2_generated_search_service_search_async.py | 47 + ...v2_generated_search_service_search_sync.py | 47 + ..._event_service_collect_user_event_async.py | 46 + ...r_event_service_collect_user_event_sync.py | 46 + ..._event_service_import_user_events_async.py | 54 + ...r_event_service_import_user_events_sync.py | 54 + ...r_event_service_purge_user_events_async.py | 50 + ...er_event_service_purge_user_events_sync.py | 50 + ..._event_service_rejoin_user_events_async.py | 49 + ...r_event_service_rejoin_user_events_sync.py | 49 + ...er_event_service_write_user_event_async.py | 50 + ...ser_event_service_write_user_event_sync.py | 50 + .../snippet_metadata_retail_v2.json | 3826 +++++++++ .../v2/scripts/fixup_retail_v2_keywords.py | 199 + owl-bot-staging/v2/setup.py | 59 + owl-bot-staging/v2/tests/__init__.py | 16 + owl-bot-staging/v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../v2/tests/unit/gapic/retail_v2/__init__.py | 16 + .../gapic/retail_v2/test_catalog_service.py | 2318 ++++++ .../retail_v2/test_completion_service.py | 1502 ++++ .../retail_v2/test_prediction_service.py | 1330 ++++ .../gapic/retail_v2/test_product_service.py | 4136 ++++++++++ .../gapic/retail_v2/test_search_service.py | 1547 ++++ .../retail_v2/test_user_event_service.py | 2039 +++++ owl-bot-staging/v2alpha/.coveragerc | 17 + owl-bot-staging/v2alpha/.flake8 | 33 + owl-bot-staging/v2alpha/MANIFEST.in | 2 + owl-bot-staging/v2alpha/README.rst | 49 + owl-bot-staging/v2alpha/docs/conf.py | 376 + owl-bot-staging/v2alpha/docs/index.rst | 7 + .../docs/retail_v2alpha/catalog_service.rst | 10 + .../retail_v2alpha/completion_service.rst | 6 + .../docs/retail_v2alpha/control_service.rst | 10 + .../retail_v2alpha/prediction_service.rst | 6 + .../docs/retail_v2alpha/product_service.rst | 10 + .../docs/retail_v2alpha/search_service.rst | 10 + .../v2alpha/docs/retail_v2alpha/services.rst | 13 + .../retail_v2alpha/serving_config_service.rst | 10 + .../v2alpha/docs/retail_v2alpha/types.rst | 7 + .../retail_v2alpha/user_event_service.rst | 6 + .../v2alpha/google/cloud/retail/__init__.py | 281 + .../v2alpha/google/cloud/retail/py.typed | 2 + .../google/cloud/retail_v2alpha/__init__.py | 282 + .../cloud/retail_v2alpha/gapic_metadata.json | 561 ++ .../google/cloud/retail_v2alpha/py.typed | 2 + .../cloud/retail_v2alpha/services/__init__.py | 15 + .../services/catalog_service/__init__.py | 22 + .../services/catalog_service/async_client.py | 1352 ++++ .../services/catalog_service/client.py | 1582 ++++ .../services/catalog_service/pagers.py | 140 + .../catalog_service/transports/__init__.py | 33 + .../catalog_service/transports/base.py | 297 + .../catalog_service/transports/grpc.py | 600 ++ .../transports/grpc_asyncio.py | 599 ++ .../services/completion_service/__init__.py | 22 + .../completion_service/async_client.py | 391 + .../services/completion_service/client.py | 593 ++ .../completion_service/transports/__init__.py | 33 + .../completion_service/transports/base.py | 176 + .../completion_service/transports/grpc.py | 325 + .../transports/grpc_asyncio.py | 324 + .../services/control_service/__init__.py | 22 + .../services/control_service/async_client.py | 744 ++ .../services/control_service/client.py | 953 +++ .../services/control_service/pagers.py | 140 + .../control_service/transports/__init__.py | 33 + .../control_service/transports/base.py | 213 + .../control_service/transports/grpc.py | 382 + .../transports/grpc_asyncio.py | 381 + .../services/prediction_service/__init__.py | 22 + .../prediction_service/async_client.py | 279 + .../services/prediction_service/client.py | 480 ++ .../prediction_service/transports/__init__.py | 33 + .../prediction_service/transports/base.py | 154 + .../prediction_service/transports/grpc.py | 264 + .../transports/grpc_asyncio.py | 263 + .../services/product_service/__init__.py | 22 + .../services/product_service/async_client.py | 1804 +++++ .../services/product_service/client.py | 2008 +++++ .../services/product_service/pagers.py | 140 + .../product_service/transports/__init__.py | 33 + .../product_service/transports/base.py | 327 + .../product_service/transports/grpc.py | 726 ++ .../transports/grpc_asyncio.py | 725 ++ .../services/search_service/__init__.py | 22 + .../services/search_service/async_client.py | 303 + .../services/search_service/client.py | 513 ++ .../services/search_service/pagers.py | 139 + .../search_service/transports/__init__.py | 33 + .../search_service/transports/base.py | 154 + .../search_service/transports/grpc.py | 270 + .../search_service/transports/grpc_asyncio.py | 269 + .../serving_config_service/__init__.py | 22 + .../serving_config_service/async_client.py | 954 +++ .../services/serving_config_service/client.py | 1163 +++ .../services/serving_config_service/pagers.py | 140 + .../transports/__init__.py | 33 + .../serving_config_service/transports/base.py | 241 + .../serving_config_service/transports/grpc.py | 440 + .../transports/grpc_asyncio.py | 439 + .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 730 ++ .../services/user_event_service/client.py | 930 +++ .../user_event_service/transports/__init__.py | 33 + .../user_event_service/transports/base.py | 235 + .../user_event_service/transports/grpc.py | 417 + .../transports/grpc_asyncio.py | 416 + .../cloud/retail_v2alpha/types/__init__.py | 284 + .../cloud/retail_v2alpha/types/catalog.py | 528 ++ .../retail_v2alpha/types/catalog_service.py | 453 ++ .../cloud/retail_v2alpha/types/common.py | 1179 +++ .../types/completion_service.py | 223 + .../cloud/retail_v2alpha/types/control.py | 123 + .../retail_v2alpha/types/control_service.py | 197 + .../retail_v2alpha/types/export_config.py | 134 + .../retail_v2alpha/types/import_config.py | 691 ++ .../types/prediction_service.py | 263 + .../cloud/retail_v2alpha/types/product.py | 705 ++ .../retail_v2alpha/types/product_service.py | 877 ++ .../cloud/retail_v2alpha/types/promotion.py | 50 + .../retail_v2alpha/types/purge_config.py | 251 + .../retail_v2alpha/types/search_service.py | 1099 +++ .../retail_v2alpha/types/serving_config.py | 309 + .../types/serving_config_service.py | 234 + .../cloud/retail_v2alpha/types/user_event.py | 507 ++ .../types/user_event_service.py | 154 + owl-bot-staging/v2alpha/mypy.ini | 3 + owl-bot-staging/v2alpha/noxfile.py | 180 + ...log_service_add_catalog_attribute_async.py | 49 + ...alog_service_add_catalog_attribute_sync.py | 49 + ...log_service_get_attributes_config_async.py | 45 + ...alog_service_get_attributes_config_sync.py | 45 + ...log_service_get_completion_config_async.py | 45 + ...alog_service_get_completion_config_sync.py | 45 + ...atalog_service_get_default_branch_async.py | 44 + ...catalog_service_get_default_branch_sync.py | 44 + ...ted_catalog_service_list_catalogs_async.py | 46 + ...ated_catalog_service_list_catalogs_sync.py | 46 + ..._service_remove_catalog_attribute_async.py | 46 + ...g_service_remove_catalog_attribute_sync.py | 46 + ...service_replace_catalog_attribute_async.py | 49 + ..._service_replace_catalog_attribute_sync.py | 49 + ...atalog_service_set_default_branch_async.py | 42 + ...catalog_service_set_default_branch_sync.py | 42 + ..._service_update_attributes_config_async.py | 48 + ...g_service_update_attributes_config_sync.py | 48 + ...ed_catalog_service_update_catalog_async.py | 49 + ...ted_catalog_service_update_catalog_sync.py | 49 + ..._service_update_completion_config_async.py | 48 + ...g_service_update_completion_config_sync.py | 48 + ...completion_service_complete_query_async.py | 46 + ..._completion_service_complete_query_sync.py | 46 + ...on_service_import_completion_data_async.py | 54 + ...ion_service_import_completion_data_sync.py | 54 + ...ed_control_service_create_control_async.py | 53 + ...ted_control_service_create_control_sync.py | 53 + ...ed_control_service_delete_control_async.py | 43 + ...ted_control_service_delete_control_sync.py | 43 + ...rated_control_service_get_control_async.py | 45 + ...erated_control_service_get_control_sync.py | 45 + ...ted_control_service_list_controls_async.py | 46 + ...ated_control_service_list_controls_sync.py | 46 + ...ed_control_service_update_control_async.py | 51 + ...ted_control_service_update_control_sync.py | 51 + ...erated_prediction_service_predict_async.py | 50 + ...nerated_prediction_service_predict_sync.py | 50 + ...ct_service_add_fulfillment_places_async.py | 51 + ...uct_service_add_fulfillment_places_sync.py | 51 + ...uct_service_add_local_inventories_async.py | 49 + ...duct_service_add_local_inventories_sync.py | 49 + ...ed_product_service_create_product_async.py | 50 + ...ted_product_service_create_product_sync.py | 50 + ...ed_product_service_delete_product_async.py | 43 + ...ted_product_service_delete_product_sync.py | 43 + ...rated_product_service_get_product_async.py | 45 + ...erated_product_service_get_product_sync.py | 45 + ...d_product_service_import_products_async.py | 53 + ...ed_product_service_import_products_sync.py | 53 + ...ted_product_service_list_products_async.py | 46 + ...ated_product_service_list_products_sync.py | 46 + ...ed_product_service_purge_products_async.py | 50 + ...ted_product_service_purge_products_sync.py | 50 + ...service_remove_fulfillment_places_async.py | 51 + ..._service_remove_fulfillment_places_sync.py | 51 + ..._service_remove_local_inventories_async.py | 50 + ...t_service_remove_local_inventories_sync.py | 50 + ...ted_product_service_set_inventory_async.py | 52 + ...ated_product_service_set_inventory_sync.py | 52 + ...ed_product_service_update_product_async.py | 48 + ...ted_product_service_update_product_sync.py | 48 + ...a_generated_search_service_search_async.py | 47 + ...ha_generated_search_service_search_sync.py | 47 + ...erving_config_service_add_control_async.py | 46 + ...serving_config_service_add_control_sync.py | 46 + ...fig_service_create_serving_config_async.py | 51 + ...nfig_service_create_serving_config_sync.py | 51 + ...fig_service_delete_serving_config_async.py | 43 + ...nfig_service_delete_serving_config_sync.py | 43 + ...config_service_get_serving_config_async.py | 45 + ..._config_service_get_serving_config_sync.py | 45 + ...nfig_service_list_serving_configs_async.py | 46 + ...onfig_service_list_serving_configs_sync.py | 46 + ...ing_config_service_remove_control_async.py | 46 + ...ving_config_service_remove_control_sync.py | 46 + ...fig_service_update_serving_config_async.py | 49 + ...nfig_service_update_serving_config_sync.py | 49 + ..._event_service_collect_user_event_async.py | 46 + ...r_event_service_collect_user_event_sync.py | 46 + ..._event_service_import_user_events_async.py | 54 + ...r_event_service_import_user_events_sync.py | 54 + ...r_event_service_purge_user_events_async.py | 50 + ...er_event_service_purge_user_events_sync.py | 50 + ..._event_service_rejoin_user_events_async.py | 49 + ...r_event_service_rejoin_user_events_sync.py | 49 + ...er_event_service_write_user_event_async.py | 50 + ...ser_event_service_write_user_event_sync.py | 50 + .../snippet_metadata_retail_v2alpha.json | 7066 +++++++++++++++++ .../scripts/fixup_retail_v2alpha_keywords.py | 219 + owl-bot-staging/v2alpha/setup.py | 59 + owl-bot-staging/v2alpha/tests/__init__.py | 16 + .../v2alpha/tests/unit/__init__.py | 16 + .../v2alpha/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/retail_v2alpha/__init__.py | 16 + .../retail_v2alpha/test_catalog_service.py | 3844 +++++++++ .../retail_v2alpha/test_completion_service.py | 1502 ++++ .../retail_v2alpha/test_control_service.py | 2617 ++++++ .../retail_v2alpha/test_prediction_service.py | 1330 ++++ .../retail_v2alpha/test_product_service.py | 4288 ++++++++++ .../retail_v2alpha/test_search_service.py | 1547 ++++ .../test_serving_config_service.py | 3330 ++++++++ .../retail_v2alpha/test_user_event_service.py | 2039 +++++ owl-bot-staging/v2beta/.coveragerc | 17 + owl-bot-staging/v2beta/.flake8 | 33 + owl-bot-staging/v2beta/MANIFEST.in | 2 + owl-bot-staging/v2beta/README.rst | 49 + owl-bot-staging/v2beta/docs/conf.py | 376 + owl-bot-staging/v2beta/docs/index.rst | 7 + .../docs/retail_v2beta/catalog_service.rst | 10 + .../docs/retail_v2beta/completion_service.rst | 6 + .../docs/retail_v2beta/control_service.rst | 10 + .../docs/retail_v2beta/prediction_service.rst | 6 + .../docs/retail_v2beta/product_service.rst | 10 + .../docs/retail_v2beta/search_service.rst | 10 + .../v2beta/docs/retail_v2beta/services.rst | 13 + .../retail_v2beta/serving_config_service.rst | 10 + .../v2beta/docs/retail_v2beta/types.rst | 7 + .../docs/retail_v2beta/user_event_service.rst | 6 + .../v2beta/google/cloud/retail/__init__.py | 275 + .../v2beta/google/cloud/retail/py.typed | 2 + .../google/cloud/retail_v2beta/__init__.py | 276 + .../cloud/retail_v2beta/gapic_metadata.json | 551 ++ .../google/cloud/retail_v2beta/py.typed | 2 + .../cloud/retail_v2beta/services/__init__.py | 15 + .../services/catalog_service/__init__.py | 22 + .../services/catalog_service/async_client.py | 1350 ++++ .../services/catalog_service/client.py | 1580 ++++ .../services/catalog_service/pagers.py | 140 + .../catalog_service/transports/__init__.py | 33 + .../catalog_service/transports/base.py | 297 + .../catalog_service/transports/grpc.py | 600 ++ .../transports/grpc_asyncio.py | 599 ++ .../services/completion_service/__init__.py | 22 + .../completion_service/async_client.py | 391 + .../services/completion_service/client.py | 593 ++ .../completion_service/transports/__init__.py | 33 + .../completion_service/transports/base.py | 176 + .../completion_service/transports/grpc.py | 325 + .../transports/grpc_asyncio.py | 324 + .../services/control_service/__init__.py | 22 + .../services/control_service/async_client.py | 742 ++ .../services/control_service/client.py | 951 +++ .../services/control_service/pagers.py | 140 + .../control_service/transports/__init__.py | 33 + .../control_service/transports/base.py | 213 + .../control_service/transports/grpc.py | 382 + .../transports/grpc_asyncio.py | 381 + .../services/prediction_service/__init__.py | 22 + .../prediction_service/async_client.py | 279 + .../services/prediction_service/client.py | 480 ++ .../prediction_service/transports/__init__.py | 33 + .../prediction_service/transports/base.py | 154 + .../prediction_service/transports/grpc.py | 264 + .../transports/grpc_asyncio.py | 263 + .../services/product_service/__init__.py | 22 + .../services/product_service/async_client.py | 1692 ++++ .../services/product_service/client.py | 1895 +++++ .../services/product_service/pagers.py | 140 + .../product_service/transports/__init__.py | 33 + .../product_service/transports/base.py | 312 + .../product_service/transports/grpc.py | 680 ++ .../transports/grpc_asyncio.py | 679 ++ .../services/search_service/__init__.py | 22 + .../services/search_service/async_client.py | 303 + .../services/search_service/client.py | 513 ++ .../services/search_service/pagers.py | 139 + .../search_service/transports/__init__.py | 33 + .../search_service/transports/base.py | 154 + .../search_service/transports/grpc.py | 270 + .../search_service/transports/grpc_asyncio.py | 269 + .../serving_config_service/__init__.py | 22 + .../serving_config_service/async_client.py | 954 +++ .../services/serving_config_service/client.py | 1163 +++ .../services/serving_config_service/pagers.py | 140 + .../transports/__init__.py | 33 + .../serving_config_service/transports/base.py | 241 + .../serving_config_service/transports/grpc.py | 440 + .../transports/grpc_asyncio.py | 439 + .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 730 ++ .../services/user_event_service/client.py | 930 +++ .../user_event_service/transports/__init__.py | 33 + .../user_event_service/transports/base.py | 235 + .../user_event_service/transports/grpc.py | 417 + .../transports/grpc_asyncio.py | 416 + .../cloud/retail_v2beta/types/__init__.py | 278 + .../cloud/retail_v2beta/types/catalog.py | 528 ++ .../retail_v2beta/types/catalog_service.py | 453 ++ .../cloud/retail_v2beta/types/common.py | 1178 +++ .../retail_v2beta/types/completion_service.py | 223 + .../cloud/retail_v2beta/types/control.py | 112 + .../retail_v2beta/types/control_service.py | 197 + .../retail_v2beta/types/export_config.py | 134 + .../retail_v2beta/types/import_config.py | 691 ++ .../retail_v2beta/types/prediction_service.py | 263 + .../cloud/retail_v2beta/types/product.py | 705 ++ .../retail_v2beta/types/product_service.py | 844 ++ .../cloud/retail_v2beta/types/promotion.py | 50 + .../cloud/retail_v2beta/types/purge_config.py | 107 + .../retail_v2beta/types/search_service.py | 1074 +++ .../retail_v2beta/types/serving_config.py | 309 + .../types/serving_config_service.py | 234 + .../cloud/retail_v2beta/types/user_event.py | 507 ++ .../retail_v2beta/types/user_event_service.py | 154 + owl-bot-staging/v2beta/mypy.ini | 3 + owl-bot-staging/v2beta/noxfile.py | 180 + ...log_service_add_catalog_attribute_async.py | 49 + ...alog_service_add_catalog_attribute_sync.py | 49 + ...log_service_get_attributes_config_async.py | 45 + ...alog_service_get_attributes_config_sync.py | 45 + ...log_service_get_completion_config_async.py | 45 + ...alog_service_get_completion_config_sync.py | 45 + ...atalog_service_get_default_branch_async.py | 44 + ...catalog_service_get_default_branch_sync.py | 44 + ...ted_catalog_service_list_catalogs_async.py | 46 + ...ated_catalog_service_list_catalogs_sync.py | 46 + ..._service_remove_catalog_attribute_async.py | 46 + ...g_service_remove_catalog_attribute_sync.py | 46 + ...service_replace_catalog_attribute_async.py | 49 + ..._service_replace_catalog_attribute_sync.py | 49 + ...atalog_service_set_default_branch_async.py | 42 + ...catalog_service_set_default_branch_sync.py | 42 + ..._service_update_attributes_config_async.py | 48 + ...g_service_update_attributes_config_sync.py | 48 + ...ed_catalog_service_update_catalog_async.py | 49 + ...ted_catalog_service_update_catalog_sync.py | 49 + ..._service_update_completion_config_async.py | 48 + ...g_service_update_completion_config_sync.py | 48 + ...completion_service_complete_query_async.py | 46 + ..._completion_service_complete_query_sync.py | 46 + ...on_service_import_completion_data_async.py | 54 + ...ion_service_import_completion_data_sync.py | 54 + ...ed_control_service_create_control_async.py | 52 + ...ted_control_service_create_control_sync.py | 52 + ...ed_control_service_delete_control_async.py | 43 + ...ted_control_service_delete_control_sync.py | 43 + ...rated_control_service_get_control_async.py | 45 + ...erated_control_service_get_control_sync.py | 45 + ...ted_control_service_list_controls_async.py | 46 + ...ated_control_service_list_controls_sync.py | 46 + ...ed_control_service_update_control_async.py | 50 + ...ted_control_service_update_control_sync.py | 50 + ...erated_prediction_service_predict_async.py | 50 + ...nerated_prediction_service_predict_sync.py | 50 + ...ct_service_add_fulfillment_places_async.py | 51 + ...uct_service_add_fulfillment_places_sync.py | 51 + ...uct_service_add_local_inventories_async.py | 49 + ...duct_service_add_local_inventories_sync.py | 49 + ...ed_product_service_create_product_async.py | 50 + ...ted_product_service_create_product_sync.py | 50 + ...ed_product_service_delete_product_async.py | 43 + ...ted_product_service_delete_product_sync.py | 43 + ...rated_product_service_get_product_async.py | 45 + ...erated_product_service_get_product_sync.py | 45 + ...d_product_service_import_products_async.py | 53 + ...ed_product_service_import_products_sync.py | 53 + ...ted_product_service_list_products_async.py | 46 + ...ated_product_service_list_products_sync.py | 46 + ...service_remove_fulfillment_places_async.py | 51 + ..._service_remove_fulfillment_places_sync.py | 51 + ..._service_remove_local_inventories_async.py | 50 + ...t_service_remove_local_inventories_sync.py | 50 + ...ted_product_service_set_inventory_async.py | 52 + ...ated_product_service_set_inventory_sync.py | 52 + ...ed_product_service_update_product_async.py | 48 + ...ted_product_service_update_product_sync.py | 48 + ...a_generated_search_service_search_async.py | 47 + ...ta_generated_search_service_search_sync.py | 47 + ...erving_config_service_add_control_async.py | 46 + ...serving_config_service_add_control_sync.py | 46 + ...fig_service_create_serving_config_async.py | 51 + ...nfig_service_create_serving_config_sync.py | 51 + ...fig_service_delete_serving_config_async.py | 43 + ...nfig_service_delete_serving_config_sync.py | 43 + ...config_service_get_serving_config_async.py | 45 + ..._config_service_get_serving_config_sync.py | 45 + ...nfig_service_list_serving_configs_async.py | 46 + ...onfig_service_list_serving_configs_sync.py | 46 + ...ing_config_service_remove_control_async.py | 46 + ...ving_config_service_remove_control_sync.py | 46 + ...fig_service_update_serving_config_async.py | 49 + ...nfig_service_update_serving_config_sync.py | 49 + ..._event_service_collect_user_event_async.py | 46 + ...r_event_service_collect_user_event_sync.py | 46 + ..._event_service_import_user_events_async.py | 54 + ...r_event_service_import_user_events_sync.py | 54 + ...r_event_service_purge_user_events_async.py | 50 + ...er_event_service_purge_user_events_sync.py | 50 + ..._event_service_rejoin_user_events_async.py | 49 + ...r_event_service_rejoin_user_events_sync.py | 49 + ...er_event_service_write_user_event_async.py | 50 + ...ser_event_service_write_user_event_sync.py | 50 + .../snippet_metadata_retail_v2beta.json | 6913 ++++++++++++++++ .../scripts/fixup_retail_v2beta_keywords.py | 218 + owl-bot-staging/v2beta/setup.py | 59 + owl-bot-staging/v2beta/tests/__init__.py | 16 + owl-bot-staging/v2beta/tests/unit/__init__.py | 16 + .../v2beta/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/retail_v2beta/__init__.py | 16 + .../retail_v2beta/test_catalog_service.py | 3844 +++++++++ .../retail_v2beta/test_completion_service.py | 1502 ++++ .../retail_v2beta/test_control_service.py | 2605 ++++++ .../retail_v2beta/test_prediction_service.py | 1330 ++++ .../retail_v2beta/test_product_service.py | 4136 ++++++++++ .../retail_v2beta/test_search_service.py | 1547 ++++ .../test_serving_config_service.py | 3330 ++++++++ .../retail_v2beta/test_user_event_service.py | 2039 +++++ 554 files changed, 175515 insertions(+) create mode 100644 owl-bot-staging/v2/.coveragerc create mode 100644 owl-bot-staging/v2/.flake8 create mode 100644 owl-bot-staging/v2/MANIFEST.in create mode 100644 owl-bot-staging/v2/README.rst create mode 100644 owl-bot-staging/v2/docs/conf.py create mode 100644 owl-bot-staging/v2/docs/index.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/catalog_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/completion_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/prediction_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/product_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/search_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/services.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/types.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/user_event_service.rst create mode 100644 owl-bot-staging/v2/google/cloud/retail/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/common.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/product.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py create mode 100644 owl-bot-staging/v2/mypy.ini create mode 100644 owl-bot-staging/v2/noxfile.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json create mode 100644 owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py create mode 100644 owl-bot-staging/v2/setup.py create mode 100644 owl-bot-staging/v2/tests/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py create mode 100644 owl-bot-staging/v2alpha/.coveragerc create mode 100644 owl-bot-staging/v2alpha/.flake8 create mode 100644 owl-bot-staging/v2alpha/MANIFEST.in create mode 100644 owl-bot-staging/v2alpha/README.rst create mode 100644 owl-bot-staging/v2alpha/docs/conf.py create mode 100644 owl-bot-staging/v2alpha/docs/index.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail/py.typed create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py create mode 100644 owl-bot-staging/v2alpha/mypy.ini create mode 100644 owl-bot-staging/v2alpha/noxfile.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json create mode 100644 owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py create mode 100644 owl-bot-staging/v2alpha/setup.py create mode 100644 owl-bot-staging/v2alpha/tests/__init__.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py create mode 100644 owl-bot-staging/v2beta/.coveragerc create mode 100644 owl-bot-staging/v2beta/.flake8 create mode 100644 owl-bot-staging/v2beta/MANIFEST.in create mode 100644 owl-bot-staging/v2beta/README.rst create mode 100644 owl-bot-staging/v2beta/docs/conf.py create mode 100644 owl-bot-staging/v2beta/docs/index.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/services.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/types.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst create mode 100644 owl-bot-staging/v2beta/google/cloud/retail/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail/py.typed create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py create mode 100644 owl-bot-staging/v2beta/mypy.ini create mode 100644 owl-bot-staging/v2beta/noxfile.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json create mode 100644 owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py create mode 100644 owl-bot-staging/v2beta/setup.py create mode 100644 owl-bot-staging/v2beta/tests/__init__.py create mode 100644 owl-bot-staging/v2beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc new file mode 100644 index 00000000..a8b114f0 --- /dev/null +++ b/owl-bot-staging/v2/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/retail/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2/.flake8 b/owl-bot-staging/v2/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v2/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in new file mode 100644 index 00000000..985b915c --- /dev/null +++ b/owl-bot-staging/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/retail *.py +recursive-include google/cloud/retail_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst new file mode 100644 index 00000000..cb039760 --- /dev/null +++ b/owl-bot-staging/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Retail API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Retail API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py new file mode 100644 index 00000000..5be9eb4b --- /dev/null +++ b/owl-bot-staging/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-retail documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-retail" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-retail-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-retail.tex", + u"google-cloud-retail Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-retail", + u"Google Cloud Retail Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-retail", + u"google-cloud-retail Documentation", + author, + "google-cloud-retail", + "GAPIC library for Google Cloud Retail API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst new file mode 100644 index 00000000..c70f61bc --- /dev/null +++ b/owl-bot-staging/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + retail_v2/services + retail_v2/types diff --git a/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst b/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst new file mode 100644 index 00000000..5b7227d9 --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst @@ -0,0 +1,10 @@ +CatalogService +-------------------------------- + +.. automodule:: google.cloud.retail_v2.services.catalog_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2.services.catalog_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/completion_service.rst b/owl-bot-staging/v2/docs/retail_v2/completion_service.rst new file mode 100644 index 00000000..551f89ed --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/completion_service.rst @@ -0,0 +1,6 @@ +CompletionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2.services.completion_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst b/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst new file mode 100644 index 00000000..12ffb6ee --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst @@ -0,0 +1,6 @@ +PredictionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2.services.prediction_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/product_service.rst b/owl-bot-staging/v2/docs/retail_v2/product_service.rst new file mode 100644 index 00000000..0b8fa911 --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/product_service.rst @@ -0,0 +1,10 @@ +ProductService +-------------------------------- + +.. automodule:: google.cloud.retail_v2.services.product_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2.services.product_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/search_service.rst b/owl-bot-staging/v2/docs/retail_v2/search_service.rst new file mode 100644 index 00000000..af72819d --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/search_service.rst @@ -0,0 +1,10 @@ +SearchService +------------------------------- + +.. automodule:: google.cloud.retail_v2.services.search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2.services.search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/services.rst b/owl-bot-staging/v2/docs/retail_v2/services.rst new file mode 100644 index 00000000..f86138d7 --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/services.rst @@ -0,0 +1,11 @@ +Services for Google Cloud Retail v2 API +======================================= +.. toctree:: + :maxdepth: 2 + + catalog_service + completion_service + prediction_service + product_service + search_service + user_event_service diff --git a/owl-bot-staging/v2/docs/retail_v2/types.rst b/owl-bot-staging/v2/docs/retail_v2/types.rst new file mode 100644 index 00000000..54951beb --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Retail v2 API +==================================== + +.. automodule:: google.cloud.retail_v2.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst b/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst new file mode 100644 index 00000000..00e214a9 --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst @@ -0,0 +1,6 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.retail_v2.services.user_event_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/google/cloud/retail/__init__.py b/owl-bot-staging/v2/google/cloud/retail/__init__.py new file mode 100644 index 00000000..0d70ed64 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail/__init__.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.retail_v2.services.catalog_service.client import CatalogServiceClient +from google.cloud.retail_v2.services.catalog_service.async_client import CatalogServiceAsyncClient +from google.cloud.retail_v2.services.completion_service.client import CompletionServiceClient +from google.cloud.retail_v2.services.completion_service.async_client import CompletionServiceAsyncClient +from google.cloud.retail_v2.services.prediction_service.client import PredictionServiceClient +from google.cloud.retail_v2.services.prediction_service.async_client import PredictionServiceAsyncClient +from google.cloud.retail_v2.services.product_service.client import ProductServiceClient +from google.cloud.retail_v2.services.product_service.async_client import ProductServiceAsyncClient +from google.cloud.retail_v2.services.search_service.client import SearchServiceClient +from google.cloud.retail_v2.services.search_service.async_client import SearchServiceAsyncClient +from google.cloud.retail_v2.services.user_event_service.client import UserEventServiceClient +from google.cloud.retail_v2.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.retail_v2.types.catalog import Catalog +from google.cloud.retail_v2.types.catalog import ProductLevelConfig +from google.cloud.retail_v2.types.catalog_service import GetDefaultBranchRequest +from google.cloud.retail_v2.types.catalog_service import GetDefaultBranchResponse +from google.cloud.retail_v2.types.catalog_service import ListCatalogsRequest +from google.cloud.retail_v2.types.catalog_service import ListCatalogsResponse +from google.cloud.retail_v2.types.catalog_service import SetDefaultBranchRequest +from google.cloud.retail_v2.types.catalog_service import UpdateCatalogRequest +from google.cloud.retail_v2.types.common import Audience +from google.cloud.retail_v2.types.common import ColorInfo +from google.cloud.retail_v2.types.common import CustomAttribute +from google.cloud.retail_v2.types.common import FulfillmentInfo +from google.cloud.retail_v2.types.common import Image +from google.cloud.retail_v2.types.common import Interval +from google.cloud.retail_v2.types.common import LocalInventory +from google.cloud.retail_v2.types.common import PriceInfo +from google.cloud.retail_v2.types.common import Rating +from google.cloud.retail_v2.types.common import UserInfo +from google.cloud.retail_v2.types.completion_service import CompleteQueryRequest +from google.cloud.retail_v2.types.completion_service import CompleteQueryResponse +from google.cloud.retail_v2.types.import_config import BigQuerySource +from google.cloud.retail_v2.types.import_config import CompletionDataInputConfig +from google.cloud.retail_v2.types.import_config import GcsSource +from google.cloud.retail_v2.types.import_config import ImportCompletionDataRequest +from google.cloud.retail_v2.types.import_config import ImportCompletionDataResponse +from google.cloud.retail_v2.types.import_config import ImportErrorsConfig +from google.cloud.retail_v2.types.import_config import ImportMetadata +from google.cloud.retail_v2.types.import_config import ImportProductsRequest +from google.cloud.retail_v2.types.import_config import ImportProductsResponse +from google.cloud.retail_v2.types.import_config import ImportUserEventsRequest +from google.cloud.retail_v2.types.import_config import ImportUserEventsResponse +from google.cloud.retail_v2.types.import_config import ProductInlineSource +from google.cloud.retail_v2.types.import_config import ProductInputConfig +from google.cloud.retail_v2.types.import_config import UserEventImportSummary +from google.cloud.retail_v2.types.import_config import UserEventInlineSource +from google.cloud.retail_v2.types.import_config import UserEventInputConfig +from google.cloud.retail_v2.types.prediction_service import PredictRequest +from google.cloud.retail_v2.types.prediction_service import PredictResponse +from google.cloud.retail_v2.types.product import Product +from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesMetadata +from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesRequest +from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesResponse +from google.cloud.retail_v2.types.product_service import AddLocalInventoriesMetadata +from google.cloud.retail_v2.types.product_service import AddLocalInventoriesRequest +from google.cloud.retail_v2.types.product_service import AddLocalInventoriesResponse +from google.cloud.retail_v2.types.product_service import CreateProductRequest +from google.cloud.retail_v2.types.product_service import DeleteProductRequest +from google.cloud.retail_v2.types.product_service import GetProductRequest +from google.cloud.retail_v2.types.product_service import ListProductsRequest +from google.cloud.retail_v2.types.product_service import ListProductsResponse +from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesMetadata +from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesRequest +from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesResponse +from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesMetadata +from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesRequest +from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesResponse +from google.cloud.retail_v2.types.product_service import SetInventoryMetadata +from google.cloud.retail_v2.types.product_service import SetInventoryRequest +from google.cloud.retail_v2.types.product_service import SetInventoryResponse +from google.cloud.retail_v2.types.product_service import UpdateProductRequest +from google.cloud.retail_v2.types.promotion import Promotion +from google.cloud.retail_v2.types.purge_config import PurgeMetadata +from google.cloud.retail_v2.types.purge_config import PurgeUserEventsRequest +from google.cloud.retail_v2.types.purge_config import PurgeUserEventsResponse +from google.cloud.retail_v2.types.search_service import SearchRequest +from google.cloud.retail_v2.types.search_service import SearchResponse +from google.cloud.retail_v2.types.user_event import CompletionDetail +from google.cloud.retail_v2.types.user_event import ProductDetail +from google.cloud.retail_v2.types.user_event import PurchaseTransaction +from google.cloud.retail_v2.types.user_event import UserEvent +from google.cloud.retail_v2.types.user_event_service import CollectUserEventRequest +from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsMetadata +from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsRequest +from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsResponse +from google.cloud.retail_v2.types.user_event_service import WriteUserEventRequest + +__all__ = ('CatalogServiceClient', + 'CatalogServiceAsyncClient', + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', + 'ProductServiceClient', + 'ProductServiceAsyncClient', + 'SearchServiceClient', + 'SearchServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'Catalog', + 'ProductLevelConfig', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'SetDefaultBranchRequest', + 'UpdateCatalogRequest', + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2/google/cloud/retail/py.typed b/owl-bot-staging/v2/google/cloud/retail/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py new file mode 100644 index 00000000..c7f56a8d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.catalog_service import CatalogServiceClient +from .services.catalog_service import CatalogServiceAsyncClient +from .services.completion_service import CompletionServiceClient +from .services.completion_service import CompletionServiceAsyncClient +from .services.prediction_service import PredictionServiceClient +from .services.prediction_service import PredictionServiceAsyncClient +from .services.product_service import ProductServiceClient +from .services.product_service import ProductServiceAsyncClient +from .services.search_service import SearchServiceClient +from .services.search_service import SearchServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.catalog import Catalog +from .types.catalog import ProductLevelConfig +from .types.catalog_service import GetDefaultBranchRequest +from .types.catalog_service import GetDefaultBranchResponse +from .types.catalog_service import ListCatalogsRequest +from .types.catalog_service import ListCatalogsResponse +from .types.catalog_service import SetDefaultBranchRequest +from .types.catalog_service import UpdateCatalogRequest +from .types.common import Audience +from .types.common import ColorInfo +from .types.common import CustomAttribute +from .types.common import FulfillmentInfo +from .types.common import Image +from .types.common import Interval +from .types.common import LocalInventory +from .types.common import PriceInfo +from .types.common import Rating +from .types.common import UserInfo +from .types.completion_service import CompleteQueryRequest +from .types.completion_service import CompleteQueryResponse +from .types.import_config import BigQuerySource +from .types.import_config import CompletionDataInputConfig +from .types.import_config import GcsSource +from .types.import_config import ImportCompletionDataRequest +from .types.import_config import ImportCompletionDataResponse +from .types.import_config import ImportErrorsConfig +from .types.import_config import ImportMetadata +from .types.import_config import ImportProductsRequest +from .types.import_config import ImportProductsResponse +from .types.import_config import ImportUserEventsRequest +from .types.import_config import ImportUserEventsResponse +from .types.import_config import ProductInlineSource +from .types.import_config import ProductInputConfig +from .types.import_config import UserEventImportSummary +from .types.import_config import UserEventInlineSource +from .types.import_config import UserEventInputConfig +from .types.prediction_service import PredictRequest +from .types.prediction_service import PredictResponse +from .types.product import Product +from .types.product_service import AddFulfillmentPlacesMetadata +from .types.product_service import AddFulfillmentPlacesRequest +from .types.product_service import AddFulfillmentPlacesResponse +from .types.product_service import AddLocalInventoriesMetadata +from .types.product_service import AddLocalInventoriesRequest +from .types.product_service import AddLocalInventoriesResponse +from .types.product_service import CreateProductRequest +from .types.product_service import DeleteProductRequest +from .types.product_service import GetProductRequest +from .types.product_service import ListProductsRequest +from .types.product_service import ListProductsResponse +from .types.product_service import RemoveFulfillmentPlacesMetadata +from .types.product_service import RemoveFulfillmentPlacesRequest +from .types.product_service import RemoveFulfillmentPlacesResponse +from .types.product_service import RemoveLocalInventoriesMetadata +from .types.product_service import RemoveLocalInventoriesRequest +from .types.product_service import RemoveLocalInventoriesResponse +from .types.product_service import SetInventoryMetadata +from .types.product_service import SetInventoryRequest +from .types.product_service import SetInventoryResponse +from .types.product_service import UpdateProductRequest +from .types.promotion import Promotion +from .types.purge_config import PurgeMetadata +from .types.purge_config import PurgeUserEventsRequest +from .types.purge_config import PurgeUserEventsResponse +from .types.search_service import SearchRequest +from .types.search_service import SearchResponse +from .types.user_event import CompletionDetail +from .types.user_event import ProductDetail +from .types.user_event import PurchaseTransaction +from .types.user_event import UserEvent +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import RejoinUserEventsMetadata +from .types.user_event_service import RejoinUserEventsRequest +from .types.user_event_service import RejoinUserEventsResponse +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CatalogServiceAsyncClient', + 'CompletionServiceAsyncClient', + 'PredictionServiceAsyncClient', + 'ProductServiceAsyncClient', + 'SearchServiceAsyncClient', + 'UserEventServiceAsyncClient', +'AddFulfillmentPlacesMetadata', +'AddFulfillmentPlacesRequest', +'AddFulfillmentPlacesResponse', +'AddLocalInventoriesMetadata', +'AddLocalInventoriesRequest', +'AddLocalInventoriesResponse', +'Audience', +'BigQuerySource', +'Catalog', +'CatalogServiceClient', +'CollectUserEventRequest', +'ColorInfo', +'CompleteQueryRequest', +'CompleteQueryResponse', +'CompletionDataInputConfig', +'CompletionDetail', +'CompletionServiceClient', +'CreateProductRequest', +'CustomAttribute', +'DeleteProductRequest', +'FulfillmentInfo', +'GcsSource', +'GetDefaultBranchRequest', +'GetDefaultBranchResponse', +'GetProductRequest', +'Image', +'ImportCompletionDataRequest', +'ImportCompletionDataResponse', +'ImportErrorsConfig', +'ImportMetadata', +'ImportProductsRequest', +'ImportProductsResponse', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'Interval', +'ListCatalogsRequest', +'ListCatalogsResponse', +'ListProductsRequest', +'ListProductsResponse', +'LocalInventory', +'PredictRequest', +'PredictResponse', +'PredictionServiceClient', +'PriceInfo', +'Product', +'ProductDetail', +'ProductInlineSource', +'ProductInputConfig', +'ProductLevelConfig', +'ProductServiceClient', +'Promotion', +'PurchaseTransaction', +'PurgeMetadata', +'PurgeUserEventsRequest', +'PurgeUserEventsResponse', +'Rating', +'RejoinUserEventsMetadata', +'RejoinUserEventsRequest', +'RejoinUserEventsResponse', +'RemoveFulfillmentPlacesMetadata', +'RemoveFulfillmentPlacesRequest', +'RemoveFulfillmentPlacesResponse', +'RemoveLocalInventoriesMetadata', +'RemoveLocalInventoriesRequest', +'RemoveLocalInventoriesResponse', +'SearchRequest', +'SearchResponse', +'SearchServiceClient', +'SetDefaultBranchRequest', +'SetInventoryMetadata', +'SetInventoryRequest', +'SetInventoryResponse', +'UpdateCatalogRequest', +'UpdateProductRequest', +'UserEvent', +'UserEventImportSummary', +'UserEventInlineSource', +'UserEventInputConfig', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json new file mode 100644 index 00000000..9e04aec8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json @@ -0,0 +1,333 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.retail_v2", + "protoPackage": "google.cloud.retail.v2", + "schema": "1.0", + "services": { + "CatalogService": { + "clients": { + "grpc": { + "libraryClient": "CatalogServiceClient", + "rpcs": { + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CatalogServiceAsyncClient", + "rpcs": { + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + } + } + } + } + }, + "CompletionService": { + "clients": { + "grpc": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CompletionServiceAsyncClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + } + } + }, + "PredictionService": { + "clients": { + "grpc": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionServiceAsyncClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + } + } + }, + "ProductService": { + "clients": { + "grpc": { + "libraryClient": "ProductServiceClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductServiceAsyncClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + } + } + }, + "SearchService": { + "clients": { + "grpc": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SearchServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/py.typed b/owl-bot-staging/v2/google/cloud/retail_v2/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py new file mode 100644 index 00000000..d276b897 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CatalogServiceClient +from .async_client import CatalogServiceAsyncClient + +__all__ = ( + 'CatalogServiceClient', + 'CatalogServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py new file mode 100644 index 00000000..b0a1b99e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py @@ -0,0 +1,653 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.services.catalog_service import pagers +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport +from .client import CatalogServiceClient + + +class CatalogServiceAsyncClient: + """Service for managing catalog configuration.""" + + _client: CatalogServiceClient + + DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(CatalogServiceClient.branch_path) + parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) + catalog_path = staticmethod(CatalogServiceClient.catalog_path) + parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) + common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CatalogServiceClient.common_project_path) + parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) + common_location_path = staticmethod(CatalogServiceClient.common_location_path) + parse_common_location_path = staticmethod(CatalogServiceClient.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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CatalogServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsAsyncPager: + r"""Lists all the [Catalog][google.cloud.retail.v2.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_list_catalogs(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + parent (:class:`str`): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2.Catalog]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.retail_v2.services.catalog_service.pagers.ListCatalogsAsyncPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.ListCatalogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_catalogs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCatalogsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_update_catalog(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] + method. + catalog (:class:`google.cloud.retail_v2.types.Catalog`): + Required. The [Catalog][google.cloud.retail.v2.Catalog] + to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2.Catalog], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_catalog, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_set_default_branch(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (:class:`str`): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.SetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_get_default_branch(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (:class:`str`): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # 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_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py new file mode 100644 index 00000000..dab9ff8c --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py @@ -0,0 +1,862 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.services.catalog_service import pagers +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CatalogServiceGrpcTransport +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +class CatalogServiceClientMeta(type): + """Metaclass for the CatalogService 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[CatalogServiceTransport]] + _transport_registry["grpc"] = CatalogServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CatalogServiceTransport]: + """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): + """Service for managing catalog configuration.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CatalogServiceClient: 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: + CatalogServiceClient: 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) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CatalogServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CatalogServiceTransport): + # transport is a CatalogServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsPager: + r"""Lists all the [Catalog][google.cloud.retail.v2.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_list_catalogs(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2.Catalog]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.retail_v2.services.catalog_service.pagers.ListCatalogsPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ListCatalogsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ListCatalogsRequest): + request = catalog_service.ListCatalogsRequest(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_catalogs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCatalogsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_update_catalog(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] + method. + catalog (google.cloud.retail_v2.types.Catalog): + Required. The [Catalog][google.cloud.retail.v2.Catalog] + to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2.Catalog], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCatalogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCatalogRequest): + request = catalog_service.UpdateCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + 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_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_set_default_branch(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.SetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.SetDefaultBranchRequest): + request = catalog_service.SetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_get_default_branch(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetDefaultBranchRequest): + request = catalog_service.GetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py new file mode 100644 index 00000000..11dd0677 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog_service + + +class ListCatalogsPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.ListCatalogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.ListCatalogsResponse` + 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[..., catalog_service.ListCatalogsResponse], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + for page in self.pages: + yield from page.catalogs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCatalogsAsyncPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.ListCatalogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.ListCatalogsResponse` + 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[catalog_service.ListCatalogsResponse]], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + async def async_generator(): + async for page in self.pages: + for response in page.catalogs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py new file mode 100644 index 00000000..0cffa336 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 CatalogServiceTransport +from .grpc import CatalogServiceGrpcTransport +from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] +_transport_registry['grpc'] = CatalogServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport + +__all__ = ( + 'CatalogServiceTransport', + 'CatalogServiceGrpcTransport', + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py new file mode 100644 index 00000000..661247c1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py @@ -0,0 +1,198 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CatalogServiceTransport(abc.ABC): + """Abstract transport class for CatalogService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_catalogs: gapic_v1.method.wrap_method( + self.list_catalogs, + default_timeout=None, + client_info=client_info, + ), + self.update_catalog: gapic_v1.method.wrap_method( + self.update_catalog, + default_timeout=None, + client_info=client_info, + ), + self.set_default_branch: gapic_v1.method.wrap_method( + self.set_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_default_branch: gapic_v1.method.wrap_method( + self.get_default_branch, + 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Union[ + catalog_service.ListCatalogsResponse, + Awaitable[catalog_service.ListCatalogsResponse] + ]]: + raise NotImplementedError() + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Union[ + gcr_catalog.Catalog, + Awaitable[gcr_catalog.Catalog] + ]]: + raise NotImplementedError() + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Union[ + catalog_service.GetDefaultBranchResponse, + Awaitable[catalog_service.GetDefaultBranchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CatalogServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py new file mode 100644 index 00000000..17492b4a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO + + +class CatalogServiceGrpcTransport(CatalogServiceTransport): + """gRPC backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + catalog_service.ListCatalogsResponse]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + ~.ListCatalogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + gcr_catalog.Catalog]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + ~.Catalog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + empty_pb2.Empty]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + ~.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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + catalog_service.GetDefaultBranchResponse]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + ~.GetDefaultBranchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CatalogServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..dfc3cd7b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py @@ -0,0 +1,380 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CatalogServiceGrpcTransport + + +class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): + """gRPC AsyncIO backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Awaitable[catalog_service.ListCatalogsResponse]]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + Awaitable[~.ListCatalogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Awaitable[gcr_catalog.Catalog]]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + Awaitable[~.Catalog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + 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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Awaitable[catalog_service.GetDefaultBranchResponse]]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + Awaitable[~.GetDefaultBranchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py new file mode 100644 index 00000000..b8af95bd --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CompletionServiceClient +from .async_client import CompletionServiceAsyncClient + +__all__ = ( + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py new file mode 100644 index 00000000..9e5d6432 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .client import CompletionServiceClient + + +class CompletionServiceAsyncClient: + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: CompletionServiceClient + + DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(CompletionServiceClient.catalog_path) + parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) + common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CompletionServiceClient.common_project_path) + parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) + common_location_path = staticmethod(CompletionServiceClient.common_location_path) + parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CompletionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_complete_query(): + # Create a client + client = retail_v2.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_query, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_import_completion_data(): + # Create a client + client = retail_v2.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. + 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. + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_completion_data, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py new file mode 100644 index 00000000..ca5bb55d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CompletionServiceGrpcTransport +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +class CompletionServiceClientMeta(type): + """Metaclass for the CompletionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] + _transport_registry["grpc"] = CompletionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CompletionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CompletionServiceClient(metaclass=CompletionServiceClientMeta): + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CompletionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CompletionServiceTransport): + # transport is a CompletionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_complete_query(): + # Create a client + client = retail_v2.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a completion_service.CompleteQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, completion_service.CompleteQueryRequest): + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_import_completion_data(): + # Create a client + client = retail_v2.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. + 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. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportCompletionDataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportCompletionDataRequest): + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_completion_data] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py new file mode 100644 index 00000000..a0c9542f --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CompletionServiceTransport +from .grpc import CompletionServiceGrpcTransport +from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] +_transport_registry['grpc'] = CompletionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport + +__all__ = ( + 'CompletionServiceTransport', + 'CompletionServiceGrpcTransport', + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py new file mode 100644 index 00000000..7b2cb516 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CompletionServiceTransport(abc.ABC): + """Abstract transport class for CompletionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.complete_query: gapic_v1.method.wrap_method( + self.complete_query, + default_timeout=None, + client_info=client_info, + ), + self.import_completion_data: gapic_v1.method.wrap_method( + self.import_completion_data, + 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Union[ + completion_service.CompleteQueryResponse, + Awaitable[completion_service.CompleteQueryResponse] + ]]: + raise NotImplementedError() + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CompletionServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py new file mode 100644 index 00000000..44cb929b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py @@ -0,0 +1,325 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO + + +class CompletionServiceGrpcTransport(CompletionServiceTransport): + """gRPC backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + ~.CompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + operations_pb2.Operation]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CompletionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..f7131541 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py @@ -0,0 +1,324 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CompletionServiceGrpcTransport + + +class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): + """gRPC AsyncIO backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Awaitable[completion_service.CompleteQueryResponse]]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + Awaitable[~.CompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + 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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py new file mode 100644 index 00000000..7c079c80 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import PredictionServiceClient +from .async_client import PredictionServiceAsyncClient + +__all__ = ( + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py new file mode 100644 index 00000000..ae9f9c86 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport +from .client import PredictionServiceClient + + +class PredictionServiceAsyncClient: + """Service for making recommendation prediction.""" + + _client: PredictionServiceClient + + DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT + + product_path = staticmethod(PredictionServiceClient.product_path) + parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) + common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(PredictionServiceClient.common_project_path) + parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) + common_location_path = staticmethod(PredictionServiceClient.common_location_path) + parse_common_location_path = staticmethod(PredictionServiceClient.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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PredictionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_predict(): + # Create a client + client = retail_v2.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + request = prediction_service.PredictRequest(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.predict, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py new file mode 100644 index 00000000..67a94f53 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py @@ -0,0 +1,480 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionServiceGrpcTransport +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +class PredictionServiceClientMeta(type): + """Metaclass for the PredictionService 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[PredictionServiceTransport]] + _transport_registry["grpc"] = PredictionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PredictionServiceTransport]: + """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): + """Service for making recommendation prediction.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PredictionServiceClient: 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: + PredictionServiceClient: 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) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PredictionServiceTransport): + # transport is a PredictionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_predict(): + # Create a client + client = retail_v2.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a prediction_service.PredictRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_service.PredictRequest): + request = prediction_service.PredictRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.predict] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py new file mode 100644 index 00000000..bb65c664 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PredictionServiceTransport +from .grpc import PredictionServiceGrpcTransport +from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] +_transport_registry['grpc'] = PredictionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport + +__all__ = ( + 'PredictionServiceTransport', + 'PredictionServiceGrpcTransport', + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py new file mode 100644 index 00000000..f3b77c06 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import prediction_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PredictionServiceTransport(abc.ABC): + """Abstract transport class for PredictionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.predict: gapic_v1.method.wrap_method( + self.predict, + 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + Union[ + prediction_service.PredictResponse, + Awaitable[prediction_service.PredictResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'PredictionServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py new file mode 100644 index 00000000..0e86800c --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py @@ -0,0 +1,264 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO + + +class PredictionServiceGrpcTransport(PredictionServiceTransport): + """gRPC backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + prediction_service.PredictResponse]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + ~.PredictResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'PredictionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..472e079a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import PredictionServiceGrpcTransport + + +class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): + """gRPC AsyncIO backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + Awaitable[prediction_service.PredictResponse]]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + Awaitable[~.PredictResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py new file mode 100644 index 00000000..0fa6330a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ProductServiceClient +from .async_client import ProductServiceAsyncClient + +__all__ = ( + 'ProductServiceClient', + 'ProductServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py new file mode 100644 index 00000000..db29be72 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py @@ -0,0 +1,1701 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.services.product_service import pagers +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.cloud.retail_v2.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport +from .client import ProductServiceClient + + +class ProductServiceAsyncClient: + """Service for ingesting [Product][google.cloud.retail.v2.Product] + information of the customer's website. + """ + + _client: ProductServiceClient + + DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(ProductServiceClient.branch_path) + parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) + product_path = staticmethod(ProductServiceClient.product_path) + parse_product_path = staticmethod(ProductServiceClient.parse_product_path) + common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProductServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProductServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProductServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProductServiceClient.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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ProductServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ProductServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_create_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`google.cloud.retail_v2.types.Product`): + Required. The [Product][google.cloud.retail.v2.Product] + to create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + Required. The ID to use for the + [Product][google.cloud.retail.v2.Product], which will + become the final component of the + [Product.name][google.cloud.retail.v2.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2.Product]s with the same + [parent][google.cloud.retail.v2.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_get_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested + [Product][google.cloud.retail.v2.Product] 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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Gets a list of [Product][google.cloud.retail.v2.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_list_products(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2.Product]s under this + branch, regardless of whether or not this branch exists, + a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.services.product_service.pagers.ListProductsAsyncPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_update_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (:class:`google.cloud.retail_v2.types.Product`): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2.Product] to update. The + immutable and output only fields are NOT supported. If + not set, all supported fields (the fields that are + neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + The attribute key can be updated by setting the mask + path as "attributes.${key_name}". If a key name is + present in the mask but not in the patching product from + the request, this key will be deleted after the update. + + 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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_delete_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2.Product] to delete + can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] with more than + one + [variants][google.cloud.retail.v2.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2.Product]s. + + Request processing may be synchronous. Non-existing items are + created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2.Product]s to be successfully + updated. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_import_products(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2.Product] while respecting the + last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_set_inventory(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2.Product() + inventory.title = "title_value" + + request = retail_v2.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (:class:`google.cloud.retail_v2.types.Product`): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product] named in + [Product.name][google.cloud.retail.v2.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.SetInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_inventory, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + async def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places, + while respecting the last update timestamps of each inventory + field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_add_local_inventories(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.AddLocalInventoriesResponse` Response of the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + API. Currently empty because there is no meaningful + response populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places at + a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_remove_local_inventories(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py new file mode 100644 index 00000000..dc6ce5c9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py @@ -0,0 +1,1904 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.services.product_service import pagers +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.cloud.retail_v2.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductServiceGrpcTransport +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +class ProductServiceClientMeta(type): + """Metaclass for the ProductService 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[ProductServiceTransport]] + _transport_registry["grpc"] = ProductServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ProductServiceTransport]: + """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 ProductServiceClient(metaclass=ProductServiceClientMeta): + """Service for ingesting [Product][google.cloud.retail.v2.Product] + information of the customer's website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProductServiceClient: 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: + ProductServiceClient: 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) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ProductServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProductServiceTransport): + # transport is a ProductServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_create_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (google.cloud.retail_v2.types.Product): + Required. The [Product][google.cloud.retail.v2.Product] + to create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2.Product], which will + become the final component of the + [Product.name][google.cloud.retail.v2.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2.Product]s with the same + [parent][google.cloud.retail.v2.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.CreateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.CreateProductRequest): + request = product_service.CreateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_get_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested + [Product][google.cloud.retail.v2.Product] 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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.GetProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.GetProductRequest): + request = product_service.GetProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Gets a list of [Product][google.cloud.retail.v2.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_list_products(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2.Product]s under this + branch, regardless of whether or not this branch exists, + a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.services.product_service.pagers.ListProductsPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.ListProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.ListProductsRequest): + request = product_service.ListProductsRequest(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_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_update_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (google.cloud.retail_v2.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2.Product] to update. The + immutable and output only fields are NOT supported. If + not set, all supported fields (the fields that are + neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + The attribute key can be updated by setting the mask + path as "attributes.${key_name}". If a key name is + present in the mask but not in the patching product from + the request, this key will be deleted after the update. + + 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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.UpdateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.UpdateProductRequest): + request = product_service.UpdateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + 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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_delete_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2.Product] to delete + can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] with more than + one + [variants][google.cloud.retail.v2.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.DeleteProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.DeleteProductRequest): + request = product_service.DeleteProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2.Product]s. + + Request processing may be synchronous. Non-existing items are + created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2.Product]s to be successfully + updated. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_import_products(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportProductsRequest): + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2.Product] while respecting the + last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_set_inventory(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2.Product() + inventory.title = "title_value" + + request = retail_v2.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (google.cloud.retail_v2.types.Product): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product] named in + [Product.name][google.cloud.retail.v2.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.SetInventoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.SetInventoryRequest): + request = product_service.SetInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_add_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddFulfillmentPlacesRequest): + request = product_service.AddFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): + request = product_service.RemoveFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places, + while respecting the last update timestamps of each inventory + field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_add_local_inventories(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.AddLocalInventoriesResponse` Response of the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + API. Currently empty because there is no meaningful + response populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddLocalInventoriesRequest): + request = product_service.AddLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places at + a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_remove_local_inventories(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveLocalInventoriesRequest): + request = product_service.RemoveLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py new file mode 100644 index 00000000..f9e49958 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product_service + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.ListProductsResponse` + 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[..., product_service.ListProductsResponse], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[product_service.ListProductsResponse]: + 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[product.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.ListProductsResponse` + 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[product_service.ListProductsResponse]], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: + 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[product.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py new file mode 100644 index 00000000..db824dec --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ProductServiceTransport +from .grpc import ProductServiceGrpcTransport +from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] +_transport_registry['grpc'] = ProductServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport + +__all__ = ( + 'ProductServiceTransport', + 'ProductServiceGrpcTransport', + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py new file mode 100644 index 00000000..e3de653c --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py @@ -0,0 +1,312 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ProductServiceTransport(abc.ABC): + """Abstract transport class for ProductService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_product: gapic_v1.method.wrap_method( + self.create_product, + default_timeout=None, + client_info=client_info, + ), + self.get_product: gapic_v1.method.wrap_method( + self.get_product, + default_timeout=None, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + default_timeout=None, + client_info=client_info, + ), + self.update_product: gapic_v1.method.wrap_method( + self.update_product, + default_timeout=None, + client_info=client_info, + ), + self.delete_product: gapic_v1.method.wrap_method( + self.delete_product, + default_timeout=None, + client_info=client_info, + ), + self.import_products: gapic_v1.method.wrap_method( + self.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.set_inventory: gapic_v1.method.wrap_method( + self.set_inventory, + default_timeout=None, + client_info=client_info, + ), + self.add_fulfillment_places: gapic_v1.method.wrap_method( + self.add_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.remove_fulfillment_places: gapic_v1.method.wrap_method( + self.remove_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.add_local_inventories: gapic_v1.method.wrap_method( + self.add_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.remove_local_inventories: gapic_v1.method.wrap_method( + self.remove_local_inventories, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Union[ + product.Product, + Awaitable[product.Product] + ]]: + raise NotImplementedError() + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Union[ + product_service.ListProductsResponse, + Awaitable[product_service.ListProductsResponse] + ]]: + raise NotImplementedError() + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProductServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py new file mode 100644 index 00000000..108f3215 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py @@ -0,0 +1,680 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO + + +class ProductServiceGrpcTransport(ProductServiceTransport): + """gRPC backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + gcr_product.Product]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.CreateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + product.Product]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + product_service.ListProductsResponse]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + gcr_product.Product]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + ~.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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2.Product]s. + + Request processing may be synchronous. Non-existing items are + created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2.Product]s to be successfully + updated. + + Returns: + Callable[[~.ImportProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + operations_pb2.Operation]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2.Product] while respecting the + last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places, + while respecting the last update timestamps of each inventory + field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places at + a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProductServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..1d4ccc2d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py @@ -0,0 +1,679 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductServiceGrpcTransport + + +class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): + """gRPC AsyncIO backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.CreateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Awaitable[product.Product]]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Awaitable[product_service.ListProductsResponse]]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + 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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2.Product]s. + + Request processing may be synchronous. Non-existing items are + created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2.Product]s to be successfully + updated. + + Returns: + Callable[[~.ImportProductsRequest], + 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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2.Product] while respecting the + last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + 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 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + 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 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places, + while respecting the last update timestamps of each inventory + field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + 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 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places at + a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + 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 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py new file mode 100644 index 00000000..2f63fc22 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SearchServiceClient +from .async_client import SearchServiceAsyncClient + +__all__ = ( + 'SearchServiceClient', + 'SearchServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py new file mode 100644 index 00000000..c48710b8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.services.search_service import pagers +from google.cloud.retail_v2.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .client import SearchServiceClient + + +class SearchServiceAsyncClient: + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: SearchServiceClient + + DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(SearchServiceClient.branch_path) + parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + product_path = staticmethod(SearchServiceClient.product_path) + parse_product_path = staticmethod(SearchServiceClient.parse_product_path) + common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(SearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SearchServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAsyncPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_search(): + # Create a client + client = retail_v2.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.services.search_service.pagers.SearchAsyncPager: + Response message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py new file mode 100644 index 00000000..0072e3b0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py @@ -0,0 +1,513 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.services.search_service import pagers +from google.cloud.retail_v2.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SearchServiceGrpcTransport +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +class SearchServiceClientMeta(type): + """Metaclass for the SearchService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] + _transport_registry["grpc"] = SearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SearchServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SearchServiceClient(metaclass=SearchServiceClientMeta): + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SearchServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SearchServiceTransport): + # transport is a SearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_search(): + # Create a client + client = retail_v2.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.services.search_service.pagers.SearchPager: + Response message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a search_service.SearchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py new file mode 100644 index 00000000..524810e2 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2.types import search_service + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py new file mode 100644 index 00000000..7917cd1d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SearchServiceTransport +from .grpc import SearchServiceGrpcTransport +from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] +_transport_registry['grpc'] = SearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport + +__all__ = ( + 'SearchServiceTransport', + 'SearchServiceGrpcTransport', + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py new file mode 100644 index 00000000..541055f5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import search_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SearchServiceTransport(abc.ABC): + """Abstract transport class for SearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search: gapic_v1.method.wrap_method( + self.search, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Union[ + search_service.SearchResponse, + Awaitable[search_service.SearchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SearchServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py new file mode 100644 index 00000000..ee53c769 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py @@ -0,0 +1,270 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO + + +class SearchServiceGrpcTransport(SearchServiceTransport): + """gRPC backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..6c6e5f29 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SearchServiceGrpcTransport + + +class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): + """gRPC AsyncIO backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Awaitable[search_service.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py new file mode 100644 index 00000000..5f5171c1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py new file mode 100644 index 00000000..99002514 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py @@ -0,0 +1,730 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on the customer + website. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(UserEventServiceClient.catalog_path) + parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) + product_path = staticmethod(UserEventServiceClient.product_path) + parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_write_user_event(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_collect_user_event(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_purge_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_import_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_rejoin_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py new file mode 100644 index 00000000..cd1d35d8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py @@ -0,0 +1,930 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[UserEventServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on the customer + website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_write_user_event(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_collect_user_event(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_purge_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeUserEventsRequest): + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_import_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_rejoin_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.RejoinUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.RejoinUserEventsRequest): + request = user_event_service.RejoinUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py new file mode 100644 index 00000000..f53ee5d7 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py new file mode 100644 index 00000000..661a2d50 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py @@ -0,0 +1,235 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.rejoin_user_events: gapic_v1.method.wrap_method( + self.rejoin_user_events, + 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 write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + user_event.UserEvent, + Awaitable[user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py new file mode 100644 index 00000000..af50579d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..cdc1a2f9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + 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 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py new file mode 100644 index 00000000..8e0ea23a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .catalog import ( + Catalog, + ProductLevelConfig, +) +from .catalog_service import ( + GetDefaultBranchRequest, + GetDefaultBranchResponse, + ListCatalogsRequest, + ListCatalogsResponse, + SetDefaultBranchRequest, + UpdateCatalogRequest, +) +from .common import ( + Audience, + ColorInfo, + CustomAttribute, + FulfillmentInfo, + Image, + Interval, + LocalInventory, + PriceInfo, + Rating, + UserInfo, +) +from .completion_service import ( + CompleteQueryRequest, + CompleteQueryResponse, +) +from .import_config import ( + BigQuerySource, + CompletionDataInputConfig, + GcsSource, + ImportCompletionDataRequest, + ImportCompletionDataResponse, + ImportErrorsConfig, + ImportMetadata, + ImportProductsRequest, + ImportProductsResponse, + ImportUserEventsRequest, + ImportUserEventsResponse, + ProductInlineSource, + ProductInputConfig, + UserEventImportSummary, + UserEventInlineSource, + UserEventInputConfig, +) +from .prediction_service import ( + PredictRequest, + PredictResponse, +) +from .product import ( + Product, +) +from .product_service import ( + AddFulfillmentPlacesMetadata, + AddFulfillmentPlacesRequest, + AddFulfillmentPlacesResponse, + AddLocalInventoriesMetadata, + AddLocalInventoriesRequest, + AddLocalInventoriesResponse, + CreateProductRequest, + DeleteProductRequest, + GetProductRequest, + ListProductsRequest, + ListProductsResponse, + RemoveFulfillmentPlacesMetadata, + RemoveFulfillmentPlacesRequest, + RemoveFulfillmentPlacesResponse, + RemoveLocalInventoriesMetadata, + RemoveLocalInventoriesRequest, + RemoveLocalInventoriesResponse, + SetInventoryMetadata, + SetInventoryRequest, + SetInventoryResponse, + UpdateProductRequest, +) +from .promotion import ( + Promotion, +) +from .purge_config import ( + PurgeMetadata, + PurgeUserEventsRequest, + PurgeUserEventsResponse, +) +from .search_service import ( + SearchRequest, + SearchResponse, +) +from .user_event import ( + CompletionDetail, + ProductDetail, + PurchaseTransaction, + UserEvent, +) +from .user_event_service import ( + CollectUserEventRequest, + RejoinUserEventsMetadata, + RejoinUserEventsRequest, + RejoinUserEventsResponse, + WriteUserEventRequest, +) + +__all__ = ( + 'Catalog', + 'ProductLevelConfig', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'SetDefaultBranchRequest', + 'UpdateCatalogRequest', + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py new file mode 100644 index 00000000..47a372fb --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'ProductLevelConfig', + 'Catalog', + }, +) + + +class ProductLevelConfig(proto.Message): + r"""Configures what level the product should be uploaded with + regards to how users will be send events and how predictions + will be made. + + Attributes: + ingestion_product_type (str): + The type of [Product][google.cloud.retail.v2.Product]s + allowed to be ingested into the catalog. Acceptable values + are: + + - ``primary`` (default): You can ingest + [Product][google.cloud.retail.v2.Product]s of all types. + When ingesting a + [Product][google.cloud.retail.v2.Product], its type will + default to + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + if unset. + - ``variant`` (incompatible with Retail Search): You can + only ingest + [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s. This means + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] + cannot be empty. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``variant`` and + [merchant_center_product_id_field][google.cloud.retail.v2.ProductLevelConfig.merchant_center_product_id_field] + is ``itemGroupId``, an INVALID_ARGUMENT error is returned. + + See `Product + levels `__ + for more details. + merchant_center_product_id_field (str): + Which field of `Merchant Center + Product `__ + should be imported as + [Product.id][google.cloud.retail.v2.Product.id]. Acceptable + values are: + + - ``offerId`` (default): Import ``offerId`` as the product + ID. + - ``itemGroupId``: Import ``itemGroupId`` as the product + ID. Notice that Retail API will choose one item from the + ones with the same ``itemGroupId``, and use it to + represent the item group. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``itemGroupId`` and + [ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] + is ``variant``, an INVALID_ARGUMENT error is returned. + + See `Product + levels `__ + for more details. + """ + + ingestion_product_type = proto.Field( + proto.STRING, + number=1, + ) + merchant_center_product_id_field = proto.Field( + proto.STRING, + number=2, + ) + + +class Catalog(proto.Message): + r"""The catalog configuration. + + Attributes: + name (str): + Required. Immutable. The fully qualified + resource name of the catalog. + display_name (str): + Required. Immutable. The catalog display name. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + product_level_config (google.cloud.retail_v2.types.ProductLevelConfig): + Required. The product level configuration. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + product_level_config = proto.Field( + proto.MESSAGE, + number=4, + message='ProductLevelConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py new file mode 100644 index 00000000..721ef858 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'UpdateCatalogRequest', + 'SetDefaultBranchRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + }, +) + + +class ListCatalogsRequest(proto.Message): + r"""Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + + Attributes: + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2.Catalog]s under this + location, regardless of whether or not this location exists, + a PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of [Catalog][google.cloud.retail.v2.Catalog]s + to return. If unspecified, defaults to 50. The maximum + allowed value is 1000. Values above 1000 will be coerced to + 1000. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [ListCatalogsResponse.next_page_token][google.cloud.retail.v2.ListCatalogsResponse.next_page_token], + received from a previous + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCatalogsResponse(proto.Message): + r"""Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + + Attributes: + catalogs (Sequence[google.cloud.retail_v2.types.Catalog]): + All the customer's + [Catalog][google.cloud.retail.v2.Catalog]s. + next_page_token (str): + A token that can be sent as + [ListCatalogsRequest.page_token][google.cloud.retail.v2.ListCatalogsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + catalogs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateCatalogRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] + method. + + Attributes: + catalog (google.cloud.retail_v2.types.Catalog): + Required. The [Catalog][google.cloud.retail.v2.Catalog] to + update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2.Catalog], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2.Catalog] 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 + [Catalog][google.cloud.retail.v2.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + catalog = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class SetDefaultBranchRequest(proto.Message): + r"""Request message to set a specified branch as new default_branch. + + Attributes: + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + branch_id (str): + The final component of the resource name of a branch. + + This field must be one of "0", "1" or "2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If there are no sufficient active products in the targeted + branch and + [force][google.cloud.retail.v2.SetDefaultBranchRequest.force] + is not set, a FAILED_PRECONDITION error is returned. + note (str): + Some note on this request, this can be retrieved by + [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch] + before next valid default branch set occurs. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + force (bool): + If set to true, it permits switching to a branch with + [branch_id][google.cloud.retail.v2.SetDefaultBranchRequest.branch_id] + even if it has no sufficient active products. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + force = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetDefaultBranchRequest(proto.Message): + r"""Request message to show which branch is currently the default + branch. + + Attributes: + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDefaultBranchResponse(proto.Message): + r"""Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. + + Attributes: + branch (str): + Full resource name of the branch id currently + set as default branch. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when this branch is set to default. + note (str): + This corresponds to + [SetDefaultBranchRequest.note][google.cloud.retail.v2.SetDefaultBranchRequest.note] + field, when this branch was set as default. + """ + + branch = proto.Field( + proto.STRING, + number=1, + ) + set_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py new file mode 100644 index 00000000..fe50745a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py @@ -0,0 +1,736 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'LocalInventory', + }, +) + + +class Audience(proto.Message): + r"""An intended audience of the + [Product][google.cloud.retail.v2.Product] for whom it's sold. + + Attributes: + genders (Sequence[str]): + The genders of the audience. Strongly encouraged to use the + standard values: "male", "female", "unisex". + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `gender `__. + Schema.org property + `Product.audience.suggestedGender `__. + age_groups (Sequence[str]): + The age groups of the audience. Strongly encouraged to use + the standard values: "newborn" (up to 3 months old), + "infant" (3–12 months old), "toddler" (1–5 years old), + "kids" (5–13 years old), "adult" (typically teens or older). + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `age_group `__. + Schema.org property + `Product.audience.suggestedMinAge `__ + and + `Product.audience.suggestedMaxAge `__. + """ + + genders = proto.RepeatedField( + proto.STRING, + number=1, + ) + age_groups = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class ColorInfo(proto.Message): + r"""The color information of a + [Product][google.cloud.retail.v2.Product]. + + Attributes: + color_families (Sequence[str]): + The standard color families. Strongly recommended to use the + following standard color groups: "Red", "Pink", "Orange", + "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", + "White", "Gray", "Black" and "Mixed". Normally it is + expected to have only 1 color family. May consider using + single "Mixed" instead of multiple values. + + A maximum of 5 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + colors (Sequence[str]): + The color display names, which may be different from + standard color family names, such as the color aliases used + in the website frontend. Normally it is expected to have + only 1 color. May consider using single "Mixed" instead of + multiple values. + + A maximum of 25 colors are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + """ + + color_families = proto.RepeatedField( + proto.STRING, + number=1, + ) + colors = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in + [Product][google.cloud.retail.v2.Product]. + + Attributes: + text (Sequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an INVALID_ARGUMENT + error is returned. + + Exactly one of + [text][google.cloud.retail.v2.CustomAttribute.text] or + [numbers][google.cloud.retail.v2.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + numbers (Sequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [text][google.cloud.retail.v2.CustomAttribute.text] or + [numbers][google.cloud.retail.v2.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + searchable (bool): + This field is normally ignored unless + [AttributesConfig.attribute_config_level][] of the + [Catalog][google.cloud.retail.v2.Catalog] is set to the + deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For + information about product-level attribute configuration, see + `Configuration + modes `__. + If true, custom attribute values are searchable by text + queries in + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2.UserEvent]. + + Only set if type + [text][google.cloud.retail.v2.CustomAttribute.text] is set. + Otherwise, a INVALID_ARGUMENT error is returned. + + This field is a member of `oneof`_ ``_searchable``. + indexable (bool): + This field is normally ignored unless + [AttributesConfig.attribute_config_level][] of the + [Catalog][google.cloud.retail.v2.Catalog] is set to the + deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For + information about product-level attribute configuration, see + `Configuration + modes `__. + If true, custom attribute values are indexed, so that they + can be filtered, faceted or boosted in + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2.UserEvent]. + + See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter], + [SearchRequest.facet_specs][google.cloud.retail.v2.SearchRequest.facet_specs] + and + [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] + for more details. + + This field is a member of `oneof`_ ``_indexable``. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + searchable = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + indexable = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + +class FulfillmentInfo(proto.Message): + r"""Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + Attributes: + type_ (str): + The fulfillment type, including commonly used types (such as + pickup in store and same day delivery), and custom types. + Customers have to map custom types to their display names + before rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + place_ids (Sequence[str]): + The IDs for this + [type][google.cloud.retail.v2.FulfillmentInfo.type], such as + the store IDs for + [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2.FulfillmentInfo.type] + or the region IDs for + [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2.FulfillmentInfo.type]. + + A maximum of 3000 values are allowed. Each value must be a + string with a length limit of 30 characters, matching the + pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". + Otherwise, an INVALID_ARGUMENT error is returned. + """ + + type_ = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class Image(proto.Message): + r"""[Product][google.cloud.retail.v2.Product] image. Recommendations AI + and Retail Search do not use product images to improve prediction + and search results. However, product images can be returned in + results, and are shown in prediction or search previews in the + console. + + Attributes: + uri (str): + Required. URI of the image. + + This field must be a valid UTF-8 encoded URI with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + height (int): + Height of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + width (int): + Width of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + height = proto.Field( + proto.INT32, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + + +class Interval(proto.Message): + r"""A floating point interval. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum = proto.Field( + proto.DOUBLE, + number=1, + oneof='min', + ) + exclusive_minimum = proto.Field( + proto.DOUBLE, + number=2, + oneof='min', + ) + maximum = proto.Field( + proto.DOUBLE, + number=3, + oneof='max', + ) + exclusive_maximum = proto.Field( + proto.DOUBLE, + number=4, + oneof='max', + ) + + +class PriceInfo(proto.Message): + r"""The price information of a + [Product][google.cloud.retail.v2.Product]. + + Attributes: + currency_code (str): + The 3-letter currency code defined in `ISO + 4217 `__. + + If this field is an unrecognizable currency code, an + INVALID_ARGUMENT error is returned. + + The + [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s with the same + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] + must share the same + [currency_code][google.cloud.retail.v2.PriceInfo.currency_code]. + Otherwise, a FAILED_PRECONDITION error is returned. + price (float): + Price of the product. + + Google Merchant Center property + `price `__. + Schema.org property + `Offer.price `__. + original_price (float): + Price of the product without any discount. If zero, by + default set to be the + [price][google.cloud.retail.v2.PriceInfo.price]. If set, + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + should be greater than or equal to + [price][google.cloud.retail.v2.PriceInfo.price], otherwise + an INVALID_ARGUMENT error is thrown. + cost (float): + The costs associated with the sale of a particular product. + Used for gross profit reporting. + + - Profit = [price][google.cloud.retail.v2.PriceInfo.price] + - [cost][google.cloud.retail.v2.PriceInfo.cost] + + Google Merchant Center property + `cost_of_goods_sold `__. + price_effective_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2.PriceInfo.price] starts to be + effective. This can be set as a future timestamp, and the + [price][google.cloud.retail.v2.PriceInfo.price] is only used + for search after + [price_effective_time][google.cloud.retail.v2.PriceInfo.price_effective_time]. + If so, the + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + is used before + [price_effective_time][google.cloud.retail.v2.PriceInfo.price_effective_time]. + + Do not set if + [price][google.cloud.retail.v2.PriceInfo.price] is always + effective because it will cause additional latency during + search. + price_expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2.PriceInfo.price] stops to be + effective. The + [price][google.cloud.retail.v2.PriceInfo.price] is used for + search before + [price_expire_time][google.cloud.retail.v2.PriceInfo.price_expire_time]. + If this field is set, the + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + is used after + [price_expire_time][google.cloud.retail.v2.PriceInfo.price_expire_time]. + + Do not set if + [price][google.cloud.retail.v2.PriceInfo.price] is always + effective because it will cause additional latency during + search. + price_range (google.cloud.retail_v2.types.PriceInfo.PriceRange): + Output only. The price range of all the child + [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s grouped together + on the + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]. Only populated + for + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]. + Do not set this field in API requests. + """ + + class PriceRange(proto.Message): + r"""The price range of all + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. + + Attributes: + price (google.cloud.retail_v2.types.Interval): + The inclusive + [Product.pricing_info.price][google.cloud.retail.v2.PriceInfo.price] + interval of all + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. + original_price (google.cloud.retail_v2.types.Interval): + The inclusive + [Product.pricing_info.original_price][google.cloud.retail.v2.PriceInfo.original_price] + internal of all + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. + """ + + price = proto.Field( + proto.MESSAGE, + number=1, + message='Interval', + ) + original_price = proto.Field( + proto.MESSAGE, + number=2, + message='Interval', + ) + + currency_code = proto.Field( + proto.STRING, + number=1, + ) + price = proto.Field( + proto.FLOAT, + number=2, + ) + original_price = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + price_effective_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + price_expire_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + price_range = proto.Field( + proto.MESSAGE, + number=7, + message=PriceRange, + ) + + +class Rating(proto.Message): + r"""The rating of a [Product][google.cloud.retail.v2.Product]. + + Attributes: + rating_count (int): + The total number of ratings. This value is independent of + the value of + [rating_histogram][google.cloud.retail.v2.Rating.rating_histogram]. + + This value must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + average_rating (float): + The average rating of the + [Product][google.cloud.retail.v2.Product]. + + The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT + error is returned. + rating_histogram (Sequence[int]): + List of rating counts per rating value (index = rating - 1). + The list is empty if there is no rating. If the list is + non-empty, its size is always 5. Otherwise, an + INVALID_ARGUMENT error is returned. + + For example, [41, 14, 13, 47, 303]. It means that the + [Product][google.cloud.retail.v2.Product] got 41 ratings + with 1 star, 14 ratings with 2 star, and so on. + """ + + rating_count = proto.Field( + proto.INT32, + number=1, + ) + average_rating = proto.Field( + proto.FLOAT, + number=2, + ) + rating_histogram = proto.RepeatedField( + proto.INT32, + number=3, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. Don't set for + anonymous users. + + Always use a hashed value for this ID. + + Don't set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + ip_address (str): + The end user's IP address. This field is used to extract + location information for personalization. + + This field must be either an IPv4 address (e.g. + "104.133.9.80") or an IPv6 address (e.g. + "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an + INVALID_ARGUMENT error is returned. + + This should not be set when: + + - setting + [SearchRequest.user_info][google.cloud.retail.v2.SearchRequest.user_info]. + - using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request] + is set. + user_agent (str): + User agent as included in the HTTP header. Required for + getting + [SearchResponse.sponsored_results][google.cloud.retail.v2.SearchResponse.sponsored_results]. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request] + is set. + direct_user_request (bool): + True if the request is made directly from the end user, in + which case the + [ip_address][google.cloud.retail.v2.UserInfo.ip_address] and + [user_agent][google.cloud.retail.v2.UserInfo.user_agent] can + be populated from the HTTP request. This flag should be set + only if the API request is made directly from the end user + such as a mobile app (and not if a gateway or a server is + processing and pushing the user events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent]. + """ + + user_id = proto.Field( + proto.STRING, + number=1, + ) + ip_address = proto.Field( + proto.STRING, + number=2, + ) + user_agent = proto.Field( + proto.STRING, + number=3, + ) + direct_user_request = proto.Field( + proto.BOOL, + number=4, + ) + + +class LocalInventory(proto.Message): + r"""The inventory information at a place (e.g. a store) + identified by a place ID. + + Attributes: + place_id (str): + The place ID for the current set of inventory + information. + price_info (google.cloud.retail_v2.types.PriceInfo): + Product price and cost information. + + Google Merchant Center property + `price `__. + attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): + Additional local inventory attributes, for example, store + name, promotion tags, etc. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - At most 30 attributes are allowed. + - The key must be a UTF-8 encoded string with a length + limit of 32 characters. + - The key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis + or KEY_1_LIKE_THIS. + - The attribute values must be of the same type (text or + number). + - Only 1 value is allowed for each attribute. + - For text values, the length limit is 256 UTF-8 + characters. + - The attribute does not support search. The ``searchable`` + field should be unset or set to false. + - The max summed total bytes of custom attribute keys and + values per product is 5MiB. + fulfillment_types (Sequence[str]): + Input only. Supported fulfillment types. Valid fulfillment + type values include commonly used types (such as pickup in + store and same day delivery), and custom types. Customers + have to map custom types to their display names before + rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + All the elements must be distinct. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + place_id = proto.Field( + proto.STRING, + number=1, + ) + price_info = proto.Field( + proto.MESSAGE, + number=2, + message='PriceInfo', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='CustomAttribute', + ) + fulfillment_types = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py new file mode 100644 index 00000000..421cc1c0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'CompleteQueryRequest', + 'CompleteQueryResponse', + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Auto-complete parameters. + + Attributes: + catalog (str): + Required. Catalog for which the completion is performed. + + Full resource name of catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + query (str): + Required. The query used to generate + suggestions. + The maximum number of allowed characters is 255. + visitor_id (str): + Required field. A unique identifier for tracking visitors. + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + language_codes (Sequence[str]): + The language filters applied to the output suggestions. If + set, it should contain the language of the query. If not + set, suggestions are returned without considering language + restrictions. This is the BCP-47 language code, such as + "en-US" or "sr-Latn". For more information, see `Tags for + Identifying + Languages `__. The + maximum number of language codes is 3. + device_type (str): + The device type context for completion suggestions. It is + useful to apply different suggestions on different device + types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the + suggestions are across all device types. + + Supported formats: + + - ``UNKNOWN_DEVICE_TYPE`` + + - ``DESKTOP`` + + - ``MOBILE`` + + - A customized string starts with ``OTHER_``, e.g. + ``OTHER_IPHONE``. + dataset (str): + Determines which dataset to use for fetching completion. + "user-data" will use the imported dataset through + [CompletionService.ImportCompletionData][google.cloud.retail.v2.CompletionService.ImportCompletionData]. + "cloud-retail" will use the dataset generated by cloud + retail based on user events. If leave empty, it will use the + "user-data". + + Current supported values: + + - user-data + + - cloud-retail: This option requires enabling auto-learning + function first. See + `guidelines `__. + max_suggestions (int): + Completion max suggestions. If left unset or set to 0, then + will fallback to the configured value + [CompletionConfig.max_suggestions][]. + + The maximum allowed max suggestions is 20. If it is set + higher, it will be capped by 20. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + visitor_id = proto.Field( + proto.STRING, + number=7, + ) + language_codes = proto.RepeatedField( + proto.STRING, + number=3, + ) + device_type = proto.Field( + proto.STRING, + number=4, + ) + dataset = proto.Field( + proto.STRING, + number=6, + ) + max_suggestions = proto.Field( + proto.INT32, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response of the auto-complete query. + + Attributes: + completion_results (Sequence[google.cloud.retail_v2.types.CompleteQueryResponse.CompletionResult]): + Results of the matching suggestions. The + result list is ordered and the first result is + top suggestion. + attribution_token (str): + A unique complete token. This should be included in the + [UserEvent.completion_detail][google.cloud.retail.v2.UserEvent.completion_detail] + for search events resulting from this completion, which + enables accurate attribution of complete model performance. + recent_search_results (Sequence[google.cloud.retail_v2.types.CompleteQueryResponse.RecentSearchResult]): + Matched recent searches of this user. The maximum number of + recent searches is 10. This field is a restricted feature. + Contact Retail Search support team if you are interested in + enabling it. + + This feature is only available when + [CompleteQueryRequest.visitor_id][google.cloud.retail.v2.CompleteQueryRequest.visitor_id] + field is set and + [UserEvent][google.cloud.retail.v2.UserEvent] is imported. + The recent searches satisfy the follow rules: + + - They are ordered from latest to oldest. + + - They are matched with + [CompleteQueryRequest.query][google.cloud.retail.v2.CompleteQueryRequest.query] + case insensitively. + + - They are transformed to lower cases. + + - They are UTF-8 safe. + + Recent searches are deduplicated. More recent searches will + be reserved when duplication happens. + """ + + class CompletionResult(proto.Message): + r"""Resource that represents completion results. + + Attributes: + suggestion (str): + The suggestion for the query. + attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): + Custom attributes for the suggestion term. + + - For "user-data", the attributes are additional custom + attributes ingested through BigQuery. + + - For "cloud-retail", the attributes are product attributes + generated by Cloud Retail. This is an experimental + feature. Contact Retail Search support team if you are + interested in enabling it. + """ + + suggestion = proto.Field( + proto.STRING, + number=1, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=common.CustomAttribute, + ) + + class RecentSearchResult(proto.Message): + r"""Recent search of this user. + + Attributes: + recent_search (str): + The recent search query. + """ + + recent_search = proto.Field( + proto.STRING, + number=1, + ) + + completion_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=CompletionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + recent_search_results = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=RecentSearchResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py new file mode 100644 index 00000000..983e15df --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py @@ -0,0 +1,697 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import user_event +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'GcsSource', + 'BigQuerySource', + 'ProductInlineSource', + 'UserEventInlineSource', + 'ImportErrorsConfig', + 'ImportProductsRequest', + 'ImportUserEventsRequest', + 'ImportCompletionDataRequest', + 'ProductInputConfig', + 'UserEventInputConfig', + 'CompletionDataInputConfig', + 'ImportMetadata', + 'ImportProductsResponse', + 'ImportUserEventsResponse', + 'UserEventImportSummary', + 'ImportCompletionDataResponse', + }, +) + + +class GcsSource(proto.Message): + r"""Google Cloud Storage location for input content. + format. + + Attributes: + input_uris (Sequence[str]): + Required. Google Cloud Storage URIs to input files. URI can + be up to 2000 characters long. URIs can match the full + object path (for example, + ``gs://bucket/directory/object.json``) or a pattern matching + one or more files, such as ``gs://bucket/directory/*.json``. + A request can contain at most 100 files, and each file can + be up to 2 GB. See `Importing product + information `__ + for the expected file format and setup instructions. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2.Product] per line. Each + product must have a valid + [Product.id][google.cloud.retail.v2.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2.UserEvent] per line. + - ``user_event_ga360``: Using + https://support.google.com/analytics/answer/3437719. + + Supported values for control imports: + + - 'control' (default): One JSON [Control][] per line. + + Supported values for catalog attribute imports: + + - 'catalog_attribute' (default): One CSV + [CatalogAttribute][] per line. + """ + + input_uris = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID (can be project # or ID) that + the BigQuery source is in with a length limit of + 128 characters. If not specified, inherits the + project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2.Product] per line. Each + product must have a valid + [Product.id][google.cloud.retail.v2.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2.UserEvent] per line. + - ``user_event_ga360``: The schema is available here: + https://support.google.com/analytics/answer/3437719. + - ``user_event_ga4``: This feature is in private preview. + Please contact the support team for importing Google + Analytics 4 events. The schema is available here: + https://support.google.com/analytics/answer/7029846. + + Supported values for auto-completion imports: + + - ``suggestions`` (default): One JSON completion suggestion + per line. + - ``denylist``: One JSON deny suggestion per line. + - ``allowlist``: One JSON allow suggestion per line. + """ + + partition_date = proto.Field( + proto.MESSAGE, + number=6, + oneof='partition', + message=date_pb2.Date, + ) + project_id = proto.Field( + proto.STRING, + number=5, + ) + dataset_id = proto.Field( + proto.STRING, + number=1, + ) + table_id = proto.Field( + proto.STRING, + number=2, + ) + gcs_staging_dir = proto.Field( + proto.STRING, + number=3, + ) + data_schema = proto.Field( + proto.STRING, + number=4, + ) + + +class ProductInlineSource(proto.Message): + r"""The inline source for the input config for ImportProducts + method. + + Attributes: + products (Sequence[google.cloud.retail_v2.types.Product]): + Required. A list of products to update/create. Each product + must have a valid + [Product.id][google.cloud.retail.v2.Product.id]. Recommended + max of 100 items. + """ + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=product.Product, + ) + + +class UserEventInlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (Sequence[google.cloud.retail_v2.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + +class ImportErrorsConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage prefix for import errors. This must be + an empty, existing Cloud Storage directory. Import errors + will be written to sharded files in this directory, one per + line, as a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportProductsRequest(proto.Message): + r"""Request message for Import methods. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` + + If no updateMask is specified, requires products.create + permission. If updateMask is specified, requires + products.update permission. + request_id (str): + Deprecated. This field has no effect. + input_config (google.cloud.retail_v2.types.ProductInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported 'products' to update. If not set, will + by default update all fields. + reconciliation_mode (google.cloud.retail_v2.types.ImportProductsRequest.ReconciliationMode): + The mode of reconciliation between existing products and the + products to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. + notification_pubsub_topic (str): + Full Pub/Sub topic name for receiving notification. If this + field is set, when the import is finished, a notification + will be sent to specified Pub/Sub topic. The message data + will be JSON string of a + [Operation][google.longrunning.Operation]. + + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. It has to be within + the same project as + [ImportProductsRequest.parent][google.cloud.retail.v2.ImportProductsRequest.parent]. + Make sure that both + ``cloud-retail-customer-data-access@system.gserviceaccount.com`` + and + ``service-@gcp-sa-retail.iam.gserviceaccount.com`` + have the ``pubsub.topics.publish`` IAM permission on the + topic. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + """ + class ReconciliationMode(proto.Enum): + r"""Indicates how imported products are reconciled with the + existing products created or imported before. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + request_id = proto.Field( + proto.STRING, + number=6, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='ProductInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + reconciliation_mode = proto.Field( + proto.ENUM, + number=5, + enum=ReconciliationMode, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=7, + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + input_config (google.cloud.retail_v2.types.UserEventInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='UserEventInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + + +class ImportCompletionDataRequest(proto.Message): + r"""Request message for ImportCompletionData methods. + + Attributes: + parent (str): + Required. The catalog which the suggestions dataset belongs + to. + + Format: + ``projects/1234/locations/global/catalogs/default_catalog``. + input_config (google.cloud.retail_v2.types.CompletionDataInputConfig): + Required. The desired input location of the + data. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='CompletionDataInputConfig', + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=3, + ) + + +class ProductInputConfig(proto.Message): + r"""The input config source for products. + + 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: + product_inline_source (google.cloud.retail_v2.types.ProductInlineSource): + The Inline source for the input content for + products. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2.types.GcsSource): + Google Cloud Storage location for the input + content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + product_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='ProductInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class UserEventInputConfig(proto.Message): + r"""The input config source for user events. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user_event_inline_source (google.cloud.retail_v2.types.UserEventInlineSource): + Required. The Inline source for the input + content for UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2.types.GcsSource): + Required. Google Cloud Storage location for + the input content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2.types.BigQuerySource): + Required. BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + user_event_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='UserEventInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class CompletionDataInputConfig(proto.Message): + r"""The input config source for completion data. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + big_query_source (google.cloud.retail_v2.types.BigQuerySource): + Required. BigQuery input source. + Add the IAM permission "BigQuery Data Viewer" + for + cloud-retail-customer-data-access@system.gserviceaccount.com + before using this feature otherwise an error is + thrown. + + This field is a member of `oneof`_ ``source``. + """ + + big_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='BigQuerySource', + ) + + +class ImportMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + request_id (str): + Deprecated. This field is never set. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=3, + ) + failure_count = proto.Field( + proto.INT64, + number=4, + ) + request_id = proto.Field( + proto.STRING, + number=5, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=6, + ) + + +class ImportProductsResponse(proto.Message): + r"""Response of the + [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + import_summary (google.cloud.retail_v2.types.UserEventImportSummary): + Aggregated statistics of user event import + status. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + import_summary = proto.Field( + proto.MESSAGE, + number=3, + message='UserEventImportSummary', + ) + + +class UserEventImportSummary(proto.Message): + r"""A summary of import result. The UserEventImportSummary + summarizes the import status for user events. + + Attributes: + joined_events_count (int): + Count of user events imported with complete + existing catalog information. + unjoined_events_count (int): + Count of user events imported, but with + catalog information not found in the imported + catalog. + """ + + joined_events_count = proto.Field( + proto.INT64, + number=1, + ) + unjoined_events_count = proto.Field( + proto.INT64, + number=2, + ) + + +class ImportCompletionDataResponse(proto.Message): + r"""Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. + 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 (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py new file mode 100644 index 00000000..68e8c74b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py @@ -0,0 +1,275 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import user_event as gcr_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'PredictRequest', + 'PredictResponse', + }, +) + + +class PredictRequest(proto.Message): + r"""Request message for Predict method. + + Attributes: + placement (str): + Required. Full resource name of the format: + {name=projects/*/locations/global/catalogs/default_catalog/placements/*} + The ID of the Recommendations AI placement. Before you can + request predictions from your model, you must create at + least one placement for it. For more information, see + `Managing + placements `__. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements + user_event (google.cloud.retail_v2.types.UserEvent): + Required. Context about the user, what they are looking at + and what action they took to trigger the predict request. + Note that this user event detail won't be ingested to + userEvent logs. Thus, a separate userEvent write request is + required for event logging. + + Don't set + [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] + or + [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] + to the same fixed ID for different users. If you are trying + to receive non-personalized recommendations (not + recommended; this can negatively impact model performance), + instead set + [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] + to a random unique ID and leave + [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] + unset. + page_size (int): + Maximum number of results to return per page. + Set this property to the number of prediction + results needed. If zero, the service will choose + a reasonable default. The maximum allowed value + is 100. Values above 100 will be coerced to 100. + page_token (str): + The previous PredictResponse.next_page_token. + filter (str): + Filter for restricting prediction results with a length + limit of 5,000 characters. Accepts values for tags and the + ``filterOutOfStockItems`` flag. + + - Tag expressions. Restricts predictions to products that + match all of the specified tags. Boolean operators ``OR`` + and ``NOT`` are supported if the expression is enclosed + in parentheses, and must be separated from the tag values + by a space. ``-"tagA"`` is also supported and is + equivalent to ``NOT "tagA"``. Tag values must be double + quoted UTF-8 encoded strings with a size limit of 1,000 + characters. + + Note: "Recently viewed" models don't support tag + filtering at the moment. + + - filterOutOfStockItems. Restricts predictions to products + that do not have a stockState value of OUT_OF_STOCK. + + Examples: + + - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT + "promotional") + - filterOutOfStockItems tag=(-"promotional") + - filterOutOfStockItems + + If your filter blocks all prediction results, the API will + return generic (unfiltered) popular products. If you only + want results strictly matching the filters, set + ``strictFiltering`` to True in ``PredictRequest.params`` to + receive empty results instead. Note that the API will never + return items with storageStatus of "EXPIRED" or "DELETED" + regardless of filter choices. + validate_only (bool): + Use validate only mode for this prediction + query. If set to true, a dummy model will be + used that returns arbitrary products. Note that + the validate only mode should only be used for + testing the API, or if the model is not ready. + params (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific parameters for the predictions. + + Allowed values: + + - ``returnProduct``: Boolean. If set to true, the + associated product object will be returned in the + ``results.metadata`` field in the prediction response. + - ``returnScore``: Boolean. If set to true, the prediction + 'score' corresponding to each returned product will be + set in the ``results.metadata`` field in the prediction + response. The given 'score' indicates the probability of + an product being clicked/purchased given the user's + context and history. + - ``strictFiltering``: Boolean. True by default. If set to + false, the service will return generic (unfiltered) + popular products instead of empty if your filter blocks + all prediction results. + - ``priceRerankLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of + {'no-price-reranking', 'low-price-reranking', + 'medium-price-reranking', 'high-price-reranking'}. This + gives request-level control and adjusts prediction + results based on product price. + - ``diversityLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of {'no-diversity', + 'low-diversity', 'medium-diversity', 'high-diversity', + 'auto-diversity'}. This gives request-level control and + adjusts prediction results based on product category. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + placement = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + filter = proto.Field( + proto.STRING, + number=5, + ) + validate_only = proto.Field( + proto.BOOL, + number=6, + ) + params = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class PredictResponse(proto.Message): + r"""Response message for predict method. + + Attributes: + results (Sequence[google.cloud.retail_v2.types.PredictResponse.PredictionResult]): + A list of recommended products. The order + represents the ranking (from the most relevant + product to the least). + attribution_token (str): + A unique attribution token. This should be included in the + [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting + from this recommendation, which enables accurate attribution + of recommendation model performance. + missing_ids (Sequence[str]): + IDs of products in the request that were + missing from the inventory. + validate_only (bool): + True if the validateOnly property was set in + the request. + """ + + class PredictionResult(proto.Message): + r"""PredictionResult represents the recommendation prediction + results. + + Attributes: + id (str): + ID of the recommended product + metadata (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional product metadata / annotations. + + Possible values: + + - ``product``: JSON representation of the product. Is set + if ``returnProduct`` is set to true in + ``PredictRequest.params``. + - ``score``: Prediction score in double value. Is set if + ``returnScore`` is set to true in + ``PredictRequest.params``. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + metadata = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=PredictionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + missing_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py new file mode 100644 index 00000000..bff41d83 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py @@ -0,0 +1,701 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'Product', + }, +) + + +class Product(proto.Message): + r"""Product captures all metadata information of items to be + recommended or searched. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this product becomes unavailable for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + + If it is set, the [Product][google.cloud.retail.v2.Product] + is not available for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + after + [expire_time][google.cloud.retail.v2.Product.expire_time]. + However, the product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + [expire_time][google.cloud.retail.v2.Product.expire_time] + must be later than + [available_time][google.cloud.retail.v2.Product.available_time] + and + [publish_time][google.cloud.retail.v2.Product.publish_time], + otherwise an INVALID_ARGUMENT error is thrown. + + Corresponding properties: Google Merchant Center property + `expiration_date `__. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Input only. The TTL (time to live) of the product. + + If it is set, it must be a non-negative value, and + [expire_time][google.cloud.retail.v2.Product.expire_time] is + set as current timestamp plus + [ttl][google.cloud.retail.v2.Product.ttl]. The derived + [expire_time][google.cloud.retail.v2.Product.expire_time] is + returned in the output and + [ttl][google.cloud.retail.v2.Product.ttl] is left blank when + retrieving the [Product][google.cloud.retail.v2.Product]. + + If it is set, the product is not available for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + after current timestamp plus + [ttl][google.cloud.retail.v2.Product.ttl]. However, the + product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This field is a member of `oneof`_ ``expiration``. + name (str): + Immutable. Full resource name of the product, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. + id (str): + Immutable. [Product][google.cloud.retail.v2.Product] + identifier, which is the final component of + [name][google.cloud.retail.v2.Product.name]. For example, + this field is "id_1", if + [name][google.cloud.retail.v2.Product.name] is + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `id `__. + Schema.org property + `Product.sku `__. + type_ (google.cloud.retail_v2.types.Product.Type): + Immutable. The type of the product. Default to + [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] + if unset. + primary_product_id (str): + Variant group identifier. Must be an + [id][google.cloud.retail.v2.Product.id], with the same + parent branch with this product. Otherwise, an error is + thrown. + + For + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]s, this field can + only be empty or set to the same value as + [id][google.cloud.retail.v2.Product.id]. + + For VARIANT [Product][google.cloud.retail.v2.Product]s, this + field cannot be empty. A maximum of 2,000 products are + allowed to share the same + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `item_group_id `__. + Schema.org property + `Product.inProductGroupWithID `__. + collection_member_ids (Sequence[str]): + The [id][google.cloud.retail.v2.Product.id] of the + collection members when + [type][google.cloud.retail.v2.Product.type] is + [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]. + + Non-existent product ids are allowed. The + [type][google.cloud.retail.v2.Product.type] of the members + must be either + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + or + [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + otherwise and INVALID_ARGUMENT error is thrown. Should not + set it for other types. A maximum of 1000 values are + allowed. Otherwise, an INVALID_ARGUMENT error is return. + gtin (str): + The Global Trade Item Number (GTIN) of the product. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This field must be a Unigram. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `gtin `__. + Schema.org property + `Product.isbn `__, + `Product.gtin8 `__, + `Product.gtin12 `__, + `Product.gtin13 `__, or + `Product.gtin14 `__. + + If the value is not a valid GTIN, an INVALID_ARGUMENT error + is returned. + categories (Sequence[str]): + Product categories. This field is repeated for supporting + one product belonging to several parallel categories. + Strongly recommended using the full path for better search / + recommendation quality. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + For example, if a shoes product belongs to both ["Shoes & + Accessories" -> "Shoes"] and ["Sports & Fitness" -> + "Athletic Clothing" -> "Shoes"], it could be represented as: + + :: + + "categories": [ + "Shoes & Accessories > Shoes", + "Sports & Fitness > Athletic Clothing > Shoes" + ] + + Must be set for + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] otherwise an + INVALID_ARGUMENT error is returned. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2.Product]. Empty values are + not allowed. Each value must be a UTF-8 encoded string with + a length limit of 5,000 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `google_product_category `__. + Schema.org property [Product.category] + (https://schema.org/category). + title (str): + Required. Product title. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `title `__. + Schema.org property + `Product.name `__. + brands (Sequence[str]): + The brands of the product. + + A maximum of 30 brands are allowed. Each brand must be a + UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `brand `__. + Schema.org property + `Product.brand `__. + description (str): + Product description. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `description `__. + Schema.org property + `Product.description `__. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. + + For product prediction, this field is ignored and the model + automatically detects the text language. The + [Product][google.cloud.retail.v2.Product] can include text + in different languages, but duplicating + [Product][google.cloud.retail.v2.Product]s to provide text + in multiple languages can result in degraded model + performance. + + For product search this field is in use. It defaults to + "en-US" if unset. + attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): + Highly encouraged. Extra product attributes to be included. + For example, for products, this could include the store + name, vendor, style, color, etc. These are very strong + signals for recommendation model, thus we highly recommend + providing the attributes here. + + Features that can take on one of a limited number of + possible values. Two types of features can be set are: + + Textual features. some examples would be the brand/maker of + a product, or country of a customer. Numerical features. + Some examples would be the height/weight of a product, or + age of a customer. + + For example: + ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - Max entries count: 200. + - The key must be a UTF-8 encoded string with a length + limit of 128 characters. + - For indexable attribute, the key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, + ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a + non-empty UTF-8 encoded string with a length limit of 256 + characters. + - For number attributes, at most 400 values are allowed. + tags (Sequence[str]): + Custom tags associated with the product. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2.Product]. This value must + be a UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This tag can be used for filtering recommendation results by + passing the tag as part of the + [PredictRequest.filter][google.cloud.retail.v2.PredictRequest.filter]. + + Corresponding properties: Google Merchant Center property + `custom_label_0–4 `__. + price_info (google.cloud.retail_v2.types.PriceInfo): + Product price and cost information. + + Corresponding properties: Google Merchant Center property + `price `__. + rating (google.cloud.retail_v2.types.Rating): + The rating of this product. + available_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this + [Product][google.cloud.retail.v2.Product] becomes available + for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + availability (google.cloud.retail_v2.types.Product.Availability): + The online availability of the + [Product][google.cloud.retail.v2.Product]. Default to + [Availability.IN_STOCK][google.cloud.retail.v2.Product.Availability.IN_STOCK]. + + Corresponding properties: Google Merchant Center property + `availability `__. + Schema.org property + `Offer.availability `__. + available_quantity (google.protobuf.wrappers_pb2.Int32Value): + The available quantity of the item. + fulfillment_info (Sequence[google.cloud.retail_v2.types.FulfillmentInfo]): + Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + All the elements must have distinct + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type]. + Otherwise, an INVALID_ARGUMENT error is returned. + uri (str): + Canonical URL directly linking to the product detail page. + + It is strongly recommended to provide a valid uri for the + product, otherwise the service performance could be + significantly degraded. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `link `__. + Schema.org property `Offer.url `__. + images (Sequence[google.cloud.retail_v2.types.Image]): + Product images for the product. We highly recommend putting + the main image first. + + A maximum of 300 images are allowed. + + Corresponding properties: Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + audience (google.cloud.retail_v2.types.Audience): + The target group associated with a given + audience (e.g. male, veterans, car owners, + musicians, etc.) of the product. + color_info (google.cloud.retail_v2.types.ColorInfo): + The color of the product. + + Corresponding properties: Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + sizes (Sequence[str]): + The size of the product. To represent different size systems + or size types, consider using this format: + [[[size_system:]size_type:]size_value]. + + For example, in "US:MENS:M", "US" represents size system; + "MENS" represents size type; "M" represents size value. In + "GIRLS:27", size system is empty; "GIRLS" represents size + type; "27" represents size value. In "32 inches", both size + system and size type are empty, while size value is "32 + inches". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2.Product]. Each value must + be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `size `__, + `size_type `__, + and + `size_system `__. + Schema.org property + `Product.size `__. + materials (Sequence[str]): + The material of the product. For example, "leather", + "wooden". + + A maximum of 20 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 200 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `material `__. + Schema.org property + `Product.material `__. + patterns (Sequence[str]): + The pattern or graphic print of the product. For example, + "striped", "polka dot", "paisley". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2.Product]. Each value must + be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `pattern `__. + Schema.org property + `Product.pattern `__. + conditions (Sequence[str]): + The condition of the product. Strongly encouraged to use the + standard values: "new", "refurbished", "used". + + A maximum of 1 value is allowed per + [Product][google.cloud.retail.v2.Product]. Each value must + be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `condition `__. + Schema.org property + `Offer.itemCondition `__. + promotions (Sequence[google.cloud.retail_v2.types.Promotion]): + The promotions applied to the product. A maximum of 10 + values are allowed per + [Product][google.cloud.retail.v2.Product]. Only + [Promotion.promotion_id][google.cloud.retail.v2.Promotion.promotion_id] + will be used, other fields will be ignored if set. + publish_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the product is published by the retailer + for the first time, which indicates the freshness of the + products. Note that this field is different from + [available_time][google.cloud.retail.v2.Product.available_time], + given it purely describes product freshness regardless of + when it is available on search and recommendation. + retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the + [Product][google.cloud.retail.v2.Product]s are returned in + [SearchResponse][google.cloud.retail.v2.SearchResponse]. + + Supported fields for all + [type][google.cloud.retail.v2.Product.type]s: + + - [audience][google.cloud.retail.v2.Product.audience] + - [availability][google.cloud.retail.v2.Product.availability] + - [brands][google.cloud.retail.v2.Product.brands] + - [color_info][google.cloud.retail.v2.Product.color_info] + - [conditions][google.cloud.retail.v2.Product.conditions] + - [gtin][google.cloud.retail.v2.Product.gtin] + - [materials][google.cloud.retail.v2.Product.materials] + - [name][google.cloud.retail.v2.Product.name] + - [patterns][google.cloud.retail.v2.Product.patterns] + - [price_info][google.cloud.retail.v2.Product.price_info] + - [rating][google.cloud.retail.v2.Product.rating] + - [sizes][google.cloud.retail.v2.Product.sizes] + - [title][google.cloud.retail.v2.Product.title] + - [uri][google.cloud.retail.v2.Product.uri] + + Supported fields only for + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]: + + - [categories][google.cloud.retail.v2.Product.categories] + - [description][google.cloud.retail.v2.Product.description] + - [images][google.cloud.retail.v2.Product.images] + + Supported fields only for + [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT]: + + - Only the first image in + [images][google.cloud.retail.v2.Product.images] + + To mark + [attributes][google.cloud.retail.v2.Product.attributes] as + retrievable, include paths of the form "attributes.key" + where "key" is the key of a custom attribute, as specified + in [attributes][google.cloud.retail.v2.Product.attributes]. + + For + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION], + the following fields are always returned in + [SearchResponse][google.cloud.retail.v2.SearchResponse] by + default: + + - [name][google.cloud.retail.v2.Product.name] + + For + [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT], + the following fields are always returned in by default: + + - [name][google.cloud.retail.v2.Product.name] + - [color_info][google.cloud.retail.v2.Product.color_info] + + The maximum number of paths is 30. Otherwise, an + INVALID_ARGUMENT error is returned. + + Note: Returning more fields in + [SearchResponse][google.cloud.retail.v2.SearchResponse] can + increase response payload size and serving latency. + variants (Sequence[google.cloud.retail_v2.types.Product]): + Output only. Product variants grouped together on primary + product which share similar product attributes. It's + automatically grouped by + [primary_product_id][google.cloud.retail.v2.Product.primary_product_id] + for all the product variants. Only populated for + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]. + Do not set this field in API requests. + """ + class Type(proto.Enum): + r"""The type of this product.""" + TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + VARIANT = 2 + COLLECTION = 3 + + class Availability(proto.Enum): + r"""Product availability. If this field is unspecified, the + product is assumed to be in stock. + """ + AVAILABILITY_UNSPECIFIED = 0 + IN_STOCK = 1 + OUT_OF_STOCK = 2 + PREORDER = 3 + BACKORDER = 4 + + expire_time = proto.Field( + proto.MESSAGE, + number=16, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl = proto.Field( + proto.MESSAGE, + number=17, + oneof='expiration', + message=duration_pb2.Duration, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + type_ = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + primary_product_id = proto.Field( + proto.STRING, + number=4, + ) + collection_member_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + gtin = proto.Field( + proto.STRING, + number=6, + ) + categories = proto.RepeatedField( + proto.STRING, + number=7, + ) + title = proto.Field( + proto.STRING, + number=8, + ) + brands = proto.RepeatedField( + proto.STRING, + number=9, + ) + description = proto.Field( + proto.STRING, + number=10, + ) + language_code = proto.Field( + proto.STRING, + number=11, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message=common.CustomAttribute, + ) + tags = proto.RepeatedField( + proto.STRING, + number=13, + ) + price_info = proto.Field( + proto.MESSAGE, + number=14, + message=common.PriceInfo, + ) + rating = proto.Field( + proto.MESSAGE, + number=15, + message=common.Rating, + ) + available_time = proto.Field( + proto.MESSAGE, + number=18, + message=timestamp_pb2.Timestamp, + ) + availability = proto.Field( + proto.ENUM, + number=19, + enum=Availability, + ) + available_quantity = proto.Field( + proto.MESSAGE, + number=20, + message=wrappers_pb2.Int32Value, + ) + fulfillment_info = proto.RepeatedField( + proto.MESSAGE, + number=21, + message=common.FulfillmentInfo, + ) + uri = proto.Field( + proto.STRING, + number=22, + ) + images = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=common.Image, + ) + audience = proto.Field( + proto.MESSAGE, + number=24, + message=common.Audience, + ) + color_info = proto.Field( + proto.MESSAGE, + number=25, + message=common.ColorInfo, + ) + sizes = proto.RepeatedField( + proto.STRING, + number=26, + ) + materials = proto.RepeatedField( + proto.STRING, + number=27, + ) + patterns = proto.RepeatedField( + proto.STRING, + number=28, + ) + conditions = proto.RepeatedField( + proto.STRING, + number=29, + ) + promotions = proto.RepeatedField( + proto.MESSAGE, + number=34, + message=promotion.Promotion, + ) + publish_time = proto.Field( + proto.MESSAGE, + number=33, + message=timestamp_pb2.Timestamp, + ) + retrievable_fields = proto.Field( + proto.MESSAGE, + number=30, + message=field_mask_pb2.FieldMask, + ) + variants = proto.RepeatedField( + proto.MESSAGE, + number=31, + message='Product', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py new file mode 100644 index 00000000..ce4d5c3e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py @@ -0,0 +1,858 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'CreateProductRequest', + 'GetProductRequest', + 'UpdateProductRequest', + 'DeleteProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'SetInventoryRequest', + 'SetInventoryMetadata', + 'SetInventoryResponse', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesResponse', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesResponse', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesResponse', + }, +) + + +class CreateProductRequest(proto.Message): + r"""Request message for [CreateProduct][] method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + product (google.cloud.retail_v2.types.Product): + Required. The [Product][google.cloud.retail.v2.Product] to + create. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2.Product], which will become + the final component of the + [Product.name][google.cloud.retail.v2.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2.Product]s with the same + [parent][google.cloud.retail.v2.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + product_id = proto.Field( + proto.STRING, + number=3, + ) + + +class GetProductRequest(proto.Message): + r"""Request message for [GetProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested [Product][google.cloud.retail.v2.Product] + does not exist, a NOT_FOUND error is returned. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateProductRequest(proto.Message): + r"""Request message for [UpdateProduct][] method. + + Attributes: + product (google.cloud.retail_v2.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to update + does not exist and + [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Product][google.cloud.retail.v2.Product] to update. The + immutable and output only fields are NOT supported. If not + set, all supported fields (the fields that are neither + immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + The attribute key can be updated by setting the mask path as + "attributes.${key_name}". If a key name is present in the + mask but not in the patching product from the request, this + key will be deleted after the update. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, a + new [Product][google.cloud.retail.v2.Product] will be + created. In this situation, ``update_mask`` is ignored. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteProductRequest(proto.Message): + r"""Request message for [DeleteProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to delete + does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2.Product] to delete can + neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] with more than one + [variants][google.cloud.retail.v2.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2.Product] will be deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProductsRequest(proto.Message): + r"""Request message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list products + under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2.Product]s under this + branch, regardless of whether or not this branch exists, a + PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of [Product][google.cloud.retail.v2.Product]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 + [ListProductsResponse.next_page_token][google.cloud.retail.v2.ListProductsResponse.next_page_token], + received from a previous + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + filter (str): + A filter to apply on the list results. Supported features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2.ListProductsRequest.filter] + is unset. + - List + [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s sharing the + same + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]. For example: + ``primary_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2.Product]s bundled + in a + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product]. For example: + ``collection_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2.Product]s with a + partibular type. For example: ``type = "PRIMARY"`` + ``type = "VARIANT"`` ``type = "COLLECTION"`` + + If the field is unrecognizable, an INVALID_ARGUMENT error is + returned. + + If the specified + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] or + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product] does not exist, a + NOT_FOUND error is returned. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields of [Product][google.cloud.retail.v2.Product] to + return in the responses. If not set or empty, the following + fields are returned: + + - [Product.name][google.cloud.retail.v2.Product.name] + - [Product.id][google.cloud.retail.v2.Product.id] + - [Product.title][google.cloud.retail.v2.Product.title] + - [Product.uri][google.cloud.retail.v2.Product.uri] + - [Product.images][google.cloud.retail.v2.Product.images] + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.brands][google.cloud.retail.v2.Product.brands] + + If "*" is provided, all fields are returned. + [Product.name][google.cloud.retail.v2.Product.name] is + always returned no matter what mask is set. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class ListProductsResponse(proto.Message): + r"""Response message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + + Attributes: + products (Sequence[google.cloud.retail_v2.types.Product]): + The [Product][google.cloud.retail.v2.Product]s. + next_page_token (str): + A token that can be sent as + [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class SetInventoryRequest(proto.Message): + r"""Request message for [SetInventory][] method. + + Attributes: + inventory (google.cloud.retail_v2.types.Product): + Required. The inventory information to update. The allowable + fields to update are: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product] named in + [Product.name][google.cloud.retail.v2.Product.name], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Product][google.cloud.retail.v2.Product] to update + does not have existing inventory information, the provided + inventory information will be inserted. + + If the [Product][google.cloud.retail.v2.Product] to update + has existing inventory information, the provided inventory + information will be merged while respecting the last update + time for each inventory field, using the provided or default + value for + [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of fulfillment + types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear in + [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types have + empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following inventory + fields: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + + If a full overwrite of inventory information while ignoring + timestamps is needed, [UpdateProduct][] should be invoked + instead. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the request is issued, used to + prevent out-of-order updates on inventory fields + with the last update time recorded. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] with name + [Product.name][google.cloud.retail.v2.Product.name] is not + found, the inventory update will still be processed and + retained for at most 1 day until the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + inventory = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + set_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + set_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=4, + ) + + +class SetInventoryMetadata(proto.Message): + r"""Metadata related to the progress of the SetInventory operation. + Currently empty because there is no meaningful metadata populated + from the [SetInventory][] method. + + """ + + +class SetInventoryResponse(proto.Message): + r"""Response of the SetInventoryRequest. Currently empty because there + is no meaningful response populated from the [SetInventory][] + method. + + """ + + +class AddFulfillmentPlacesRequest(proto.Message): + r"""Request message for + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery" to be added for this + [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type]. + Duplicate IDs will be automatically ignored. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If the total number of place IDs exceeds 2000 for this + [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type] + after adding, then the update will be rejected. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, the + fulfillment information will still be processed and retained + for at most 1 day and processed once the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + add_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class AddFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the AddFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + """ + + +class AddFulfillmentPlacesResponse(proto.Message): + r"""Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + """ + + +class AddLocalInventoriesRequest(proto.Message): + r"""Request message for + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + local_inventories (Sequence[google.cloud.retail_v2.types.LocalInventory]): + Required. A list of inventory information at + difference places. Each place is identified by + its place ID. At most 3000 inventories are + allowed per request. + add_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided list of + [LocalInventory][google.cloud.retail.v2.LocalInventory] to + update. The field is updated to the provided value. + + If a field is set while the place does not have a previous + local inventory, the local inventory at that store is + created. + + If a field is set while the value of that field is not + provided, the original field value, if it exists, is + deleted. + + If the mask is not set or set with empty paths, all + inventory fields will be updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory updates are + issued. Used to prevent out-of-order updates on + local inventory fields. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, the + local inventory will still be processed and retained for at + most 1 day and processed once the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + local_inventories = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.LocalInventory, + ) + add_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + add_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=6, + ) + + +class AddLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the AddLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + """ + + +class AddLocalInventoriesResponse(proto.Message): + r"""Response of the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + API. Currently empty because there is no meaningful response + populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + """ + + +class RemoveLocalInventoriesRequest(proto.Message): + r"""Request message for [RemoveLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + place_ids (Sequence[str]): + Required. A list of place IDs to have their + inventory deleted. At most 3000 place IDs are + allowed per request. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory deletions are + issued. Used to prevent out-of-order updates and + deletions on local inventory fields. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, the + local inventory removal request will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class RemoveLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesResponse(proto.Message): + r"""Response of the [RemoveLocalInventories][] API. Currently empty + because there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + + +class RemoveFulfillmentPlacesRequest(proto.Message): + r"""Request message for [RemoveFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][google.cloud.retail.v2.FulfillmentInfo.type]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery", to be removed for this + [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type]. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, the + fulfillment information will still be processed and retained + for at most 1 day and processed once the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class RemoveFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveFulfillmentPlaces][] method. + + """ + + +class RemoveFulfillmentPlacesResponse(proto.Message): + r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty + because there is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py new file mode 100644 index 00000000..e8d80a4e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'Promotion', + }, +) + + +class Promotion(proto.Message): + r"""Promotion information. + + Attributes: + promotion_id (str): + ID of the promotion. For example, "free gift". + + The value must be a UTF-8 encoded string with a length limit + of 128 characters, and match the pattern: + ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or + ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is + returned. + + Google Merchant Center property + `promotion `__. + """ + + promotion_id = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py new file mode 100644 index 00000000..b8159aa6 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + }, +) + + +class PurgeMetadata(proto.Message): + r"""Metadata related to the progress of the Purge operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + """ + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + + Attributes: + parent (str): + Required. The resource name of the catalog under which the + events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}`` + filter (str): + Required. The filter string to specify the events to be + deleted with a length limit of 5,000 characters. Empty + string filter is not allowed. The eligible fields for + filtering are: + + - ``eventType``: Double quoted + [UserEvent.event_type][google.cloud.retail.v2.UserEvent.event_type] + string. + - ``eventTime``: in ISO 8601 "zulu" format. + - ``visitorId``: Double quoted string. Specifying this will + delete all events associated with a visitor. + - ``userId``: Double quoted string. Specifying this will + delete all events associated with a user. + + Examples: + + - Deleting all events in a time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + - Deleting specific eventType in time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + - Deleting all events for a specific visitor: + ``visitorId = "visitor1024"`` + + The filtering fields are assumed to have an implicit AND. + force (bool): + Actually perform the purge. If ``force`` is set to false, + the method will return the expected purge count without + deleting any user events. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsResponse(proto.Message): + r"""Response of the PurgeUserEventsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purged_events_count (int): + The total count of events purged as a result + of the operation. + """ + + purged_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py new file mode 100644 index 00000000..e6274278 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py @@ -0,0 +1,1150 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'SearchRequest', + 'SearchResponse', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + + Attributes: + placement (str): + Required. The resource name of the search engine placement, + such as + ``projects/*/locations/global/catalogs/default_catalog/placements/default_search``. + This field is used to identify the serving configuration + name and the set of models that will be used to make the + search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + + Use "default_branch" as the branch ID or leave this field + empty, to search products under the default branch. + query (str): + Raw search query. + + If this field is empty, the request is considered a category + browsing request and returned results are based on + [filter][google.cloud.retail.v2.SearchRequest.filter] and + [page_categories][google.cloud.retail.v2.SearchRequest.page_categories]. + visitor_id (str): + Required. A unique identifier for tracking visitors. For + example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + This should be the same identifier as + [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2.types.UserInfo): + User information. + page_size (int): + Maximum number of [Product][google.cloud.retail.v2.Product]s + to return. If unspecified, defaults to a reasonable value. + The maximum allowed value is 120. Values above 120 will be + coerced to 120. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [SearchResponse.next_page_token][google.cloud.retail.v2.SearchResponse.next_page_token], + received from a previous + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Product][google.cloud.retail.v2.Product]s deemed by the API + as relevant) in search results. This field is only + considered if + [page_token][google.cloud.retail.v2.SearchRequest.page_token] + is unset. + + If this field is negative, an INVALID_ARGUMENT is returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. Filter expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + canonical_filter (str): + The default filter that is applied when a user performs a + search without checking any filters on the search page. + + The filter applied to every search request when quality + improvement such as query expansion is needed. For example, + if a query does not have enough results, an expanded query + with + [SearchRequest.canonical_filter][google.cloud.retail.v2.SearchRequest.canonical_filter] + will be returned as a supplement of the original query. This + field is strongly recommended to achieve high search + quality. + + See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] + for more details about filter syntax. + order_by (str): + The order in which products are returned. Products can be + ordered by a field in an + [Product][google.cloud.retail.v2.Product] object. Leave it + unset if ordered by relevance. OrderBy expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + facet_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + dynamic_facet_spec (google.cloud.retail_v2.types.SearchRequest.DynamicFacetSpec): + Deprecated. Refer to + https://cloud.google.com/retail/docs/configs#dynamic + to enable dynamic facets. Do not set this field. + The specification for dynamically generated + facets. Notice that only textual facets can be + dynamically generated. + boost_spec (google.cloud.retail_v2.types.SearchRequest.BoostSpec): + Boost specification to boost certain products. See more + details at this `user + guide `__. + + Notice that if both [ServingConfig.boost_control_ids][] and + [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] + are set, the boost conditions from both places are + evaluated. If a search request matches multiple boost + conditions, the final boost score is equal to the sum of the + boost scores from all matched boost conditions. + query_expansion_spec (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that specifies the + conditions under which query expansion will occur. See more + details at this `user + guide `__. + variant_rollup_keys (Sequence[str]): + The keys to fetch and rollup the matching + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s attributes, + [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo] or + [LocalInventory][google.cloud.retail.v2.LocalInventory]s + attributes. The attributes from all the matching + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s or + [LocalInventory][google.cloud.retail.v2.LocalInventory]s are + merged and de-duplicated. Notice that rollup attributes will + lead to extra query latency. Maximum number of keys is 30. + + For + [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], a + fulfillment type and a fulfillment ID must be provided in + the format of "fulfillmentType.fulfillmentId". E.g., in + "pickupInStore.store123", "pickupInStore" is fulfillment + type and "store123" is the store ID. + + Supported keys are: + + - colorFamilies + - price + - originalPrice + - discount + - variantId + - inventory(place_id,price) + - inventory(place_id,original_price) + - inventory(place_id,attributes.key), where key is any key + in the + [Product.local_inventories.attributes][google.cloud.retail.v2.LocalInventory.attributes] + map. + - attributes.key, where key is any key in the + [Product.attributes][google.cloud.retail.v2.Product.attributes] + map. + - pickupInStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "pickup-in-store". + - shipToStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "ship-to-store". + - sameDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "same-day-delivery". + - nextDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "next-day-delivery". + - customFulfillment1.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-1". + - customFulfillment2.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-2". + - customFulfillment3.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-3". + - customFulfillment4.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-4". + - customFulfillment5.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-5". + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. Required for + category navigation queries to achieve good search quality. + The format should be the same as + [UserEvent.page_categories][google.cloud.retail.v2.UserEvent.page_categories]; + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + search_mode (google.cloud.retail_v2.types.SearchRequest.SearchMode): + The search mode of the search request. If not + specified, a single search request triggers both + product search and faceted search. + personalization_spec (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec): + The specification for personalization. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + spell_correction_spec (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec): + The spell correction specification that + specifies the mode under which spell correction + will take effect. + + This field is a member of `oneof`_ ``_spell_correction_spec``. + """ + class SearchMode(proto.Enum): + r"""The search mode of each search request.""" + SEARCH_MODE_UNSPECIFIED = 0 + PRODUCT_SEARCH_ONLY = 1 + FACETED_SEARCH_ONLY = 2 + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.retail_v2.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum of facet values that should be returned for this + facet. If unspecified, defaults to 20. The maximum allowed + value is 300. Values above 300 will be coerced to 300. + + If this field is negative, an INVALID_ARGUMENT is returned. + excluded_filter_keys (Sequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + Listing a facet key in this field allows its values to + appear as facet results, even when they are filtered out of + search results. Using this field does not affect what search + results are returned. + + For example, suppose there are 100 products with the color + facet "Red" and 200 products with the color facet "Blue". A + query containing the filter "colorFamilies:ANY("Red")" and + having "colorFamilies" as + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + would by default return only "Red" products in the search + results, and also return "Red" with count 100 as the only + color facet. Although there are also blue products + available, "Blue" would not be shown as an available facet + value. + + If "colorFamilies" is listed in "excludedFilterKeys", then + the query returns the facet values "Red" with count 100 and + "Blue" with count 200, because the "colorFamilies" key is + now excluded from the filter. Because this field doesn't + affect search results, the search results are still + correctly filtered to return only "Red" products. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined by Google Retail Search. It will be ordered + together with dynamic facets if dynamic facets is enabled. + If set to false, the position of this facet in the response + will be the same as in the request, and it will be ranked + before the facets with dynamic position enable and all + dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response will be determined by Google Retail + Search. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enable, which will + generate a facet 'gender'. Then the final order of the + facets in the response can be ("price", "brands", "rating", + "gender") or ("price", "brands", "gender", "rating") depends + on how Google Retail Search orders "gender" and "rating" + facets. However, notice that "price" and "brands" will + always be ranked at 1st and 2nd position since their + enable_dynamic_position are false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Product][google.cloud.retail.v2.Product] object, over which + the facet values are computed. Facet key is case-sensitive. + + Allowed facet keys when + [FacetKey.query][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.query] + is not specified: + + - textual_field = + + - "brands" + - "categories" + - "genders" + - "ageGroups" + - "availability" + - "colorFamilies" + - "colors" + - "sizes" + - "materials" + - "patterns" + - "conditions" + - "attributes.key" + - "pickupInStore" + - "shipToStore" + - "sameDayDelivery" + - "nextDayDelivery" + - "customFulfillment1" + - "customFulfillment2" + - "customFulfillment3" + - "customFulfillment4" + - "customFulfillment5" + - "inventory(place_id,attributes.key)" + + - numerical_field = + + - "price" + - "discount" + - "rating" + - "ratingCount" + - "attributes.key" + - "inventory(place_id,price)" + - "inventory(place_id,original_price)" + - "inventory(place_id,attributes.key)". + intervals (Sequence[google.cloud.retail_v2.types.Interval]): + Set only if values should be bucketized into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (Sequence[str]): + Only get facet for the given restricted values. For example, + when using "pickupInStore" as key and set restricted values + to ["store123", "store456"], only facets for "store123" and + "store456" are returned. Only supported on predefined + textual fields, custom textual attributes and fulfillments. + Maximum is 20. + + Must be set for the fulfillment facet keys: + + - pickupInStore + + - shipToStore + + - sameDayDelivery + + - nextDayDelivery + + - customFulfillment1 + + - customFulfillment2 + + - customFulfillment3 + + - customFulfillment4 + + - customFulfillment5 + prefixes (Sequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "categories" has three values "Women > Shoe", + "Women > Dress" and "Men > Shoe". If set + "prefixes" to "Women", the "categories" facet + will give only "Women > Shoe" and "Women > + Dress". Only supported on textual fields. + Maximum is 10. + contains (Sequence[str]): + Only get facet values that contains the given + strings. For example, suppose "categories" has + three values "Women > Shoe", "Women > Dress" and + "Men > Shoe". If set "contains" to "Shoe", the + "categories" facet will give only "Women > Shoe" + and "Men > Shoe". Only supported on textual + fields. Maximum is 10. + order_by (str): + The order in which [Facet.values][] are returned. + + Allowed values are: + + - "count desc", which means order by + [Facet.FacetValue.count][] descending. + + - "value desc", which means order by + [Facet.FacetValue.value][] descending. Only applies to + textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.intervals]; + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + are sorted in the order given by + [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.restricted_values]. + query (str): + The query that is used to compute facet for the given facet + key. When provided, it will override the default behavior of + facet computation. The query syntax is the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] + for detail syntax and limitations. Notice that there is no + limitation on + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + when query is specified. + + In the response, [FacetValue.value][] will be always "1" and + [FacetValue.count][] will be the number of results that + matches the query. + + For example, you can set a customized facet for + "shipToStore", where + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + is "customizedShipToStore", and + [FacetKey.query][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.query] + is "availability: ANY("IN_STOCK") AND shipToStore: + ANY("123")". Then the facet will count the products that are + both in stock and ship to store "123". + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + intervals = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes = proto.RepeatedField( + proto.STRING, + number=8, + ) + contains = proto.RepeatedField( + proto.STRING, + number=9, + ) + order_by = proto.Field( + proto.STRING, + number=4, + ) + query = proto.Field( + proto.STRING, + number=5, + ) + + facet_key = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.FacetSpec.FacetKey', + ) + limit = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position = proto.Field( + proto.BOOL, + number=4, + ) + + class DynamicFacetSpec(proto.Message): + r"""The specifications of dynamically generated facets. + + Attributes: + mode (google.cloud.retail_v2.types.SearchRequest.DynamicFacetSpec.Mode): + Mode of the DynamicFacet feature. Defaults to + [Mode.DISABLED][google.cloud.retail.v2.SearchRequest.DynamicFacetSpec.Mode.DISABLED] + if it's unset. + """ + class Mode(proto.Enum): + r"""Enum to control DynamicFacet mode""" + MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.DynamicFacetSpec.Mode', + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain items. + + Attributes: + condition_boost_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a product + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 20. + skip_boost_spec_validation (bool): + Whether to skip boostspec validation. If this field is set + to true, invalid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] + will be ignored and valid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] + will still be applied. + + This field is a member of `oneof`_ ``_skip_boost_spec_validation``. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to products which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": + + - (id: ANY("product_1", "product_2")) AND + (colorFamilies: ANY("Red","Blue")) + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition = proto.Field( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + skip_boost_spec_validation = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.retail.v2.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 3 + + condition = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.QueryExpansionSpec.Condition', + ) + pin_unexpanded_results = proto.Field( + proto.BOOL, + number=2, + ) + + class PersonalizationSpec(proto.Message): + r"""The specification for personalization. + + Attributes: + mode (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec.Mode): + Defaults to + [Mode.AUTO][google.cloud.retail.v2.SearchRequest.PersonalizationSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""The personalization mode of each search request.""" + MODE_UNSPECIFIED = 0 + AUTO = 1 + DISABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.PersonalizationSpec.Mode', + ) + + class SpellCorrectionSpec(proto.Message): + r"""The specification for query spell correction. + + Attributes: + mode (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec.Mode): + The mode under which spell correction should take effect to + replace the original search query. Default to + [Mode.AUTO][google.cloud.retail.v2.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""Enum describing under which mode spell correction should + occur. + """ + MODE_UNSPECIFIED = 0 + SUGGESTION_ONLY = 1 + AUTO = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.SpellCorrectionSpec.Mode', + ) + + placement = proto.Field( + proto.STRING, + number=1, + ) + branch = proto.Field( + proto.STRING, + number=2, + ) + query = proto.Field( + proto.STRING, + number=3, + ) + visitor_id = proto.Field( + proto.STRING, + number=4, + ) + user_info = proto.Field( + proto.MESSAGE, + number=5, + message=common.UserInfo, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + offset = proto.Field( + proto.INT32, + number=9, + ) + filter = proto.Field( + proto.STRING, + number=10, + ) + canonical_filter = proto.Field( + proto.STRING, + number=28, + ) + order_by = proto.Field( + proto.STRING, + number=11, + ) + facet_specs = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=FacetSpec, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=21, + message=DynamicFacetSpec, + ) + boost_spec = proto.Field( + proto.MESSAGE, + number=13, + message=BoostSpec, + ) + query_expansion_spec = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionSpec, + ) + variant_rollup_keys = proto.RepeatedField( + proto.STRING, + number=17, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=23, + ) + search_mode = proto.Field( + proto.ENUM, + number=31, + enum=SearchMode, + ) + personalization_spec = proto.Field( + proto.MESSAGE, + number=32, + message=PersonalizationSpec, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=34, + ) + spell_correction_spec = proto.Field( + proto.MESSAGE, + number=35, + optional=True, + message=SpellCorrectionSpec, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + + Attributes: + results (Sequence[google.cloud.retail_v2.types.SearchResponse.SearchResult]): + A list of matched items. The order represents + the ranking. + facets (Sequence[google.cloud.retail_v2.types.SearchResponse.Facet]): + Results of facets requested by user. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.retail.v2.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.retail.v2.SearchResponse.total_size] + that matches. + corrected_query (str): + Contains the spell corrected query, if found. If the spell + correction type is AUTOMATIC, then the search results are + based on corrected_query. Otherwise the original query will + be used for search. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting + from this search, which enables accurate attribution of + search model performance. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.retail.v2.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + query_expansion_info (google.cloud.retail_v2.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search is performed, and only + [redirect_uri][google.cloud.retail.v2.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] + are set in the response. + applied_controls (Sequence[str]): + The fully qualified resource name of applied + `controls `__. + invalid_condition_boost_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + The invalid + [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] + that are not applied during serving. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Product.id][google.cloud.retail.v2.Product.id] of the + searched [Product][google.cloud.retail.v2.Product]. + product (google.cloud.retail_v2.types.Product): + The product data snippet in the search response. Only + [Product.name][google.cloud.retail.v2.Product.name] is + guaranteed to be populated. + + [Product.variants][google.cloud.retail.v2.Product.variants] + contains the product variants that match the search query. + If there are multiple product variants matching the query, + top 5 most relevant product variants are returned and + ordered by relevancy. + + If relevancy can be deternmined, use + [matching_variant_fields][google.cloud.retail.v2.SearchResponse.SearchResult.matching_variant_fields] + to look up matched product variants fields. If relevancy + cannot be determined, e.g. when searching "shoe" all + products in a shoe product can be a match, 5 product + variants are returned but order is meaningless. + matching_variant_count (int): + The count of matched + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s. + matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): + If a [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] matches the search + query, this map indicates which + [Product][google.cloud.retail.v2.Product] fields are + matched. The key is the + [Product.name][google.cloud.retail.v2.Product.name], the + value is a field mask of the matched + [Product][google.cloud.retail.v2.Product] fields. If matched + attributes cannot be determined, this map will be empty. + + For example, a key "sku1" with field mask + "products.color_info" indicates there is a match between + "sku1" [ColorInfo][google.cloud.retail.v2.ColorInfo] and the + query. + variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): + The rollup matching + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] attributes. The + key is one of the + [SearchRequest.variant_rollup_keys][google.cloud.retail.v2.SearchRequest.variant_rollup_keys]. + The values are the merged and de-duplicated + [Product][google.cloud.retail.v2.Product] attributes. Notice + that the rollup values are respect filter. For example, when + filtering by "colorFamilies:ANY("red")" and rollup + "colorFamilies", only "red" is returned. + + For textual and numerical attributes, the rollup values is a + list of string or double values with type + [google.protobuf.ListValue][google.protobuf.ListValue]. For + example, if there are two variants with colors "red" and + "blue", the rollup values are + + :: + + { key: "colorFamilies" + value { + list_value { + values { string_value: "red" } + values { string_value: "blue" } + } + } + } + + For + [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], + the rollup values is a double value with type + [google.protobuf.Value][google.protobuf.Value]. For example, + ``{key: "pickupInStore.store1" value { number_value: 10 }}`` + means a there are 10 variants in this product are available + in the store "store1". + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + matching_variant_count = proto.Field( + proto.INT32, + number=3, + ) + matching_variant_fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + variant_rollup_values = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. E.g., "colorFamilies" + or "price" or "attributes.attr1". + values (Sequence[google.cloud.retail_v2.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Text value of a facet, such as "Black" for + facet "colorFamilies". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.retail_v2.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value = proto.Field( + proto.STRING, + number=1, + oneof='facet_value', + ) + interval = proto.Field( + proto.MESSAGE, + number=2, + oneof='facet_value', + message=common.Interval, + ) + count = proto.Field( + proto.INT64, + number=3, + ) + + key = proto.Field( + proto.STRING, + number=1, + ) + values = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SearchResponse.Facet.FacetValue', + ) + dynamic_facet = proto.Field( + proto.BOOL, + number=3, + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count = proto.Field( + proto.INT64, + number=2, + ) + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + corrected_query = proto.Field( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + next_page_token = proto.Field( + proto.STRING, + number=6, + ) + query_expansion_info = proto.Field( + proto.MESSAGE, + number=7, + message=QueryExpansionInfo, + ) + redirect_uri = proto.Field( + proto.STRING, + number=10, + ) + applied_controls = proto.RepeatedField( + proto.STRING, + number=12, + ) + invalid_condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py new file mode 100644 index 00000000..0d6b6823 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py @@ -0,0 +1,508 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import product as gcr_product +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'UserEvent', + 'ProductDetail', + 'CompletionDetail', + 'PurchaseTransaction', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Retail API needs + to know about how end users interact with customers' website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + - ``add-to-cart``: Products being added to cart. + - ``category-page-view``: Special pages such as sale or + promotion pages viewed. + - ``detail-page-view``: Products detail page viewed. + - ``home-page-view``: Homepage viewed. + - ``promotion-offered``: Promotion is offered to a user. + - ``promotion-not-offered``: Promotion is not offered to a + user. + - ``purchase-complete``: User finishing a purchase. + - ``search``: Product search. + - ``shopping-cart-page-view``: User viewing a shopping + cart. + visitor_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + Don't set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + The field should not contain PII or user-data. We recommend + to use Google Analytics `Client + ID `__ + for this field. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the sesion_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add visitor_id as prefix. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.retail.v2.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + experiment_ids (Sequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups + (e.g. using Retail API, using different + recommendation models). + attribution_token (str): + Highly recommended for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]. + This field enables accurate attribution of recommendation + model performance. + + The value must be a valid + [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] + for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]. + The value must be a valid + [SearchResponse.attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] + for user events that are the result of + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + + This token enables us to accurately attribute page view or + purchase back to the event and the particular predict + response containing this clicked/purchased product. If user + clicks on product K in the recommendation results, pass + [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] + as a URL parameter to product K's page. When recording + events on product K's page, log the + [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] + to this field. + product_details (Sequence[google.cloud.retail_v2.types.ProductDetail]): + The main product details related to the event. + + This field is optional except for the following event types: + + - ``add-to-cart`` + - ``detail-page-view`` + - ``purchase-complete`` + + In a ``search`` event, this field represents the products + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [product_details][google.cloud.retail.v2.UserEvent.product_details] + is desired. The end user may have not finished browsing the + whole page yet. + completion_detail (google.cloud.retail_v2.types.CompletionDetail): + The main auto-completion details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Retail API use those + custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - The key must be a UTF-8 encoded string with a length + limit of 5,000 characters. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a UTF-8 + encoded string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is traffic_channel, which is how a user arrives + at the site. Users can arrive at the site by coming to the + site directly, coming through Google search, or in other + ways. + cart_id (str): + The ID or name of the associated shopping cart. This ID is + used to associate multiple items added or present in the + cart before purchase. + + This can only be set for ``add-to-cart``, + ``purchase-complete``, or ``shopping-cart-page-view`` + events. + purchase_transaction (google.cloud.retail_v2.types.PurchaseTransaction): + A transaction represents the entire purchase transaction. + + Required for ``purchase-complete`` events. Other event types + should not set this field. Otherwise, an INVALID_ARGUMENT + error is returned. + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.retail.v2.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + At least one of + [search_query][google.cloud.retail.v2.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. + + See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + order_by (str): + The order in which products are returned. + + See + [SearchRequest.order_by][google.cloud.retail.v2.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.retail.v2.SearchRequest.offset] + for definition. + + If this field is negative, an INVALID_ARGUMENT is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + + Required for ``category-page-view`` events. At least one of + [search_query][google.cloud.retail.v2.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2.types.UserInfo): + User information. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. + page_view_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageViewId`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + """ + + event_type = proto.Field( + proto.STRING, + number=1, + ) + visitor_id = proto.Field( + proto.STRING, + number=2, + ) + session_id = proto.Field( + proto.STRING, + number=21, + ) + event_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + experiment_ids = proto.RepeatedField( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + product_details = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ProductDetail', + ) + completion_detail = proto.Field( + proto.MESSAGE, + number=22, + message='CompletionDetail', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=common.CustomAttribute, + ) + cart_id = proto.Field( + proto.STRING, + number=8, + ) + purchase_transaction = proto.Field( + proto.MESSAGE, + number=9, + message='PurchaseTransaction', + ) + search_query = proto.Field( + proto.STRING, + number=10, + ) + filter = proto.Field( + proto.STRING, + number=16, + ) + order_by = proto.Field( + proto.STRING, + number=17, + ) + offset = proto.Field( + proto.INT32, + number=18, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=11, + ) + user_info = proto.Field( + proto.MESSAGE, + number=12, + message=common.UserInfo, + ) + uri = proto.Field( + proto.STRING, + number=13, + ) + referrer_uri = proto.Field( + proto.STRING, + number=14, + ) + page_view_id = proto.Field( + proto.STRING, + number=15, + ) + + +class ProductDetail(proto.Message): + r"""Detailed product information associated with a user event. + + Attributes: + product (google.cloud.retail_v2.types.Product): + Required. [Product][google.cloud.retail.v2.Product] + information. + + Required field(s): + + - [Product.id][google.cloud.retail.v2.Product.id] + + Optional override field(s): + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + + If any supported optional fields are provided, we will treat + them as a full override when looking up product information + from the catalog. Thus, it is important to ensure that the + overriding fields are accurate and complete. + + All other product fields are ignored and instead populated + via catalog lookup after event ingestion. + quantity (google.protobuf.wrappers_pb2.Int32Value): + Quantity of the product associated with the user event. + + For example, this field will be 2 if two products are added + to the shopping cart for ``purchase-complete`` event. + Required for ``add-to-cart`` and ``purchase-complete`` event + types. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + quantity = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +class CompletionDetail(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + completion_attribution_token (str): + Completion attribution token in + [CompleteQueryResponse.attribution_token][google.cloud.retail.v2.CompleteQueryResponse.attribution_token]. + selected_suggestion (str): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2.CompleteQueryResponse.CompletionResult.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2.CompleteQueryResponse.CompletionResult.suggestion] + position, starting from 0. + """ + + completion_attribution_token = proto.Field( + proto.STRING, + number=1, + ) + selected_suggestion = proto.Field( + proto.STRING, + number=2, + ) + selected_position = proto.Field( + proto.INT32, + number=3, + ) + + +class PurchaseTransaction(proto.Message): + r"""A transaction represents the entire purchase transaction. + + Attributes: + id (str): + The transaction ID with a length limit of 128 + characters. + revenue (float): + Required. Total non-zero revenue or grand + total associated with the transaction. This + value include shipping, tax, or other + adjustments to total revenue that you want to + include as part of your revenue calculations. + tax (float): + All the taxes associated with the + transaction. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [revenue][google.cloud.retail.v2.PurchaseTransaction.revenue] + - [tax][google.cloud.retail.v2.PurchaseTransaction.tax] - + [cost][google.cloud.retail.v2.PurchaseTransaction.cost] + currency_code (str): + Required. Currency code. Use three-character + ISO-4217 code. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + revenue = proto.Field( + proto.FLOAT, + number=2, + ) + tax = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + currency_code = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py new file mode 100644 index 00000000..fcfc46d7 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import user_event as gcr_user_event + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'WriteUserEventRequest', + 'CollectUserEventRequest', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'RejoinUserEventsMetadata', + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (google.cloud.retail_v2.types.UserEvent): + Required. User event to write. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for 3rd party requests. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.STRING, + number=2, + ) + uri = proto.Field( + proto.STRING, + number=3, + ) + ets = proto.Field( + proto.INT64, + number=4, + ) + + +class RejoinUserEventsRequest(proto.Message): + r"""Request message for RejoinUserEvents method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event_rejoin_scope (google.cloud.retail_v2.types.RejoinUserEventsRequest.UserEventRejoinScope): + The type of the user event rejoin to define the scope and + range of the user events to be rejoined with the latest + product catalog. Defaults to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not + set, or set to an invalid integer value. + """ + class UserEventRejoinScope(proto.Enum): + r"""The scope of user events to be rejoined with the latest product + catalog. If the rejoining aims at reducing number of unjoined + events, set UserEventRejoinScope to UNJOINED_EVENTS. If the + rejoining aims at correcting product catalog information in joined + events, set UserEventRejoinScope to JOINED_EVENTS. If all events + needs to be rejoined, set UserEventRejoinScope to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. + """ + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 + JOINED_EVENTS = 1 + UNJOINED_EVENTS = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event_rejoin_scope = proto.Field( + proto.ENUM, + number=2, + enum=UserEventRejoinScope, + ) + + +class RejoinUserEventsResponse(proto.Message): + r"""Response message for RejoinUserEvents method. + + Attributes: + rejoined_user_events_count (int): + Number of user events that were joined with + latest product catalog. + """ + + rejoined_user_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +class RejoinUserEventsMetadata(proto.Message): + r"""Metadata for RejoinUserEvents method. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py new file mode 100644 index 00000000..e7ab4118 --- /dev/null +++ b/owl-bot-staging/v2/noxfile.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.6", + "3.7", + "3.8", + "3.9", + "3.10", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==19.10b0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.9" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/retail_v2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py new file mode 100644 index 00000000..fb30eae6 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_GetDefaultBranch_async] +from google.cloud import retail_v2 + + +async def sample_get_default_branch(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py new file mode 100644 index 00000000..0af0ece9 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_GetDefaultBranch_sync] +from google.cloud import retail_v2 + + +def sample_get_default_branch(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py new file mode 100644 index 00000000..2a0930de --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_ListCatalogs_async] +from google.cloud import retail_v2 + + +async def sample_list_catalogs(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py new file mode 100644 index 00000000..2671a121 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_ListCatalogs_sync] +from google.cloud import retail_v2 + + +def sample_list_catalogs(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py new file mode 100644 index 00000000..f85e3ed8 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_SetDefaultBranch_async] +from google.cloud import retail_v2 + + +async def sample_set_default_branch(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + +# [END retail_v2_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py new file mode 100644 index 00000000..34371062 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_SetDefaultBranch_sync] +from google.cloud import retail_v2 + + +def sample_set_default_branch(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + +# [END retail_v2_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py new file mode 100644 index 00000000..2a2b3dde --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_UpdateCatalog_async] +from google.cloud import retail_v2 + + +async def sample_update_catalog(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py new file mode 100644 index 00000000..bf721cba --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_UpdateCatalog_sync] +from google.cloud import retail_v2 + + +def sample_update_catalog(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py new file mode 100644 index 00000000..c72ecfdf --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CompletionService_CompleteQuery_async] +from google.cloud import retail_v2 + + +async def sample_complete_query(): + # Create a client + client = retail_v2.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py new file mode 100644 index 00000000..30b10016 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CompletionService_CompleteQuery_sync] +from google.cloud import retail_v2 + + +def sample_complete_query(): + # Create a client + client = retail_v2.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py new file mode 100644 index 00000000..75f45f91 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CompletionService_ImportCompletionData_async] +from google.cloud import retail_v2 + + +async def sample_import_completion_data(): + # Create a client + client = retail_v2.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py new file mode 100644 index 00000000..cc31057e --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CompletionService_ImportCompletionData_sync] +from google.cloud import retail_v2 + + +def sample_import_completion_data(): + # Create a client + client = retail_v2.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py new file mode 100644 index 00000000..f46819c5 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_PredictionService_Predict_async] +from google.cloud import retail_v2 + + +async def sample_predict(): + # Create a client + client = retail_v2.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py new file mode 100644 index 00000000..ad37063f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_PredictionService_Predict_sync] +from google.cloud import retail_v2 + + +def sample_predict(): + # Create a client + client = retail_v2.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py new file mode 100644 index 00000000..ceea2869 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_AddFulfillmentPlaces_async] +from google.cloud import retail_v2 + + +async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py new file mode 100644 index 00000000..1739ec91 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_AddFulfillmentPlaces_sync] +from google.cloud import retail_v2 + + +def sample_add_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py new file mode 100644 index 00000000..6155d5ce --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_AddLocalInventories_async] +from google.cloud import retail_v2 + + +async def sample_add_local_inventories(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py new file mode 100644 index 00000000..b57dce2f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_AddLocalInventories_sync] +from google.cloud import retail_v2 + + +def sample_add_local_inventories(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py new file mode 100644 index 00000000..fe1cb991 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_CreateProduct_async] +from google.cloud import retail_v2 + + +async def sample_create_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py new file mode 100644 index 00000000..9cc154d9 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_CreateProduct_sync] +from google.cloud import retail_v2 + + +def sample_create_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py new file mode 100644 index 00000000..33318da7 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_DeleteProduct_async] +from google.cloud import retail_v2 + + +async def sample_delete_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + +# [END retail_v2_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py new file mode 100644 index 00000000..797690c6 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_DeleteProduct_sync] +from google.cloud import retail_v2 + + +def sample_delete_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + +# [END retail_v2_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py new file mode 100644 index 00000000..32ba279d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_GetProduct_async] +from google.cloud import retail_v2 + + +async def sample_get_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py new file mode 100644 index 00000000..62805768 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_GetProduct_sync] +from google.cloud import retail_v2 + + +def sample_get_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py new file mode 100644 index 00000000..390f0977 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_ImportProducts_async] +from google.cloud import retail_v2 + + +async def sample_import_products(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py new file mode 100644 index 00000000..fcd8c82f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_ImportProducts_sync] +from google.cloud import retail_v2 + + +def sample_import_products(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py new file mode 100644 index 00000000..5e85f948 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_ListProducts_async] +from google.cloud import retail_v2 + + +async def sample_list_products(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py new file mode 100644 index 00000000..30f7fd1f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_ListProducts_sync] +from google.cloud import retail_v2 + + +def sample_list_products(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py new file mode 100644 index 00000000..08172bf4 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async] +from google.cloud import retail_v2 + + +async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py new file mode 100644 index 00000000..37f86ba9 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync] +from google.cloud import retail_v2 + + +def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py new file mode 100644 index 00000000..762dab6d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_RemoveLocalInventories_async] +from google.cloud import retail_v2 + + +async def sample_remove_local_inventories(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py new file mode 100644 index 00000000..7aa52d5d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_RemoveLocalInventories_sync] +from google.cloud import retail_v2 + + +def sample_remove_local_inventories(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py new file mode 100644 index 00000000..62a24100 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_SetInventory_async] +from google.cloud import retail_v2 + + +async def sample_set_inventory(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2.Product() + inventory.title = "title_value" + + request = retail_v2.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py new file mode 100644 index 00000000..aa5a0539 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_SetInventory_sync] +from google.cloud import retail_v2 + + +def sample_set_inventory(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2.Product() + inventory.title = "title_value" + + request = retail_v2.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py new file mode 100644 index 00000000..9ea76295 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_UpdateProduct_async] +from google.cloud import retail_v2 + + +async def sample_update_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py new file mode 100644 index 00000000..866c7e7c --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_UpdateProduct_sync] +from google.cloud import retail_v2 + + +def sample_update_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py new file mode 100644 index 00000000..ddebd9e8 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_SearchService_Search_async] +from google.cloud import retail_v2 + + +async def sample_search(): + # Create a client + client = retail_v2.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py new file mode 100644 index 00000000..fc20bb3d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_SearchService_Search_sync] +from google.cloud import retail_v2 + + +def sample_search(): + # Create a client + client = retail_v2.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 00000000..b8bb6a81 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_CollectUserEvent_async] +from google.cloud import retail_v2 + + +async def sample_collect_user_event(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 00000000..10b302e3 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_CollectUserEvent_sync] +from google.cloud import retail_v2 + + +def sample_collect_user_event(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py new file mode 100644 index 00000000..55ad399a --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_ImportUserEvents_async] +from google.cloud import retail_v2 + + +async def sample_import_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 00000000..835edec6 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_ImportUserEvents_sync] +from google.cloud import retail_v2 + + +def sample_import_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py new file mode 100644 index 00000000..1da1d39d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_PurgeUserEvents_async] +from google.cloud import retail_v2 + + +async def sample_purge_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py new file mode 100644 index 00000000..48814171 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_PurgeUserEvents_sync] +from google.cloud import retail_v2 + + +def sample_purge_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py new file mode 100644 index 00000000..a2617cfe --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_RejoinUserEvents_async] +from google.cloud import retail_v2 + + +async def sample_rejoin_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py new file mode 100644 index 00000000..eb8ed62c --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_RejoinUserEvents_sync] +from google.cloud import retail_v2 + + +def sample_rejoin_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py new file mode 100644 index 00000000..82afc25a --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_WriteUserEvent_async] +from google.cloud import retail_v2 + + +async def sample_write_user_event(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 00000000..62336b25 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_WriteUserEvent_sync] +from google.cloud import retail_v2 + + +def sample_write_user_event(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json new file mode 100644 index 00000000..c6a55bd4 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json @@ -0,0 +1,3826 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.retail.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-cloud-retail" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2_generated_catalog_service_get_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_GetDefaultBranch_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_get_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2_generated_catalog_service_get_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_GetDefaultBranch_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_get_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ListCatalogsRequest" + }, + { + "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.retail_v2.services.catalog_service.pagers.ListCatalogsAsyncPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2_generated_catalog_service_list_catalogs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_ListCatalogs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_list_catalogs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ListCatalogsRequest" + }, + { + "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.retail_v2.services.catalog_service.pagers.ListCatalogsPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2_generated_catalog_service_list_catalogs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_ListCatalogs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_list_catalogs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2_generated_catalog_service_set_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_SetDefaultBranch_async", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_set_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2_generated_catalog_service_set_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_SetDefaultBranch_sync", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_set_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2.types.Catalog" + }, + { + "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.retail_v2.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2_generated_catalog_service_update_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_UpdateCatalog_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_update_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2.types.Catalog" + }, + { + "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.retail_v2.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2_generated_catalog_service_update_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_UpdateCatalog_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_update_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2_generated_completion_service_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CompletionService_CompleteQuery_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_completion_service_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2.CompletionServiceClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2_generated_completion_service_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CompletionService_CompleteQuery_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_completion_service_complete_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2_generated_completion_service_import_completion_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CompletionService_ImportCompletionData_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_completion_service_import_completion_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2.CompletionServiceClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2_generated_completion_service_import_completion_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CompletionService_ImportCompletionData_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_completion_service_import_completion_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.PredictionServiceAsyncClient", + "shortName": "PredictionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.PredictionServiceAsyncClient.predict", + "method": { + "fullName": "google.cloud.retail.v2.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2_generated_prediction_service_predict_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_PredictionService_Predict_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_prediction_service_predict_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.PredictionServiceClient", + "shortName": "PredictionServiceClient" + }, + "fullName": "google.cloud.retail_v2.PredictionServiceClient.predict", + "method": { + "fullName": "google.cloud.retail.v2.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2_generated_prediction_service_predict_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_PredictionService_Predict_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_prediction_service_predict_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2_generated_product_service_add_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_AddFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_add_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2_generated_product_service_add_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_AddFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_add_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2_generated_product_service_add_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_AddLocalInventories_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_add_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2_generated_product_service_add_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_AddLocalInventories_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_add_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "name": "product_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.retail_v2.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2_generated_product_service_create_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_CreateProduct_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_create_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "name": "product_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.retail_v2.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2_generated_product_service_create_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_CreateProduct_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_create_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2_generated_product_service_delete_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_DeleteProduct_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_delete_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2_generated_product_service_delete_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_DeleteProduct_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_delete_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.GetProductRequest" + }, + { + "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.retail_v2.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2_generated_product_service_get_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_GetProduct_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_get_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.GetProductRequest" + }, + { + "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.retail_v2.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2_generated_product_service_get_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_GetProduct_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_get_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2_generated_product_service_import_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_ImportProducts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_import_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2_generated_product_service_import_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_ImportProducts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_import_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ListProductsRequest" + }, + { + "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.retail_v2.services.product_service.pagers.ListProductsAsyncPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2_generated_product_service_list_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_ListProducts_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_list_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ListProductsRequest" + }, + { + "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.retail_v2.services.product_service.pagers.ListProductsPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2_generated_product_service_list_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_ListProducts_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_list_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2_generated_product_service_remove_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_remove_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2_generated_product_service_remove_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_remove_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2_generated_product_service_remove_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_RemoveLocalInventories_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_remove_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2_generated_product_service_remove_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_RemoveLocalInventories_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_remove_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2_generated_product_service_set_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_SetInventory_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_set_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2_generated_product_service_set_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_SetInventory_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_set_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "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.retail_v2.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2_generated_product_service_update_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_UpdateProduct_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_update_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "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.retail_v2.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2_generated_product_service_update_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_UpdateProduct_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_update_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.SearchServiceAsyncClient.search", + "method": { + "fullName": "google.cloud.retail.v2.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2_generated_search_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_SearchService_Search_async", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_search_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.SearchServiceClient", + "shortName": "SearchServiceClient" + }, + "fullName": "google.cloud.retail_v2.SearchServiceClient.search", + "method": { + "fullName": "google.cloud.retail.v2.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.services.search_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2_generated_search_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_SearchService_Search_sync", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_search_service_search_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_CollectUserEvent_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_CollectUserEvent_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_ImportUserEvents_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_ImportUserEvents_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2_generated_user_event_service_purge_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_PurgeUserEvents_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_purge_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2_generated_user_event_service_purge_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_PurgeUserEvents_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_purge_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2_generated_user_event_service_rejoin_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_RejoinUserEvents_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_rejoin_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2_generated_user_event_service_rejoin_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_RejoinUserEvents_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_rejoin_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_WriteUserEvent_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_WriteUserEvent_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py new file mode 100644 index 00000000..9ed9d278 --- /dev/null +++ b/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py @@ -0,0 +1,199 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class retailCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), + 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'delete_product': ('name', ), + 'get_default_branch': ('catalog', ), + 'get_product': ('name', ), + 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), + 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), + 'import_user_events': ('parent', 'input_config', 'errors_config', ), + 'list_catalogs': ('parent', 'page_size', 'page_token', ), + 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', ), + 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), + 'purge_user_events': ('parent', 'filter', 'force', ), + 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), + 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), + 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), + 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', 'labels', 'spell_correction_spec', ), + 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), + 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), + 'update_catalog': ('catalog', 'update_mask', ), + 'update_product': ('product', 'update_mask', 'allow_missing', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=retailCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the retail client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2/setup.py b/owl-bot-staging/v2/setup.py new file mode 100644 index 00000000..1103510b --- /dev/null +++ b/owl-bot-staging/v2/setup.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-retail', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-retail", + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 2.8.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'googleapis-common-protos >= 1.55.0, <2.0.0dev', + 'proto-plus >= 1.19.7', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py new file mode 100644 index 00000000..845e18b6 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py @@ -0,0 +1,2318 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.catalog_service import CatalogServiceAsyncClient +from google.cloud.retail_v2.services.catalog_service import CatalogServiceClient +from google.cloud.retail_v2.services.catalog_service import pagers +from google.cloud.retail_v2.services.catalog_service import transports +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CatalogServiceClient._get_default_mtls_endpoint(None) is None + assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CatalogServiceGrpcTransport, "grpc"), + (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_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", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_catalog_service_client_get_transport_class(): + transport = CatalogServiceClient.get_transport_class() + available_transports = [ + transports.CatalogServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CatalogServiceClient.get_transport_class("grpc") + assert transport == transports.CatalogServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CatalogServiceClient, CatalogServiceAsyncClient +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_catalog_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ListCatalogsRequest, + dict, +]) +def test_list_catalogs(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_catalogs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalogs), + '__call__') as call: + client.list_catalogs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + +@pytest.mark.asyncio +async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_catalogs_async_from_dict(): + await test_list_catalogs_async(request_type=dict) + + +def test_list_catalogs_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = catalog_service.ListCatalogsResponse() + client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_catalogs( + 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_catalogs_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_catalogs_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_catalogs( + 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_catalogs_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + + +def test_list_catalogs_pager(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_catalogs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, catalog.Catalog) + for i in results) +def test_list_catalogs_pages(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = list(client.list_catalogs(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_catalogs_async_pager(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_catalogs(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, catalog.Catalog) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_catalogs_async_pages(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCatalogRequest, + dict, +]) +def test_update_catalog(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + ) + response = client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_catalog_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalog), + '__call__') as call: + client.update_catalog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + +@pytest.mark.asyncio +async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_catalog_async_from_dict(): + await test_update_catalog_async(request_type=dict) + + +def test_update_catalog_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = gcr_catalog.Catalog() + client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_catalog_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +def test_update_catalog_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_catalog_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.SetDefaultBranchRequest, + dict, +]) +def test_set_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_set_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + client.set_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_set_default_branch_async_from_dict(): + await test_set_default_branch_async(request_type=dict) + + +def test_set_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = None + client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_set_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_set_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetDefaultBranchRequest, + dict, +]) +def test_get_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + ) + response = client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +def test_get_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_default_branch), + '__call__') as call: + client.get_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + )) + response = await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +@pytest.mark.asyncio +async def test_get_default_branch_async_from_dict(): + await test_get_default_branch_async(request_type=dict) + + +def test_get_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = catalog_service.GetDefaultBranchResponse() + client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_get_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_get_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CatalogServiceClient.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 = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CatalogServiceGrpcTransport, + ) + +def test_catalog_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_catalog_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_catalogs', + 'update_catalog', + 'set_default_branch', + 'get_default_branch', + ) + 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_catalog_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.retail_v2.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport( + 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_catalog_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.retail_v2.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport() + adc.assert_called_once() + + +def test_catalog_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) + CatalogServiceClient() + 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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +def test_catalog_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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + transports.CatalogServiceRestTransport, + ], +) +def test_catalog_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.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_catalog_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_no_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_with_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_catalog_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcTransport( + 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_catalog_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcAsyncIOTransport( + 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_branch_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = CatalogServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = CatalogServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_branch_path(path) + assert expected == actual + +def test_catalog_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + } + path = CatalogServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CatalogServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = CatalogServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = CatalogServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CatalogServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CatalogServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CatalogServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = CatalogServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CatalogServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CatalogServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CatalogServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py new file mode 100644 index 00000000..f33a4bad --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py @@ -0,0 +1,1502 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.completion_service import CompletionServiceAsyncClient +from google.cloud.retail_v2.services.completion_service import CompletionServiceClient +from google.cloud.retail_v2.services.completion_service import transports +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CompletionServiceClient._get_default_mtls_endpoint(None) is None + assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CompletionServiceGrpcTransport, "grpc"), + (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_completion_service_client_get_transport_class(): + transport = CompletionServiceClient.get_transport_class() + available_transports = [ + transports.CompletionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CompletionServiceClient.get_transport_class("grpc") + assert transport == transports.CompletionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CompletionServiceClient, CompletionServiceAsyncClient +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_completion_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CompletionServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + ) + response = client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +def test_complete_query_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + client.complete_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + +@pytest.mark.asyncio +async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + )) + response = await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +@pytest.mark.asyncio +async def test_complete_query_async_from_dict(): + await test_complete_query_async(request_type=dict) + + +def test_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) + await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportCompletionDataRequest, + dict, +]) +def test_import_completion_data(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_completion_data_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + client.import_completion_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + +@pytest.mark.asyncio +async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_completion_data_async_from_dict(): + await test_import_completion_data_async(request_type=dict) + + +def test_import_completion_data_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # 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_completion_data_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CompletionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CompletionServiceGrpcTransport, + ) + +def test_completion_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_completion_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'complete_query', + 'import_completion_data', + ) + 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_completion_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_completion_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport() + adc.assert_called_once() + + +def test_completion_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CompletionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, + ], +) +def test_completion_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionServiceGrpcTransport, grpc_helpers), + (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_completion_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_no_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_with_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_completion_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_completion_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_completion_service_grpc_lro_client(): + client = CompletionServiceClient( + 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_completion_service_grpc_lro_async_client(): + client = CompletionServiceAsyncClient( + 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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CompletionServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CompletionServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CompletionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CompletionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = CompletionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CompletionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CompletionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CompletionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = CompletionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CompletionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CompletionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CompletionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CompletionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py new file mode 100644 index 00000000..fdbb2eeb --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py @@ -0,0 +1,1330 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.prediction_service import PredictionServiceAsyncClient +from google.cloud.retail_v2.services.prediction_service import PredictionServiceClient +from google.cloud.retail_v2.services.prediction_service import transports +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import prediction_service +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import promotion +from google.cloud.retail_v2.types import user_event +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PredictionServiceClient._get_default_mtls_endpoint(None) is None + assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionServiceGrpcTransport, "grpc"), + (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_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", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_prediction_service_client_get_transport_class(): + transport = PredictionServiceClient.get_transport_class() + available_transports = [ + transports.PredictionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = PredictionServiceClient.get_transport_class("grpc") + assert transport == transports.PredictionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + PredictionServiceClient, PredictionServiceAsyncClient +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_prediction_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_service.PredictRequest, + dict, +]) +def test_predict(request_type, transport: str = 'grpc'): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + response = client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_predict_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + client.predict() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + +@pytest.mark.asyncio +async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + )) + response = await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +@pytest.mark.asyncio +async def test_predict_async_from_dict(): + await test_predict_async(request_type=dict) + + +def test_predict_field_headers(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_predict_field_headers_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) + await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = PredictionServiceClient.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 = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'predict', + ) + 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport( + 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport() + adc.assert_called_once() + + +def test_prediction_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) + PredictionServiceClient() + 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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +def test_prediction_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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + transports.PredictionServiceRestTransport, + ], +) +def test_prediction_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.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_prediction_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_no_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_with_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_prediction_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcTransport( + 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_prediction_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcAsyncIOTransport( + 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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_product_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + product = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + "branch": "winkle", + "product": "nautilus", + } + path = PredictionServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PredictionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = PredictionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = PredictionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = PredictionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PredictionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = PredictionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = PredictionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = PredictionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = PredictionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PredictionServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py new file mode 100644 index 00000000..6bb6b078 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py @@ -0,0 +1,4136 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.product_service import ProductServiceAsyncClient +from google.cloud.retail_v2.services.product_service import ProductServiceClient +from google.cloud.retail_v2.services.product_service import pagers +from google.cloud.retail_v2.services.product_service import transports +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.cloud.retail_v2.types import promotion +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProductServiceClient._get_default_mtls_endpoint(None) is None + assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProductServiceGrpcTransport, "grpc"), + (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_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", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_product_service_client_get_transport_class(): + transport = ProductServiceClient.get_transport_class() + available_transports = [ + transports.ProductServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ProductServiceClient.get_transport_class("grpc") + assert transport == transports.ProductServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_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(ProductServiceClient, '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(ProductServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ProductServiceClient, ProductServiceAsyncClient +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_product_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.CreateProductRequest, + dict, +]) +def test_create_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_create_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.create_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + +@pytest.mark.asyncio +async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_create_product_async_from_dict(): + await test_create_product_async(request_type=dict) + + +def test_create_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + + +def test_create_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + +@pytest.mark.asyncio +async def test_create_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_get_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.get_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + +@pytest.mark.asyncio +async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_get_product_async_from_dict(): + await test_get_product_async(request_type=dict) + + +def test_get_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = product.Product() + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.GetProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.GetProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.list_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + +@pytest.mark.asyncio +async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_products_async_from_dict(): + await test_list_products_async(request_type=dict) + + +def test_list_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = product_service.ListProductsResponse() + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products( + 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_products_flattened_error(): + client = ProductServiceClient( + credentials=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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products( + 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_products_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + + +def test_list_products_pager(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_products(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, product.Product) + for i in results) +def test_list_products_pages(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(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_products_async_pager(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(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, product.Product) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_products(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + product_service.UpdateProductRequest, + dict, +]) +def test_update_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_update_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.update_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + +@pytest.mark.asyncio +async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_update_product_async_from_dict(): + await test_update_product_async(request_type=dict) + + +def test_update_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +def test_update_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.DeleteProductRequest, + dict, +]) +def test_delete_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.delete_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + +@pytest.mark.asyncio +async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_product_async_from_dict(): + await test_delete_product_async(request_type=dict) + + +def test_delete_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = None + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportProductsRequest, + dict, +]) +def test_import_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.import_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + +@pytest.mark.asyncio +async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__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_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_products_async_from_dict(): + await test_import_products_async(request_type=dict) + + +def test_import_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + product_service.SetInventoryRequest, + dict, +]) +def test_set_inventory(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_inventory_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + client.set_inventory() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + +@pytest.mark.asyncio +async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_set_inventory_async_from_dict(): + await test_set_inventory_async(request_type=dict) + + +def test_set_inventory_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_inventory_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +def test_set_inventory_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_set_inventory_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_set_inventory_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_inventory_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddFulfillmentPlacesRequest, + dict, +]) +def test_add_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + client.add_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async_from_dict(): + await test_add_fulfillment_places_async(request_type=dict) + + +def test_add_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveFulfillmentPlacesRequest, + dict, +]) +def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + client.remove_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async_from_dict(): + await test_remove_fulfillment_places_async(request_type=dict) + + +def test_remove_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddLocalInventoriesRequest, + dict, +]) +def test_add_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + client.add_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_local_inventories_async_from_dict(): + await test_add_local_inventories_async(request_type=dict) + + +def test_add_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveLocalInventoriesRequest, + dict, +]) +def test_remove_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + client.remove_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_local_inventories_async_from_dict(): + await test_remove_local_inventories_async(request_type=dict) + + +def test_remove_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ProductServiceClient.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 = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProductServiceGrpcTransport, + ) + +def test_product_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_product_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.product_service.transports.ProductServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_product', + 'get_product', + 'list_products', + 'update_product', + 'delete_product', + 'import_products', + 'set_inventory', + 'add_fulfillment_places', + 'remove_fulfillment_places', + 'add_local_inventories', + 'remove_local_inventories', + ) + 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_product_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.retail_v2.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport( + 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_product_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.retail_v2.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport() + adc.assert_called_once() + + +def test_product_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) + ProductServiceClient() + 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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + ], +) +def test_product_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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + transports.ProductServiceRestTransport, + ], +) +def test_product_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.ProductServiceGrpcTransport, grpc_helpers), + (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_product_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_no_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_with_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_product_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcTransport( + 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_product_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcAsyncIOTransport( + 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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_product_service_grpc_lro_client(): + client = ProductServiceClient( + 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_product_service_grpc_lro_async_client(): + client = ProductServiceAsyncClient( + 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" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = ProductServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = ProductServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = ProductServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = ProductServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProductServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ProductServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProductServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ProductServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProductServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ProductServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ProductServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ProductServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ProductServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ProductServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ProductServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py new file mode 100644 index 00000000..c9858027 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py @@ -0,0 +1,1547 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.search_service import SearchServiceAsyncClient +from google.cloud.retail_v2.services.search_service import SearchServiceClient +from google.cloud.retail_v2.services.search_service import pagers +from google.cloud.retail_v2.services.search_service import transports +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import search_service +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SearchServiceClient._get_default_mtls_endpoint(None) is None + assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SearchServiceGrpcTransport, "grpc"), + (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_search_service_client_get_transport_class(): + transport = SearchServiceClient.get_transport_class() + available_transports = [ + transports.SearchServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SearchServiceClient.get_transport_class("grpc") + assert transport == transports.SearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SearchServiceClient, SearchServiceAsyncClient +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SearchServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + search_service.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + + +def test_search_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = search_service.SearchResponse() + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_search_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('placement', ''), + )), + ) + pager = client.search(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_async_pager(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = SearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_search_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_search_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport() + adc.assert_called_once() + + +def test_search_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SearchServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + transports.SearchServiceRestTransport, + ], +) +def test_search_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SearchServiceGrpcTransport, grpc_helpers), + (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_search_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_no_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_with_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_branch_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = SearchServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = SearchServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = SearchServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = SearchServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py new file mode 100644 index 00000000..4dc04e51 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py @@ -0,0 +1,2039 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.retail_v2.services.user_event_service import UserEventServiceClient +from google.cloud.retail_v2.services.user_event_service import transports +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import promotion +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + ) + response = client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +def test_write_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) + await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeUserEventsRequest, + dict, +]) +def test_purge_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + client.purge_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + +@pytest.mark.asyncio +async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_user_events_async_from_dict(): + await test_purge_user_events_async(request_type=dict) + + +def test_purge_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_purge_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.RejoinUserEventsRequest, + dict, +]) +def test_rejoin_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_rejoin_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + client.rejoin_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + +@pytest.mark.asyncio +async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_rejoin_user_events_async_from_dict(): + await test_rejoin_user_events_async(request_type=dict) + + +def test_rejoin_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_rejoin_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'purge_user_events', + 'import_user_events', + 'rejoin_user_events', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_user_event_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_user_event_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +def test_user_event_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + UserEventServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +def test_user_event_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = UserEventServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = UserEventServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_product_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + product = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + "branch": "whelk", + "product": "octopus", + } + path = UserEventServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/.coveragerc b/owl-bot-staging/v2alpha/.coveragerc new file mode 100644 index 00000000..a8b114f0 --- /dev/null +++ b/owl-bot-staging/v2alpha/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/retail/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2alpha/.flake8 b/owl-bot-staging/v2alpha/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v2alpha/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v2alpha/MANIFEST.in b/owl-bot-staging/v2alpha/MANIFEST.in new file mode 100644 index 00000000..3ee710cc --- /dev/null +++ b/owl-bot-staging/v2alpha/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/retail *.py +recursive-include google/cloud/retail_v2alpha *.py diff --git a/owl-bot-staging/v2alpha/README.rst b/owl-bot-staging/v2alpha/README.rst new file mode 100644 index 00000000..cb039760 --- /dev/null +++ b/owl-bot-staging/v2alpha/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Retail API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Retail API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2alpha/docs/conf.py b/owl-bot-staging/v2alpha/docs/conf.py new file mode 100644 index 00000000..5be9eb4b --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-retail documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-retail" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-retail-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-retail.tex", + u"google-cloud-retail Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-retail", + u"Google Cloud Retail Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-retail", + u"google-cloud-retail Documentation", + author, + "google-cloud-retail", + "GAPIC library for Google Cloud Retail API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v2alpha/docs/index.rst b/owl-bot-staging/v2alpha/docs/index.rst new file mode 100644 index 00000000..dc0a2096 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + retail_v2alpha/services + retail_v2alpha/types diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst new file mode 100644 index 00000000..745d0cf4 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst @@ -0,0 +1,10 @@ +CatalogService +-------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.catalog_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.catalog_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst new file mode 100644 index 00000000..3a276433 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst @@ -0,0 +1,6 @@ +CompletionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.completion_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst new file mode 100644 index 00000000..36aaf9b6 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst @@ -0,0 +1,10 @@ +ControlService +-------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.control_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.control_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst new file mode 100644 index 00000000..b659cf98 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst @@ -0,0 +1,6 @@ +PredictionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.prediction_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst new file mode 100644 index 00000000..acbb336e --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst @@ -0,0 +1,10 @@ +ProductService +-------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.product_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.product_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst new file mode 100644 index 00000000..ad4c486d --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst @@ -0,0 +1,10 @@ +SearchService +------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst new file mode 100644 index 00000000..edeb8cfc --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst @@ -0,0 +1,13 @@ +Services for Google Cloud Retail v2alpha API +============================================ +.. toctree:: + :maxdepth: 2 + + catalog_service + completion_service + control_service + prediction_service + product_service + search_service + serving_config_service + user_event_service diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst new file mode 100644 index 00000000..c1516860 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst @@ -0,0 +1,10 @@ +ServingConfigService +-------------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.serving_config_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.serving_config_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst new file mode 100644 index 00000000..c1445ad6 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Retail v2alpha API +========================================= + +.. automodule:: google.cloud.retail_v2alpha.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst new file mode 100644 index 00000000..8c56485c --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst @@ -0,0 +1,6 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.user_event_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py new file mode 100644 index 00000000..a17a283b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.retail_v2alpha.services.catalog_service.client import CatalogServiceClient +from google.cloud.retail_v2alpha.services.catalog_service.async_client import CatalogServiceAsyncClient +from google.cloud.retail_v2alpha.services.completion_service.client import CompletionServiceClient +from google.cloud.retail_v2alpha.services.completion_service.async_client import CompletionServiceAsyncClient +from google.cloud.retail_v2alpha.services.control_service.client import ControlServiceClient +from google.cloud.retail_v2alpha.services.control_service.async_client import ControlServiceAsyncClient +from google.cloud.retail_v2alpha.services.prediction_service.client import PredictionServiceClient +from google.cloud.retail_v2alpha.services.prediction_service.async_client import PredictionServiceAsyncClient +from google.cloud.retail_v2alpha.services.product_service.client import ProductServiceClient +from google.cloud.retail_v2alpha.services.product_service.async_client import ProductServiceAsyncClient +from google.cloud.retail_v2alpha.services.search_service.client import SearchServiceClient +from google.cloud.retail_v2alpha.services.search_service.async_client import SearchServiceAsyncClient +from google.cloud.retail_v2alpha.services.serving_config_service.client import ServingConfigServiceClient +from google.cloud.retail_v2alpha.services.serving_config_service.async_client import ServingConfigServiceAsyncClient +from google.cloud.retail_v2alpha.services.user_event_service.client import UserEventServiceClient +from google.cloud.retail_v2alpha.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.retail_v2alpha.types.catalog import AttributesConfig +from google.cloud.retail_v2alpha.types.catalog import Catalog +from google.cloud.retail_v2alpha.types.catalog import CatalogAttribute +from google.cloud.retail_v2alpha.types.catalog import CompletionConfig +from google.cloud.retail_v2alpha.types.catalog import MerchantCenterLink +from google.cloud.retail_v2alpha.types.catalog import MerchantCenterLinkingConfig +from google.cloud.retail_v2alpha.types.catalog import ProductLevelConfig +from google.cloud.retail_v2alpha.types.catalog_service import AddCatalogAttributeRequest +from google.cloud.retail_v2alpha.types.catalog_service import GetAttributesConfigRequest +from google.cloud.retail_v2alpha.types.catalog_service import GetCompletionConfigRequest +from google.cloud.retail_v2alpha.types.catalog_service import GetDefaultBranchRequest +from google.cloud.retail_v2alpha.types.catalog_service import GetDefaultBranchResponse +from google.cloud.retail_v2alpha.types.catalog_service import ListCatalogsRequest +from google.cloud.retail_v2alpha.types.catalog_service import ListCatalogsResponse +from google.cloud.retail_v2alpha.types.catalog_service import RemoveCatalogAttributeRequest +from google.cloud.retail_v2alpha.types.catalog_service import ReplaceCatalogAttributeRequest +from google.cloud.retail_v2alpha.types.catalog_service import SetDefaultBranchRequest +from google.cloud.retail_v2alpha.types.catalog_service import UpdateAttributesConfigRequest +from google.cloud.retail_v2alpha.types.catalog_service import UpdateCatalogRequest +from google.cloud.retail_v2alpha.types.catalog_service import UpdateCompletionConfigRequest +from google.cloud.retail_v2alpha.types.common import Audience +from google.cloud.retail_v2alpha.types.common import ColorInfo +from google.cloud.retail_v2alpha.types.common import Condition +from google.cloud.retail_v2alpha.types.common import CustomAttribute +from google.cloud.retail_v2alpha.types.common import FulfillmentInfo +from google.cloud.retail_v2alpha.types.common import Image +from google.cloud.retail_v2alpha.types.common import Interval +from google.cloud.retail_v2alpha.types.common import LocalInventory +from google.cloud.retail_v2alpha.types.common import PriceInfo +from google.cloud.retail_v2alpha.types.common import Rating +from google.cloud.retail_v2alpha.types.common import Rule +from google.cloud.retail_v2alpha.types.common import UserInfo +from google.cloud.retail_v2alpha.types.common import AttributeConfigLevel +from google.cloud.retail_v2alpha.types.common import SearchSolutionUseCase +from google.cloud.retail_v2alpha.types.common import SolutionType +from google.cloud.retail_v2alpha.types.completion_service import CompleteQueryRequest +from google.cloud.retail_v2alpha.types.completion_service import CompleteQueryResponse +from google.cloud.retail_v2alpha.types.control import Control +from google.cloud.retail_v2alpha.types.control_service import CreateControlRequest +from google.cloud.retail_v2alpha.types.control_service import DeleteControlRequest +from google.cloud.retail_v2alpha.types.control_service import GetControlRequest +from google.cloud.retail_v2alpha.types.control_service import ListControlsRequest +from google.cloud.retail_v2alpha.types.control_service import ListControlsResponse +from google.cloud.retail_v2alpha.types.control_service import UpdateControlRequest +from google.cloud.retail_v2alpha.types.export_config import ExportErrorsConfig +from google.cloud.retail_v2alpha.types.export_config import ExportMetadata +from google.cloud.retail_v2alpha.types.export_config import ExportProductsResponse +from google.cloud.retail_v2alpha.types.export_config import ExportUserEventsResponse +from google.cloud.retail_v2alpha.types.import_config import BigQuerySource +from google.cloud.retail_v2alpha.types.import_config import CompletionDataInputConfig +from google.cloud.retail_v2alpha.types.import_config import GcsSource +from google.cloud.retail_v2alpha.types.import_config import ImportCompletionDataRequest +from google.cloud.retail_v2alpha.types.import_config import ImportCompletionDataResponse +from google.cloud.retail_v2alpha.types.import_config import ImportErrorsConfig +from google.cloud.retail_v2alpha.types.import_config import ImportMetadata +from google.cloud.retail_v2alpha.types.import_config import ImportProductsRequest +from google.cloud.retail_v2alpha.types.import_config import ImportProductsResponse +from google.cloud.retail_v2alpha.types.import_config import ImportUserEventsRequest +from google.cloud.retail_v2alpha.types.import_config import ImportUserEventsResponse +from google.cloud.retail_v2alpha.types.import_config import ProductInlineSource +from google.cloud.retail_v2alpha.types.import_config import ProductInputConfig +from google.cloud.retail_v2alpha.types.import_config import UserEventImportSummary +from google.cloud.retail_v2alpha.types.import_config import UserEventInlineSource +from google.cloud.retail_v2alpha.types.import_config import UserEventInputConfig +from google.cloud.retail_v2alpha.types.prediction_service import PredictRequest +from google.cloud.retail_v2alpha.types.prediction_service import PredictResponse +from google.cloud.retail_v2alpha.types.product import Product +from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesMetadata +from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesRequest +from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesResponse +from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesMetadata +from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesRequest +from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesResponse +from google.cloud.retail_v2alpha.types.product_service import CreateProductRequest +from google.cloud.retail_v2alpha.types.product_service import DeleteProductRequest +from google.cloud.retail_v2alpha.types.product_service import GetProductRequest +from google.cloud.retail_v2alpha.types.product_service import ListProductsRequest +from google.cloud.retail_v2alpha.types.product_service import ListProductsResponse +from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesMetadata +from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesRequest +from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesResponse +from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesMetadata +from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesRequest +from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesResponse +from google.cloud.retail_v2alpha.types.product_service import SetInventoryMetadata +from google.cloud.retail_v2alpha.types.product_service import SetInventoryRequest +from google.cloud.retail_v2alpha.types.product_service import SetInventoryResponse +from google.cloud.retail_v2alpha.types.product_service import UpdateProductRequest +from google.cloud.retail_v2alpha.types.promotion import Promotion +from google.cloud.retail_v2alpha.types.purge_config import PurgeMetadata +from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsMetadata +from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsRequest +from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsResponse +from google.cloud.retail_v2alpha.types.purge_config import PurgeUserEventsRequest +from google.cloud.retail_v2alpha.types.purge_config import PurgeUserEventsResponse +from google.cloud.retail_v2alpha.types.search_service import SearchRequest +from google.cloud.retail_v2alpha.types.search_service import SearchResponse +from google.cloud.retail_v2alpha.types.serving_config import ServingConfig +from google.cloud.retail_v2alpha.types.serving_config_service import AddControlRequest +from google.cloud.retail_v2alpha.types.serving_config_service import CreateServingConfigRequest +from google.cloud.retail_v2alpha.types.serving_config_service import DeleteServingConfigRequest +from google.cloud.retail_v2alpha.types.serving_config_service import GetServingConfigRequest +from google.cloud.retail_v2alpha.types.serving_config_service import ListServingConfigsRequest +from google.cloud.retail_v2alpha.types.serving_config_service import ListServingConfigsResponse +from google.cloud.retail_v2alpha.types.serving_config_service import RemoveControlRequest +from google.cloud.retail_v2alpha.types.serving_config_service import UpdateServingConfigRequest +from google.cloud.retail_v2alpha.types.user_event import CompletionDetail +from google.cloud.retail_v2alpha.types.user_event import ProductDetail +from google.cloud.retail_v2alpha.types.user_event import PurchaseTransaction +from google.cloud.retail_v2alpha.types.user_event import UserEvent +from google.cloud.retail_v2alpha.types.user_event_service import CollectUserEventRequest +from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsMetadata +from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsRequest +from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsResponse +from google.cloud.retail_v2alpha.types.user_event_service import WriteUserEventRequest + +__all__ = ('CatalogServiceClient', + 'CatalogServiceAsyncClient', + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', + 'ControlServiceClient', + 'ControlServiceAsyncClient', + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', + 'ProductServiceClient', + 'ProductServiceAsyncClient', + 'SearchServiceClient', + 'SearchServiceAsyncClient', + 'ServingConfigServiceClient', + 'ServingConfigServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'AttributesConfig', + 'Catalog', + 'CatalogAttribute', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'ProductLevelConfig', + 'AddCatalogAttributeRequest', + 'GetAttributesConfigRequest', + 'GetCompletionConfigRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + 'SetDefaultBranchRequest', + 'UpdateAttributesConfigRequest', + 'UpdateCatalogRequest', + 'UpdateCompletionConfigRequest', + 'Audience', + 'ColorInfo', + 'Condition', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'Rule', + 'UserInfo', + 'AttributeConfigLevel', + 'SearchSolutionUseCase', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Control', + 'CreateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + 'UpdateControlRequest', + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeProductsMetadata', + 'PurgeProductsRequest', + 'PurgeProductsResponse', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'ServingConfig', + 'AddControlRequest', + 'CreateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'RemoveControlRequest', + 'UpdateServingConfigRequest', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail/py.typed b/owl-bot-staging/v2alpha/google/cloud/retail/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py new file mode 100644 index 00000000..e515a173 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.catalog_service import CatalogServiceClient +from .services.catalog_service import CatalogServiceAsyncClient +from .services.completion_service import CompletionServiceClient +from .services.completion_service import CompletionServiceAsyncClient +from .services.control_service import ControlServiceClient +from .services.control_service import ControlServiceAsyncClient +from .services.prediction_service import PredictionServiceClient +from .services.prediction_service import PredictionServiceAsyncClient +from .services.product_service import ProductServiceClient +from .services.product_service import ProductServiceAsyncClient +from .services.search_service import SearchServiceClient +from .services.search_service import SearchServiceAsyncClient +from .services.serving_config_service import ServingConfigServiceClient +from .services.serving_config_service import ServingConfigServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.catalog import AttributesConfig +from .types.catalog import Catalog +from .types.catalog import CatalogAttribute +from .types.catalog import CompletionConfig +from .types.catalog import MerchantCenterLink +from .types.catalog import MerchantCenterLinkingConfig +from .types.catalog import ProductLevelConfig +from .types.catalog_service import AddCatalogAttributeRequest +from .types.catalog_service import GetAttributesConfigRequest +from .types.catalog_service import GetCompletionConfigRequest +from .types.catalog_service import GetDefaultBranchRequest +from .types.catalog_service import GetDefaultBranchResponse +from .types.catalog_service import ListCatalogsRequest +from .types.catalog_service import ListCatalogsResponse +from .types.catalog_service import RemoveCatalogAttributeRequest +from .types.catalog_service import ReplaceCatalogAttributeRequest +from .types.catalog_service import SetDefaultBranchRequest +from .types.catalog_service import UpdateAttributesConfigRequest +from .types.catalog_service import UpdateCatalogRequest +from .types.catalog_service import UpdateCompletionConfigRequest +from .types.common import Audience +from .types.common import ColorInfo +from .types.common import Condition +from .types.common import CustomAttribute +from .types.common import FulfillmentInfo +from .types.common import Image +from .types.common import Interval +from .types.common import LocalInventory +from .types.common import PriceInfo +from .types.common import Rating +from .types.common import Rule +from .types.common import UserInfo +from .types.common import AttributeConfigLevel +from .types.common import SearchSolutionUseCase +from .types.common import SolutionType +from .types.completion_service import CompleteQueryRequest +from .types.completion_service import CompleteQueryResponse +from .types.control import Control +from .types.control_service import CreateControlRequest +from .types.control_service import DeleteControlRequest +from .types.control_service import GetControlRequest +from .types.control_service import ListControlsRequest +from .types.control_service import ListControlsResponse +from .types.control_service import UpdateControlRequest +from .types.export_config import ExportErrorsConfig +from .types.export_config import ExportMetadata +from .types.export_config import ExportProductsResponse +from .types.export_config import ExportUserEventsResponse +from .types.import_config import BigQuerySource +from .types.import_config import CompletionDataInputConfig +from .types.import_config import GcsSource +from .types.import_config import ImportCompletionDataRequest +from .types.import_config import ImportCompletionDataResponse +from .types.import_config import ImportErrorsConfig +from .types.import_config import ImportMetadata +from .types.import_config import ImportProductsRequest +from .types.import_config import ImportProductsResponse +from .types.import_config import ImportUserEventsRequest +from .types.import_config import ImportUserEventsResponse +from .types.import_config import ProductInlineSource +from .types.import_config import ProductInputConfig +from .types.import_config import UserEventImportSummary +from .types.import_config import UserEventInlineSource +from .types.import_config import UserEventInputConfig +from .types.prediction_service import PredictRequest +from .types.prediction_service import PredictResponse +from .types.product import Product +from .types.product_service import AddFulfillmentPlacesMetadata +from .types.product_service import AddFulfillmentPlacesRequest +from .types.product_service import AddFulfillmentPlacesResponse +from .types.product_service import AddLocalInventoriesMetadata +from .types.product_service import AddLocalInventoriesRequest +from .types.product_service import AddLocalInventoriesResponse +from .types.product_service import CreateProductRequest +from .types.product_service import DeleteProductRequest +from .types.product_service import GetProductRequest +from .types.product_service import ListProductsRequest +from .types.product_service import ListProductsResponse +from .types.product_service import RemoveFulfillmentPlacesMetadata +from .types.product_service import RemoveFulfillmentPlacesRequest +from .types.product_service import RemoveFulfillmentPlacesResponse +from .types.product_service import RemoveLocalInventoriesMetadata +from .types.product_service import RemoveLocalInventoriesRequest +from .types.product_service import RemoveLocalInventoriesResponse +from .types.product_service import SetInventoryMetadata +from .types.product_service import SetInventoryRequest +from .types.product_service import SetInventoryResponse +from .types.product_service import UpdateProductRequest +from .types.promotion import Promotion +from .types.purge_config import PurgeMetadata +from .types.purge_config import PurgeProductsMetadata +from .types.purge_config import PurgeProductsRequest +from .types.purge_config import PurgeProductsResponse +from .types.purge_config import PurgeUserEventsRequest +from .types.purge_config import PurgeUserEventsResponse +from .types.search_service import SearchRequest +from .types.search_service import SearchResponse +from .types.serving_config import ServingConfig +from .types.serving_config_service import AddControlRequest +from .types.serving_config_service import CreateServingConfigRequest +from .types.serving_config_service import DeleteServingConfigRequest +from .types.serving_config_service import GetServingConfigRequest +from .types.serving_config_service import ListServingConfigsRequest +from .types.serving_config_service import ListServingConfigsResponse +from .types.serving_config_service import RemoveControlRequest +from .types.serving_config_service import UpdateServingConfigRequest +from .types.user_event import CompletionDetail +from .types.user_event import ProductDetail +from .types.user_event import PurchaseTransaction +from .types.user_event import UserEvent +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import RejoinUserEventsMetadata +from .types.user_event_service import RejoinUserEventsRequest +from .types.user_event_service import RejoinUserEventsResponse +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CatalogServiceAsyncClient', + 'CompletionServiceAsyncClient', + 'ControlServiceAsyncClient', + 'PredictionServiceAsyncClient', + 'ProductServiceAsyncClient', + 'SearchServiceAsyncClient', + 'ServingConfigServiceAsyncClient', + 'UserEventServiceAsyncClient', +'AddCatalogAttributeRequest', +'AddControlRequest', +'AddFulfillmentPlacesMetadata', +'AddFulfillmentPlacesRequest', +'AddFulfillmentPlacesResponse', +'AddLocalInventoriesMetadata', +'AddLocalInventoriesRequest', +'AddLocalInventoriesResponse', +'AttributeConfigLevel', +'AttributesConfig', +'Audience', +'BigQuerySource', +'Catalog', +'CatalogAttribute', +'CatalogServiceClient', +'CollectUserEventRequest', +'ColorInfo', +'CompleteQueryRequest', +'CompleteQueryResponse', +'CompletionConfig', +'CompletionDataInputConfig', +'CompletionDetail', +'CompletionServiceClient', +'Condition', +'Control', +'ControlServiceClient', +'CreateControlRequest', +'CreateProductRequest', +'CreateServingConfigRequest', +'CustomAttribute', +'DeleteControlRequest', +'DeleteProductRequest', +'DeleteServingConfigRequest', +'ExportErrorsConfig', +'ExportMetadata', +'ExportProductsResponse', +'ExportUserEventsResponse', +'FulfillmentInfo', +'GcsSource', +'GetAttributesConfigRequest', +'GetCompletionConfigRequest', +'GetControlRequest', +'GetDefaultBranchRequest', +'GetDefaultBranchResponse', +'GetProductRequest', +'GetServingConfigRequest', +'Image', +'ImportCompletionDataRequest', +'ImportCompletionDataResponse', +'ImportErrorsConfig', +'ImportMetadata', +'ImportProductsRequest', +'ImportProductsResponse', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'Interval', +'ListCatalogsRequest', +'ListCatalogsResponse', +'ListControlsRequest', +'ListControlsResponse', +'ListProductsRequest', +'ListProductsResponse', +'ListServingConfigsRequest', +'ListServingConfigsResponse', +'LocalInventory', +'MerchantCenterLink', +'MerchantCenterLinkingConfig', +'PredictRequest', +'PredictResponse', +'PredictionServiceClient', +'PriceInfo', +'Product', +'ProductDetail', +'ProductInlineSource', +'ProductInputConfig', +'ProductLevelConfig', +'ProductServiceClient', +'Promotion', +'PurchaseTransaction', +'PurgeMetadata', +'PurgeProductsMetadata', +'PurgeProductsRequest', +'PurgeProductsResponse', +'PurgeUserEventsRequest', +'PurgeUserEventsResponse', +'Rating', +'RejoinUserEventsMetadata', +'RejoinUserEventsRequest', +'RejoinUserEventsResponse', +'RemoveCatalogAttributeRequest', +'RemoveControlRequest', +'RemoveFulfillmentPlacesMetadata', +'RemoveFulfillmentPlacesRequest', +'RemoveFulfillmentPlacesResponse', +'RemoveLocalInventoriesMetadata', +'RemoveLocalInventoriesRequest', +'RemoveLocalInventoriesResponse', +'ReplaceCatalogAttributeRequest', +'Rule', +'SearchRequest', +'SearchResponse', +'SearchServiceClient', +'SearchSolutionUseCase', +'ServingConfig', +'ServingConfigServiceClient', +'SetDefaultBranchRequest', +'SetInventoryMetadata', +'SetInventoryRequest', +'SetInventoryResponse', +'SolutionType', +'UpdateAttributesConfigRequest', +'UpdateCatalogRequest', +'UpdateCompletionConfigRequest', +'UpdateControlRequest', +'UpdateProductRequest', +'UpdateServingConfigRequest', +'UserEvent', +'UserEventImportSummary', +'UserEventInlineSource', +'UserEventInputConfig', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json new file mode 100644 index 00000000..543e36d6 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json @@ -0,0 +1,561 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.retail_v2alpha", + "protoPackage": "google.cloud.retail.v2alpha", + "schema": "1.0", + "services": { + "CatalogService": { + "clients": { + "grpc": { + "libraryClient": "CatalogServiceClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "add_catalog_attribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "get_attributes_config" + ] + }, + "GetCompletionConfig": { + "methods": [ + "get_completion_config" + ] + }, + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "remove_catalog_attribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "replace_catalog_attribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "update_attributes_config" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "update_completion_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CatalogServiceAsyncClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "add_catalog_attribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "get_attributes_config" + ] + }, + "GetCompletionConfig": { + "methods": [ + "get_completion_config" + ] + }, + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "remove_catalog_attribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "replace_catalog_attribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "update_attributes_config" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "update_completion_config" + ] + } + } + } + } + }, + "CompletionService": { + "clients": { + "grpc": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CompletionServiceAsyncClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + } + } + }, + "ControlService": { + "clients": { + "grpc": { + "libraryClient": "ControlServiceClient", + "rpcs": { + "CreateControl": { + "methods": [ + "create_control" + ] + }, + "DeleteControl": { + "methods": [ + "delete_control" + ] + }, + "GetControl": { + "methods": [ + "get_control" + ] + }, + "ListControls": { + "methods": [ + "list_controls" + ] + }, + "UpdateControl": { + "methods": [ + "update_control" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ControlServiceAsyncClient", + "rpcs": { + "CreateControl": { + "methods": [ + "create_control" + ] + }, + "DeleteControl": { + "methods": [ + "delete_control" + ] + }, + "GetControl": { + "methods": [ + "get_control" + ] + }, + "ListControls": { + "methods": [ + "list_controls" + ] + }, + "UpdateControl": { + "methods": [ + "update_control" + ] + } + } + } + } + }, + "PredictionService": { + "clients": { + "grpc": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionServiceAsyncClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + } + } + }, + "ProductService": { + "clients": { + "grpc": { + "libraryClient": "ProductServiceClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "PurgeProducts": { + "methods": [ + "purge_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductServiceAsyncClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "PurgeProducts": { + "methods": [ + "purge_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + } + } + }, + "SearchService": { + "clients": { + "grpc": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SearchServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + }, + "ServingConfigService": { + "clients": { + "grpc": { + "libraryClient": "ServingConfigServiceClient", + "rpcs": { + "AddControl": { + "methods": [ + "add_control" + ] + }, + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, + "RemoveControl": { + "methods": [ + "remove_control" + ] + }, + "UpdateServingConfig": { + "methods": [ + "update_serving_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServingConfigServiceAsyncClient", + "rpcs": { + "AddControl": { + "methods": [ + "add_control" + ] + }, + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, + "RemoveControl": { + "methods": [ + "remove_control" + ] + }, + "UpdateServingConfig": { + "methods": [ + "update_serving_config" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py new file mode 100644 index 00000000..d276b897 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CatalogServiceClient +from .async_client import CatalogServiceAsyncClient + +__all__ = ( + 'CatalogServiceClient', + 'CatalogServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py new file mode 100644 index 00000000..e828ae6f --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py @@ -0,0 +1,1352 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.catalog_service import pagers +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport +from .client import CatalogServiceClient + + +class CatalogServiceAsyncClient: + """Service for managing catalog configuration.""" + + _client: CatalogServiceClient + + DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT + + attributes_config_path = staticmethod(CatalogServiceClient.attributes_config_path) + parse_attributes_config_path = staticmethod(CatalogServiceClient.parse_attributes_config_path) + branch_path = staticmethod(CatalogServiceClient.branch_path) + parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) + catalog_path = staticmethod(CatalogServiceClient.catalog_path) + parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) + completion_config_path = staticmethod(CatalogServiceClient.completion_config_path) + parse_completion_config_path = staticmethod(CatalogServiceClient.parse_completion_config_path) + common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CatalogServiceClient.common_project_path) + parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) + common_location_path = staticmethod(CatalogServiceClient.common_location_path) + parse_common_location_path = staticmethod(CatalogServiceClient.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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CatalogServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsAsyncPager: + r"""Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_list_catalogs(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + parent (:class:`str`): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2alpha.Catalog]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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsAsyncPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.ListCatalogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_catalogs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCatalogsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_catalog(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2alpha.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2alpha.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] + method. + catalog (:class:`google.cloud.retail_v2alpha.types.Catalog`): + Required. The + [Catalog][google.cloud.retail.v2alpha.Catalog] to + update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2alpha.Catalog], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Catalog][google.cloud.retail.v2alpha.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2alpha.Catalog] to + update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_catalog, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_set_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (:class:`str`): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.SetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (:class:`str`): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # 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_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_completion_config(self, + request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Gets a + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] + method. + name (:class:`str`): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + + 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.retail_v2alpha.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetCompletionConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_completion_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_completion_config(self, + request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, + *, + completion_config: catalog.CompletionConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Updates the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + completion_config = retail_v2alpha.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2alpha.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = await client.update_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] + method. + completion_config (:class:`google.cloud.retail_v2alpha.types.CompletionConfig`): + Required. The + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``completion_config`` 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 + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([completion_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCompletionConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if completion_config is not None: + request.completion_config = completion_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_completion_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("completion_config.name", request.completion_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_attributes_config(self, + request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Gets an + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] + method. + name (:class:`str`): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + + 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.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetAttributesConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_attributes_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_attributes_config(self, + request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, + *, + attributes_config: catalog.AttributesConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Updates the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + attributes_config = retail_v2alpha.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2alpha.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = await client.update_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] + method. + attributes_config (:class:`google.cloud.retail_v2alpha.types.AttributesConfig`): + Required. The + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. + + This corresponds to the ``attributes_config`` 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 + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attributes_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateAttributesConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attributes_config is not None: + request.attributes_config = attributes_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_attributes_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config.name", request.attributes_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_catalog_attribute(self, + request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Adds the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_add_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.AddCatalogAttributeRequest(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.add_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_catalog_attribute(self, + request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Removes the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = await client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.RemoveCatalogAttributeRequest(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.remove_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def replace_catalog_attribute(self, + request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Replaces the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.ReplaceCatalogAttributeRequest(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.replace_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py new file mode 100644 index 00000000..85a7d228 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py @@ -0,0 +1,1582 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.catalog_service import pagers +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CatalogServiceGrpcTransport +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +class CatalogServiceClientMeta(type): + """Metaclass for the CatalogService 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[CatalogServiceTransport]] + _transport_registry["grpc"] = CatalogServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CatalogServiceTransport]: + """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): + """Service for managing catalog configuration.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CatalogServiceClient: 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: + CatalogServiceClient: 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) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def attributes_config_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified attributes_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_attributes_config_path(path: str) -> Dict[str,str]: + """Parses a attributes_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/attributesConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def completion_config_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified completion_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_completion_config_path(path: str) -> Dict[str,str]: + """Parses a completion_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/completionConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CatalogServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CatalogServiceTransport): + # transport is a CatalogServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsPager: + r"""Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_list_catalogs(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2alpha.Catalog]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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ListCatalogsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ListCatalogsRequest): + request = catalog_service.ListCatalogsRequest(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_catalogs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCatalogsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_catalog(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2alpha.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2alpha.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] + method. + catalog (google.cloud.retail_v2alpha.types.Catalog): + Required. The + [Catalog][google.cloud.retail.v2alpha.Catalog] to + update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2alpha.Catalog], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Catalog][google.cloud.retail.v2alpha.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2alpha.Catalog] to + update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCatalogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCatalogRequest): + request = catalog_service.UpdateCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + 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_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_set_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.SetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.SetDefaultBranchRequest): + request = catalog_service.SetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetDefaultBranchRequest): + request = catalog_service.GetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_completion_config(self, + request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Gets a + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] + method. + name (str): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + + 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.retail_v2alpha.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetCompletionConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetCompletionConfigRequest): + request = catalog_service.GetCompletionConfigRequest(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_completion_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_completion_config(self, + request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, + *, + completion_config: catalog.CompletionConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Updates the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + completion_config = retail_v2alpha.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2alpha.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = client.update_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] + method. + completion_config (google.cloud.retail_v2alpha.types.CompletionConfig): + Required. The + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``completion_config`` 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 + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([completion_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCompletionConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCompletionConfigRequest): + request = catalog_service.UpdateCompletionConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if completion_config is not None: + request.completion_config = completion_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_completion_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("completion_config.name", request.completion_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_attributes_config(self, + request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Gets an + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] + method. + name (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + + 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.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetAttributesConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetAttributesConfigRequest): + request = catalog_service.GetAttributesConfigRequest(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_attributes_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_attributes_config(self, + request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, + *, + attributes_config: catalog.AttributesConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Updates the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + attributes_config = retail_v2alpha.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2alpha.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = client.update_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] + method. + attributes_config (google.cloud.retail_v2alpha.types.AttributesConfig): + Required. The + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. + + This corresponds to the ``attributes_config`` 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 + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attributes_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateAttributesConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateAttributesConfigRequest): + request = catalog_service.UpdateAttributesConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attributes_config is not None: + request.attributes_config = attributes_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_attributes_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config.name", request.attributes_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_catalog_attribute(self, + request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Adds the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_add_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.AddCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.AddCatalogAttributeRequest): + request = catalog_service.AddCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_catalog_attribute(self, + request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Removes the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.RemoveCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.RemoveCatalogAttributeRequest): + request = catalog_service.RemoveCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def replace_catalog_attribute(self, + request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Replaces the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ReplaceCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ReplaceCatalogAttributeRequest): + request = catalog_service.ReplaceCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.replace_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py new file mode 100644 index 00000000..f78d4bfa --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog_service + + +class ListCatalogsPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` + 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[..., catalog_service.ListCatalogsResponse], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2alpha.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + for page in self.pages: + yield from page.catalogs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCatalogsAsyncPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` + 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[catalog_service.ListCatalogsResponse]], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2alpha.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + async def async_generator(): + async for page in self.pages: + for response in page.catalogs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py new file mode 100644 index 00000000..0cffa336 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 CatalogServiceTransport +from .grpc import CatalogServiceGrpcTransport +from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] +_transport_registry['grpc'] = CatalogServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport + +__all__ = ( + 'CatalogServiceTransport', + 'CatalogServiceGrpcTransport', + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py new file mode 100644 index 00000000..8a244fb4 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py @@ -0,0 +1,297 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CatalogServiceTransport(abc.ABC): + """Abstract transport class for CatalogService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_catalogs: gapic_v1.method.wrap_method( + self.list_catalogs, + default_timeout=None, + client_info=client_info, + ), + self.update_catalog: gapic_v1.method.wrap_method( + self.update_catalog, + default_timeout=None, + client_info=client_info, + ), + self.set_default_branch: gapic_v1.method.wrap_method( + self.set_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_default_branch: gapic_v1.method.wrap_method( + self.get_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_completion_config: gapic_v1.method.wrap_method( + self.get_completion_config, + default_timeout=None, + client_info=client_info, + ), + self.update_completion_config: gapic_v1.method.wrap_method( + self.update_completion_config, + default_timeout=None, + client_info=client_info, + ), + self.get_attributes_config: gapic_v1.method.wrap_method( + self.get_attributes_config, + default_timeout=None, + client_info=client_info, + ), + self.update_attributes_config: gapic_v1.method.wrap_method( + self.update_attributes_config, + default_timeout=None, + client_info=client_info, + ), + self.add_catalog_attribute: gapic_v1.method.wrap_method( + self.add_catalog_attribute, + default_timeout=None, + client_info=client_info, + ), + self.remove_catalog_attribute: gapic_v1.method.wrap_method( + self.remove_catalog_attribute, + default_timeout=None, + client_info=client_info, + ), + self.replace_catalog_attribute: gapic_v1.method.wrap_method( + self.replace_catalog_attribute, + 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Union[ + catalog_service.ListCatalogsResponse, + Awaitable[catalog_service.ListCatalogsResponse] + ]]: + raise NotImplementedError() + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Union[ + gcr_catalog.Catalog, + Awaitable[gcr_catalog.Catalog] + ]]: + raise NotImplementedError() + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Union[ + catalog_service.GetDefaultBranchResponse, + Awaitable[catalog_service.GetDefaultBranchResponse] + ]]: + raise NotImplementedError() + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + Union[ + catalog.CompletionConfig, + Awaitable[catalog.CompletionConfig] + ]]: + raise NotImplementedError() + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + Union[ + catalog.CompletionConfig, + Awaitable[catalog.CompletionConfig] + ]]: + raise NotImplementedError() + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CatalogServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py new file mode 100644 index 00000000..4ebe0ff0 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py @@ -0,0 +1,600 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO + + +class CatalogServiceGrpcTransport(CatalogServiceTransport): + """gRPC backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + catalog_service.ListCatalogsResponse]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + ~.ListCatalogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + gcr_catalog.Catalog]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + ~.Catalog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + empty_pb2.Empty]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + ~.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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + catalog_service.GetDefaultBranchResponse]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + ~.GetDefaultBranchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + catalog.CompletionConfig]: + r"""Return a callable for the get completion config method over gRPC. + + Gets a + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. + + Returns: + Callable[[~.GetCompletionConfigRequest], + ~.CompletionConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetCompletionConfig', + request_serializer=catalog_service.GetCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['get_completion_config'] + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + catalog.CompletionConfig]: + r"""Return a callable for the update completion config method over gRPC. + + Updates the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. + + Returns: + Callable[[~.UpdateCompletionConfigRequest], + ~.CompletionConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateCompletionConfig', + request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['update_completion_config'] + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + catalog.AttributesConfig]: + r"""Return a callable for the get attributes config method over gRPC. + + Gets an + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + Returns: + Callable[[~.GetAttributesConfigRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetAttributesConfig', + request_serializer=catalog_service.GetAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['get_attributes_config'] + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + catalog.AttributesConfig]: + r"""Return a callable for the update attributes config method over gRPC. + + Updates the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + Returns: + Callable[[~.UpdateAttributesConfigRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateAttributesConfig', + request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['update_attributes_config'] + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the add catalog attribute method over gRPC. + + Adds the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.AddCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_catalog_attribute' not in self._stubs: + self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/AddCatalogAttribute', + request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['add_catalog_attribute'] + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the remove catalog attribute method over gRPC. + + Removes the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.RemoveCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_catalog_attribute' not in self._stubs: + self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/RemoveCatalogAttribute', + request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['remove_catalog_attribute'] + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the replace catalog attribute method over gRPC. + + Replaces the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.ReplaceCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_catalog_attribute' not in self._stubs: + self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/ReplaceCatalogAttribute', + request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['replace_catalog_attribute'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CatalogServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..15eacf16 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py @@ -0,0 +1,599 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CatalogServiceGrpcTransport + + +class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): + """gRPC AsyncIO backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Awaitable[catalog_service.ListCatalogsResponse]]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + Awaitable[~.ListCatalogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Awaitable[gcr_catalog.Catalog]]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + Awaitable[~.Catalog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + 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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Awaitable[catalog_service.GetDefaultBranchResponse]]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + Awaitable[~.GetDefaultBranchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + Awaitable[catalog.CompletionConfig]]: + r"""Return a callable for the get completion config method over gRPC. + + Gets a + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. + + Returns: + Callable[[~.GetCompletionConfigRequest], + Awaitable[~.CompletionConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetCompletionConfig', + request_serializer=catalog_service.GetCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['get_completion_config'] + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + Awaitable[catalog.CompletionConfig]]: + r"""Return a callable for the update completion config method over gRPC. + + Updates the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. + + Returns: + Callable[[~.UpdateCompletionConfigRequest], + Awaitable[~.CompletionConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateCompletionConfig', + request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['update_completion_config'] + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the get attributes config method over gRPC. + + Gets an + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + Returns: + Callable[[~.GetAttributesConfigRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetAttributesConfig', + request_serializer=catalog_service.GetAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['get_attributes_config'] + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the update attributes config method over gRPC. + + Updates the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + Returns: + Callable[[~.UpdateAttributesConfigRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateAttributesConfig', + request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['update_attributes_config'] + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the add catalog attribute method over gRPC. + + Adds the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.AddCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_catalog_attribute' not in self._stubs: + self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/AddCatalogAttribute', + request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['add_catalog_attribute'] + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the remove catalog attribute method over gRPC. + + Removes the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.RemoveCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_catalog_attribute' not in self._stubs: + self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/RemoveCatalogAttribute', + request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['remove_catalog_attribute'] + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the replace catalog attribute method over gRPC. + + Replaces the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.ReplaceCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_catalog_attribute' not in self._stubs: + self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/ReplaceCatalogAttribute', + request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['replace_catalog_attribute'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py new file mode 100644 index 00000000..b8af95bd --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CompletionServiceClient +from .async_client import CompletionServiceAsyncClient + +__all__ = ( + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py new file mode 100644 index 00000000..74888568 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .client import CompletionServiceClient + + +class CompletionServiceAsyncClient: + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: CompletionServiceClient + + DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(CompletionServiceClient.catalog_path) + parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) + common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CompletionServiceClient.common_project_path) + parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) + common_location_path = staticmethod(CompletionServiceClient.common_location_path) + parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CompletionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_complete_query(): + # Create a client + client = retail_v2alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_query, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_import_completion_data(): + # Create a client + client = retail_v2alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2alpha.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. + 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. + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_completion_data, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py new file mode 100644 index 00000000..6e783e95 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CompletionServiceGrpcTransport +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +class CompletionServiceClientMeta(type): + """Metaclass for the CompletionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] + _transport_registry["grpc"] = CompletionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CompletionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CompletionServiceClient(metaclass=CompletionServiceClientMeta): + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CompletionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CompletionServiceTransport): + # transport is a CompletionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_complete_query(): + # Create a client + client = retail_v2alpha.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a completion_service.CompleteQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, completion_service.CompleteQueryRequest): + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_import_completion_data(): + # Create a client + client = retail_v2alpha.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2alpha.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. + 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. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportCompletionDataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportCompletionDataRequest): + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_completion_data] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py new file mode 100644 index 00000000..a0c9542f --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CompletionServiceTransport +from .grpc import CompletionServiceGrpcTransport +from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] +_transport_registry['grpc'] = CompletionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport + +__all__ = ( + 'CompletionServiceTransport', + 'CompletionServiceGrpcTransport', + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py new file mode 100644 index 00000000..2e16e808 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CompletionServiceTransport(abc.ABC): + """Abstract transport class for CompletionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.complete_query: gapic_v1.method.wrap_method( + self.complete_query, + default_timeout=None, + client_info=client_info, + ), + self.import_completion_data: gapic_v1.method.wrap_method( + self.import_completion_data, + 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Union[ + completion_service.CompleteQueryResponse, + Awaitable[completion_service.CompleteQueryResponse] + ]]: + raise NotImplementedError() + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CompletionServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py new file mode 100644 index 00000000..dd953c63 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py @@ -0,0 +1,325 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO + + +class CompletionServiceGrpcTransport(CompletionServiceTransport): + """gRPC backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + ~.CompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + operations_pb2.Operation]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CompletionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..726b0e6e --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py @@ -0,0 +1,324 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CompletionServiceGrpcTransport + + +class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): + """gRPC AsyncIO backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Awaitable[completion_service.CompleteQueryResponse]]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + Awaitable[~.CompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + 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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py new file mode 100644 index 00000000..e9a7be2f --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ControlServiceClient +from .async_client import ControlServiceAsyncClient + +__all__ = ( + 'ControlServiceClient', + 'ControlServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py new file mode 100644 index 00000000..e32d838b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py @@ -0,0 +1,744 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.control_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.cloud.retail_v2alpha.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport +from .client import ControlServiceClient + + +class ControlServiceAsyncClient: + """Service for modifying Control.""" + + _client: ControlServiceClient + + DEFAULT_ENDPOINT = ControlServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ControlServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(ControlServiceClient.catalog_path) + parse_catalog_path = staticmethod(ControlServiceClient.parse_catalog_path) + control_path = staticmethod(ControlServiceClient.control_path) + parse_control_path = staticmethod(ControlServiceClient.parse_control_path) + common_billing_account_path = staticmethod(ControlServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ControlServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ControlServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ControlServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ControlServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ControlServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ControlServiceClient.common_project_path) + parse_common_project_path = staticmethod(ControlServiceClient.parse_common_project_path) + common_location_path = staticmethod(ControlServiceClient.common_location_path) + parse_common_location_path = staticmethod(ControlServiceClient.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: + ControlServiceAsyncClient: The constructed client. + """ + return ControlServiceClient.from_service_account_info.__func__(ControlServiceAsyncClient, 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: + ControlServiceAsyncClient: The constructed client. + """ + return ControlServiceClient.from_service_account_file.__func__(ControlServiceAsyncClient, 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 variabel 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 ControlServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ControlServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ControlServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ControlServiceClient).get_transport_class, type(ControlServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ControlServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the control service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ControlServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ControlServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_control(self, + request: Union[control_service.CreateControlRequest, dict] = None, + *, + parent: str = None, + control: gcr_control.Control = None, + control_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Creates a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_create_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = await client.create_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateControlRequest, dict]): + The request object. Request for CreateControl method. + parent (:class:`str`): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control (:class:`google.cloud.retail_v2alpha.types.Control`): + Required. The Control to create. + This corresponds to the ``control`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control_id (:class:`str`): + Required. The ID to use for the Control, which will + become the final component of the Control's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``control_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.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, control, control_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.CreateControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if control is not None: + request.control = control + if control_id is not None: + request.control_id = control_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_control(self, + request: Union[control_service.DeleteControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_delete_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteControlRequest( + name="name_value", + ) + + # Make the request + await client.delete_control(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteControlRequest, dict]): + The request object. Request for DeleteControl method. + name (:class:`str`): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.DeleteControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_control(self, + request: Union[control_service.UpdateControlRequest, dict] = None, + *, + control: gcr_control.Control = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Updates a Control. + + [Control][google.cloud.retail.v2alpha.Control] cannot be set to + a different oneof field, if so an INVALID_ARGUMENT is returned. + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.UpdateControlRequest( + control=control, + ) + + # Make the request + response = await client.update_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateControlRequest, dict]): + The request object. Request for UpdateControl method. + control (:class:`google.cloud.retail_v2alpha.types.Control`): + Required. The Control to update. + This corresponds to the ``control`` 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 + [Control][google.cloud.retail.v2alpha.Control] to + update. The following are NOT supported: + + - [Control.name][google.cloud.retail.v2alpha.Control.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([control, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.UpdateControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if control is not None: + request.control = control + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("control.name", request.control.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_control(self, + request: Union[control_service.GetControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> control.Control: + r"""Gets a Control. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetControlRequest( + name="name_value", + ) + + # Make the request + response = await client.get_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetControlRequest, dict]): + The request object. Request for GetControl method. + name (:class:`str`): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.GetControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_controls(self, + request: Union[control_service.ListControlsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListControlsAsyncPager: + r"""Lists all Controls linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_list_controls(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListControlsRequest, dict]): + The request object. Request for ListControls method. + parent (:class:`str`): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.control_service.pagers.ListControlsAsyncPager: + Response for ListControls method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.ListControlsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_controls, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListControlsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ControlServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py new file mode 100644 index 00000000..0981fa86 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py @@ -0,0 +1,953 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.control_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.cloud.retail_v2alpha.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ControlServiceGrpcTransport +from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport + + +class ControlServiceClientMeta(type): + """Metaclass for the ControlService 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[ControlServiceTransport]] + _transport_registry["grpc"] = ControlServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ControlServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ControlServiceTransport]: + """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 ControlServiceClient(metaclass=ControlServiceClientMeta): + """Service for modifying Control.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ControlServiceClient: 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: + ControlServiceClient: 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) -> ControlServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ControlServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def control_path(project: str,location: str,catalog: str,control: str,) -> str: + """Returns a fully-qualified control string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) + + @staticmethod + def parse_control_path(path: str) -> Dict[str,str]: + """Parses a control path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/controls/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ControlServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the control service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ControlServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ControlServiceTransport): + # transport is a ControlServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_control(self, + request: Union[control_service.CreateControlRequest, dict] = None, + *, + parent: str = None, + control: gcr_control.Control = None, + control_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Creates a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_create_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = client.create_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateControlRequest, dict]): + The request object. Request for CreateControl method. + parent (str): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control (google.cloud.retail_v2alpha.types.Control): + Required. The Control to create. + This corresponds to the ``control`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control_id (str): + Required. The ID to use for the Control, which will + become the final component of the Control's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``control_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.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, control, control_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.CreateControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.CreateControlRequest): + request = control_service.CreateControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if control is not None: + request.control = control + if control_id is not None: + request.control_id = control_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_control(self, + request: Union[control_service.DeleteControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_delete_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteControlRequest( + name="name_value", + ) + + # Make the request + client.delete_control(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteControlRequest, dict]): + The request object. Request for DeleteControl method. + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.DeleteControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.DeleteControlRequest): + request = control_service.DeleteControlRequest(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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_control(self, + request: Union[control_service.UpdateControlRequest, dict] = None, + *, + control: gcr_control.Control = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Updates a Control. + + [Control][google.cloud.retail.v2alpha.Control] cannot be set to + a different oneof field, if so an INVALID_ARGUMENT is returned. + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.UpdateControlRequest( + control=control, + ) + + # Make the request + response = client.update_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateControlRequest, dict]): + The request object. Request for UpdateControl method. + control (google.cloud.retail_v2alpha.types.Control): + Required. The Control to update. + This corresponds to the ``control`` 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 + [Control][google.cloud.retail.v2alpha.Control] to + update. The following are NOT supported: + + - [Control.name][google.cloud.retail.v2alpha.Control.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([control, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.UpdateControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.UpdateControlRequest): + request = control_service.UpdateControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if control is not None: + request.control = control + 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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("control.name", request.control.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_control(self, + request: Union[control_service.GetControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> control.Control: + r"""Gets a Control. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetControlRequest( + name="name_value", + ) + + # Make the request + response = client.get_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetControlRequest, dict]): + The request object. Request for GetControl method. + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.GetControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.GetControlRequest): + request = control_service.GetControlRequest(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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_controls(self, + request: Union[control_service.ListControlsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListControlsPager: + r"""Lists all Controls linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_list_controls(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListControlsRequest, dict]): + The request object. Request for ListControls method. + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.control_service.pagers.ListControlsPager: + Response for ListControls method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.ListControlsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.ListControlsRequest): + request = control_service.ListControlsRequest(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_controls] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListControlsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ControlServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py new file mode 100644 index 00000000..d1c28748 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control_service + + +class ListControlsPager: + """A pager for iterating through ``list_controls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``controls`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListControls`` requests and continue to iterate + through the ``controls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` + 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[..., control_service.ListControlsResponse], + request: control_service.ListControlsRequest, + response: control_service.ListControlsResponse, + *, + 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.retail_v2alpha.types.ListControlsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListControlsResponse): + 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 = control_service.ListControlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[control_service.ListControlsResponse]: + 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[control.Control]: + for page in self.pages: + yield from page.controls + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListControlsAsyncPager: + """A pager for iterating through ``list_controls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``controls`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListControls`` requests and continue to iterate + through the ``controls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` + 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[control_service.ListControlsResponse]], + request: control_service.ListControlsRequest, + response: control_service.ListControlsResponse, + *, + 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.retail_v2alpha.types.ListControlsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListControlsResponse): + 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 = control_service.ListControlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[control_service.ListControlsResponse]: + 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[control.Control]: + async def async_generator(): + async for page in self.pages: + for response in page.controls: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py new file mode 100644 index 00000000..3622876b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ControlServiceTransport +from .grpc import ControlServiceGrpcTransport +from .grpc_asyncio import ControlServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ControlServiceTransport]] +_transport_registry['grpc'] = ControlServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ControlServiceGrpcAsyncIOTransport + +__all__ = ( + 'ControlServiceTransport', + 'ControlServiceGrpcTransport', + 'ControlServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py new file mode 100644 index 00000000..ef91c3df --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ControlServiceTransport(abc.ABC): + """Abstract transport class for ControlService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_control: gapic_v1.method.wrap_method( + self.create_control, + default_timeout=None, + client_info=client_info, + ), + self.delete_control: gapic_v1.method.wrap_method( + self.delete_control, + default_timeout=None, + client_info=client_info, + ), + self.update_control: gapic_v1.method.wrap_method( + self.update_control, + default_timeout=None, + client_info=client_info, + ), + self.get_control: gapic_v1.method.wrap_method( + self.get_control, + default_timeout=None, + client_info=client_info, + ), + self.list_controls: gapic_v1.method.wrap_method( + self.list_controls, + 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 create_control(self) -> Callable[ + [control_service.CreateControlRequest], + Union[ + gcr_control.Control, + Awaitable[gcr_control.Control] + ]]: + raise NotImplementedError() + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + Union[ + gcr_control.Control, + Awaitable[gcr_control.Control] + ]]: + raise NotImplementedError() + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + Union[ + control.Control, + Awaitable[control.Control] + ]]: + raise NotImplementedError() + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + Union[ + control_service.ListControlsResponse, + Awaitable[control_service.ListControlsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ControlServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py new file mode 100644 index 00000000..121caf7d --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py @@ -0,0 +1,382 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO + + +class ControlServiceGrpcTransport(ControlServiceTransport): + """gRPC backend transport for ControlService. + + Service for modifying Control. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_control(self) -> Callable[ + [control_service.CreateControlRequest], + gcr_control.Control]: + r"""Return a callable for the create control method over gRPC. + + Creates a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['create_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/CreateControl', + request_serializer=control_service.CreateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['create_control'] + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete control method over gRPC. + + Deletes a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteControlRequest], + ~.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_control' not in self._stubs: + self._stubs['delete_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/DeleteControl', + request_serializer=control_service.DeleteControlRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_control'] + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + gcr_control.Control]: + r"""Return a callable for the update control method over gRPC. + + Updates a Control. + + [Control][google.cloud.retail.v2alpha.Control] cannot be set to + a different oneof field, if so an INVALID_ARGUMENT is returned. + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['update_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/UpdateControl', + request_serializer=control_service.UpdateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['update_control'] + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + control.Control]: + r"""Return a callable for the get control method over gRPC. + + Gets a Control. + + Returns: + Callable[[~.GetControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['get_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/GetControl', + request_serializer=control_service.GetControlRequest.serialize, + response_deserializer=control.Control.deserialize, + ) + return self._stubs['get_control'] + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + control_service.ListControlsResponse]: + r"""Return a callable for the list controls method over gRPC. + + Lists all Controls linked to this catalog. + + Returns: + Callable[[~.ListControlsRequest], + ~.ListControlsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_controls' not in self._stubs: + self._stubs['list_controls'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/ListControls', + request_serializer=control_service.ListControlsRequest.serialize, + response_deserializer=control_service.ListControlsResponse.deserialize, + ) + return self._stubs['list_controls'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ControlServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..9703924c --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ControlServiceGrpcTransport + + +class ControlServiceGrpcAsyncIOTransport(ControlServiceTransport): + """gRPC AsyncIO backend transport for ControlService. + + Service for modifying Control. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_control(self) -> Callable[ + [control_service.CreateControlRequest], + Awaitable[gcr_control.Control]]: + r"""Return a callable for the create control method over gRPC. + + Creates a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['create_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/CreateControl', + request_serializer=control_service.CreateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['create_control'] + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete control method over gRPC. + + Deletes a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteControlRequest], + 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_control' not in self._stubs: + self._stubs['delete_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/DeleteControl', + request_serializer=control_service.DeleteControlRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_control'] + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + Awaitable[gcr_control.Control]]: + r"""Return a callable for the update control method over gRPC. + + Updates a Control. + + [Control][google.cloud.retail.v2alpha.Control] cannot be set to + a different oneof field, if so an INVALID_ARGUMENT is returned. + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['update_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/UpdateControl', + request_serializer=control_service.UpdateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['update_control'] + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + Awaitable[control.Control]]: + r"""Return a callable for the get control method over gRPC. + + Gets a Control. + + Returns: + Callable[[~.GetControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['get_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/GetControl', + request_serializer=control_service.GetControlRequest.serialize, + response_deserializer=control.Control.deserialize, + ) + return self._stubs['get_control'] + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + Awaitable[control_service.ListControlsResponse]]: + r"""Return a callable for the list controls method over gRPC. + + Lists all Controls linked to this catalog. + + Returns: + Callable[[~.ListControlsRequest], + Awaitable[~.ListControlsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_controls' not in self._stubs: + self._stubs['list_controls'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/ListControls', + request_serializer=control_service.ListControlsRequest.serialize, + response_deserializer=control_service.ListControlsResponse.deserialize, + ) + return self._stubs['list_controls'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ControlServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py new file mode 100644 index 00000000..7c079c80 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import PredictionServiceClient +from .async_client import PredictionServiceAsyncClient + +__all__ = ( + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py new file mode 100644 index 00000000..b9255f77 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport +from .client import PredictionServiceClient + + +class PredictionServiceAsyncClient: + """Service for making recommendation prediction.""" + + _client: PredictionServiceClient + + DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT + + product_path = staticmethod(PredictionServiceClient.product_path) + parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) + common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(PredictionServiceClient.common_project_path) + parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) + common_location_path = staticmethod(PredictionServiceClient.common_location_path) + parse_common_location_path = staticmethod(PredictionServiceClient.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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PredictionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_predict(): + # Create a client + client = retail_v2alpha.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + request = prediction_service.PredictRequest(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.predict, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py new file mode 100644 index 00000000..1cb0e419 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py @@ -0,0 +1,480 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionServiceGrpcTransport +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +class PredictionServiceClientMeta(type): + """Metaclass for the PredictionService 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[PredictionServiceTransport]] + _transport_registry["grpc"] = PredictionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PredictionServiceTransport]: + """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): + """Service for making recommendation prediction.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PredictionServiceClient: 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: + PredictionServiceClient: 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) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PredictionServiceTransport): + # transport is a PredictionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_predict(): + # Create a client + client = retail_v2alpha.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a prediction_service.PredictRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_service.PredictRequest): + request = prediction_service.PredictRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.predict] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py new file mode 100644 index 00000000..bb65c664 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PredictionServiceTransport +from .grpc import PredictionServiceGrpcTransport +from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] +_transport_registry['grpc'] = PredictionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport + +__all__ = ( + 'PredictionServiceTransport', + 'PredictionServiceGrpcTransport', + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py new file mode 100644 index 00000000..a5424c9e --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PredictionServiceTransport(abc.ABC): + """Abstract transport class for PredictionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.predict: gapic_v1.method.wrap_method( + self.predict, + 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + Union[ + prediction_service.PredictResponse, + Awaitable[prediction_service.PredictResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'PredictionServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py new file mode 100644 index 00000000..0e227d35 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py @@ -0,0 +1,264 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO + + +class PredictionServiceGrpcTransport(PredictionServiceTransport): + """gRPC backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + prediction_service.PredictResponse]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + ~.PredictResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'PredictionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..26a9ecfc --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import PredictionServiceGrpcTransport + + +class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): + """gRPC AsyncIO backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + Awaitable[prediction_service.PredictResponse]]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + Awaitable[~.PredictResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py new file mode 100644 index 00000000..0fa6330a --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ProductServiceClient +from .async_client import ProductServiceAsyncClient + +__all__ = ( + 'ProductServiceClient', + 'ProductServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py new file mode 100644 index 00000000..2933dcb8 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py @@ -0,0 +1,1804 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.services.product_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import purge_config +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport +from .client import ProductServiceClient + + +class ProductServiceAsyncClient: + """Service for ingesting [Product][google.cloud.retail.v2alpha.Product] + information of the customer's website. + """ + + _client: ProductServiceClient + + DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(ProductServiceClient.branch_path) + parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) + product_path = staticmethod(ProductServiceClient.product_path) + parse_product_path = staticmethod(ProductServiceClient.parse_product_path) + common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProductServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProductServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProductServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProductServiceClient.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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ProductServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ProductServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_create_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`google.cloud.retail_v2alpha.types.Product`): + Required. The + [Product][google.cloud.retail.v2alpha.Product] to + create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + Required. The ID to use for the + [Product][google.cloud.retail.v2alpha.Product], which + will become the final component of the + [Product.name][google.cloud.retail.v2alpha.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This field must be unique among all + [Product][google.cloud.retail.v2alpha.Product]s with the + same + [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Product][google.cloud.retail.v2alpha.Product] 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.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_list_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2alpha.Product]s under + this branch, regardless of whether or not this branch + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.product_service.pagers.ListProductsAsyncPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (:class:`google.cloud.retail_v2alpha.types.Product`): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2alpha.Product] to + update. The immutable and output only fields are NOT + supported. If not set, all supported fields (the fields + that are neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_delete_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2alpha.Product] to + delete can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product] member + nor a + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] with more + than one + [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2alpha.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def purge_products(self, + request: Union[purge_config.PurgeProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Permanently deletes all selected + [Product][google.cloud.retail.v2alpha.Product]s under a branch. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed offline. Depending on the + number of [Product][google.cloud.retail.v2alpha.Product]s, this + operation could take hours to complete. Before the operation + completes, some [Product][google.cloud.retail.v2alpha.Product]s + may still be returned by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Depending on the number of + [Product][google.cloud.retail.v2alpha.Product]s, this operation + could take hours to complete. To get a sample of + [Product][google.cloud.retail.v2alpha.Product]s that would be + deleted, set + [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] + to false. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_purge_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeProductsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PurgeProductsRequest, dict]): + The request object. Request message for PurgeProducts + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.PurgeProductsResponse` Response of the PurgeProductsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeProductsResponse, + metadata_type=purge_config.PurgeProductsMetadata, + ) + + # Done; return the response. + return response + + async def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2alpha.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2alpha.Product]s to be + successfully updated. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_import_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2alpha.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2alpha.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_set_inventory(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2alpha.Product() + inventory.title = "title_value" + + request = retail_v2alpha.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (:class:`google.cloud.retail_v2alpha.types.Product`): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product] named in + [Product.name][google.cloud.retail.v2alpha.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2alpha.Product] to + update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.SetInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_inventory, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + async def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [AddFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_add_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [AddLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_remove_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py new file mode 100644 index 00000000..6206989b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py @@ -0,0 +1,2008 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.services.product_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import purge_config +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductServiceGrpcTransport +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +class ProductServiceClientMeta(type): + """Metaclass for the ProductService 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[ProductServiceTransport]] + _transport_registry["grpc"] = ProductServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ProductServiceTransport]: + """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 ProductServiceClient(metaclass=ProductServiceClientMeta): + """Service for ingesting [Product][google.cloud.retail.v2alpha.Product] + information of the customer's website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProductServiceClient: 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: + ProductServiceClient: 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) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ProductServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProductServiceTransport): + # transport is a ProductServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_create_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (google.cloud.retail_v2alpha.types.Product): + Required. The + [Product][google.cloud.retail.v2alpha.Product] to + create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2alpha.Product], which + will become the final component of the + [Product.name][google.cloud.retail.v2alpha.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This field must be unique among all + [Product][google.cloud.retail.v2alpha.Product]s with the + same + [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.CreateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.CreateProductRequest): + request = product_service.CreateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Product][google.cloud.retail.v2alpha.Product] 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.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.GetProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.GetProductRequest): + request = product_service.GetProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_list_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2alpha.Product]s under + this branch, regardless of whether or not this branch + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.product_service.pagers.ListProductsPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.ListProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.ListProductsRequest): + request = product_service.ListProductsRequest(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_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (google.cloud.retail_v2alpha.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2alpha.Product] to + update. The immutable and output only fields are NOT + supported. If not set, all supported fields (the fields + that are neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.UpdateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.UpdateProductRequest): + request = product_service.UpdateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + 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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_delete_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2alpha.Product] to + delete can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product] member + nor a + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] with more + than one + [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2alpha.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.DeleteProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.DeleteProductRequest): + request = product_service.DeleteProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def purge_products(self, + request: Union[purge_config.PurgeProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Permanently deletes all selected + [Product][google.cloud.retail.v2alpha.Product]s under a branch. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed offline. Depending on the + number of [Product][google.cloud.retail.v2alpha.Product]s, this + operation could take hours to complete. Before the operation + completes, some [Product][google.cloud.retail.v2alpha.Product]s + may still be returned by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Depending on the number of + [Product][google.cloud.retail.v2alpha.Product]s, this operation + could take hours to complete. To get a sample of + [Product][google.cloud.retail.v2alpha.Product]s that would be + deleted, set + [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] + to false. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_purge_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeProductsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PurgeProductsRequest, dict]): + The request object. Request message for PurgeProducts + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.PurgeProductsResponse` Response of the PurgeProductsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeProductsRequest): + request = purge_config.PurgeProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeProductsResponse, + metadata_type=purge_config.PurgeProductsMetadata, + ) + + # Done; return the response. + return response + + def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2alpha.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2alpha.Product]s to be + successfully updated. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_import_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2alpha.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportProductsRequest): + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2alpha.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_set_inventory(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2alpha.Product() + inventory.title = "title_value" + + request = retail_v2alpha.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (google.cloud.retail_v2alpha.types.Product): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product] named in + [Product.name][google.cloud.retail.v2alpha.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2alpha.Product] to + update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.SetInventoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.SetInventoryRequest): + request = product_service.SetInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_add_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [AddFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddFulfillmentPlacesRequest): + request = product_service.AddFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): + request = product_service.RemoveFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_add_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [AddLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddLocalInventoriesRequest): + request = product_service.AddLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_remove_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveLocalInventoriesRequest): + request = product_service.RemoveLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py new file mode 100644 index 00000000..5e235009 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product_service + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` + 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[..., product_service.ListProductsResponse], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2alpha.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[product_service.ListProductsResponse]: + 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[product.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` + 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[product_service.ListProductsResponse]], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2alpha.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: + 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[product.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py new file mode 100644 index 00000000..db824dec --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ProductServiceTransport +from .grpc import ProductServiceGrpcTransport +from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] +_transport_registry['grpc'] = ProductServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport + +__all__ = ( + 'ProductServiceTransport', + 'ProductServiceGrpcTransport', + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py new file mode 100644 index 00000000..fe69ccf2 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import purge_config +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ProductServiceTransport(abc.ABC): + """Abstract transport class for ProductService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_product: gapic_v1.method.wrap_method( + self.create_product, + default_timeout=None, + client_info=client_info, + ), + self.get_product: gapic_v1.method.wrap_method( + self.get_product, + default_timeout=None, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + default_timeout=None, + client_info=client_info, + ), + self.update_product: gapic_v1.method.wrap_method( + self.update_product, + default_timeout=None, + client_info=client_info, + ), + self.delete_product: gapic_v1.method.wrap_method( + self.delete_product, + default_timeout=None, + client_info=client_info, + ), + self.purge_products: gapic_v1.method.wrap_method( + self.purge_products, + default_timeout=None, + client_info=client_info, + ), + self.import_products: gapic_v1.method.wrap_method( + self.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.set_inventory: gapic_v1.method.wrap_method( + self.set_inventory, + default_timeout=None, + client_info=client_info, + ), + self.add_fulfillment_places: gapic_v1.method.wrap_method( + self.add_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.remove_fulfillment_places: gapic_v1.method.wrap_method( + self.remove_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.add_local_inventories: gapic_v1.method.wrap_method( + self.add_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.remove_local_inventories: gapic_v1.method.wrap_method( + self.remove_local_inventories, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Union[ + product.Product, + Awaitable[product.Product] + ]]: + raise NotImplementedError() + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Union[ + product_service.ListProductsResponse, + Awaitable[product_service.ListProductsResponse] + ]]: + raise NotImplementedError() + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def purge_products(self) -> Callable[ + [purge_config.PurgeProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProductServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py new file mode 100644 index 00000000..72a1777c --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py @@ -0,0 +1,726 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import purge_config +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO + + +class ProductServiceGrpcTransport(ProductServiceTransport): + """gRPC backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2alpha.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + gcr_product.Product]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.CreateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + product.Product]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + product_service.ListProductsResponse]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + gcr_product.Product]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + ~.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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def purge_products(self) -> Callable[ + [purge_config.PurgeProductsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge products method over gRPC. + + Permanently deletes all selected + [Product][google.cloud.retail.v2alpha.Product]s under a branch. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed offline. Depending on the + number of [Product][google.cloud.retail.v2alpha.Product]s, this + operation could take hours to complete. Before the operation + completes, some [Product][google.cloud.retail.v2alpha.Product]s + may still be returned by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Depending on the number of + [Product][google.cloud.retail.v2alpha.Product]s, this operation + could take hours to complete. To get a sample of + [Product][google.cloud.retail.v2alpha.Product]s that would be + deleted, set + [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] + to false. + + Returns: + Callable[[~.PurgeProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_products' not in self._stubs: + self._stubs['purge_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/PurgeProducts', + request_serializer=purge_config.PurgeProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_products'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2alpha.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2alpha.Product]s to be + successfully updated. + + Returns: + Callable[[~.ImportProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + operations_pb2.Operation]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2alpha.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProductServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..f130d491 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py @@ -0,0 +1,725 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import purge_config +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductServiceGrpcTransport + + +class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): + """gRPC AsyncIO backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2alpha.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.CreateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Awaitable[product.Product]]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Awaitable[product_service.ListProductsResponse]]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + 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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def purge_products(self) -> Callable[ + [purge_config.PurgeProductsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge products method over gRPC. + + Permanently deletes all selected + [Product][google.cloud.retail.v2alpha.Product]s under a branch. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed offline. Depending on the + number of [Product][google.cloud.retail.v2alpha.Product]s, this + operation could take hours to complete. Before the operation + completes, some [Product][google.cloud.retail.v2alpha.Product]s + may still be returned by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Depending on the number of + [Product][google.cloud.retail.v2alpha.Product]s, this operation + could take hours to complete. To get a sample of + [Product][google.cloud.retail.v2alpha.Product]s that would be + deleted, set + [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] + to false. + + Returns: + Callable[[~.PurgeProductsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_products' not in self._stubs: + self._stubs['purge_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/PurgeProducts', + request_serializer=purge_config.PurgeProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_products'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2alpha.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2alpha.Product]s to be + successfully updated. + + Returns: + Callable[[~.ImportProductsRequest], + 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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2alpha.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + 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 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + 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 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + 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 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + 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 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py new file mode 100644 index 00000000..2f63fc22 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SearchServiceClient +from .async_client import SearchServiceAsyncClient + +__all__ = ( + 'SearchServiceClient', + 'SearchServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py new file mode 100644 index 00000000..d39b3203 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.search_service import pagers +from google.cloud.retail_v2alpha.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .client import SearchServiceClient + + +class SearchServiceAsyncClient: + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: SearchServiceClient + + DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(SearchServiceClient.branch_path) + parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + product_path = staticmethod(SearchServiceClient.product_path) + parse_product_path = staticmethod(SearchServiceClient.parse_product_path) + common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(SearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SearchServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAsyncPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_search(): + # Create a client + client = retail_v2alpha.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.search_service.pagers.SearchAsyncPager: + Response message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py new file mode 100644 index 00000000..4786889b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py @@ -0,0 +1,513 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.search_service import pagers +from google.cloud.retail_v2alpha.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SearchServiceGrpcTransport +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +class SearchServiceClientMeta(type): + """Metaclass for the SearchService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] + _transport_registry["grpc"] = SearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SearchServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SearchServiceClient(metaclass=SearchServiceClientMeta): + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SearchServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SearchServiceTransport): + # transport is a SearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_search(): + # Create a client + client = retail_v2alpha.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.search_service.pagers.SearchPager: + Response message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a search_service.SearchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py new file mode 100644 index 00000000..7487beee --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import search_service + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2alpha.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2alpha.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py new file mode 100644 index 00000000..7917cd1d --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SearchServiceTransport +from .grpc import SearchServiceGrpcTransport +from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] +_transport_registry['grpc'] = SearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport + +__all__ = ( + 'SearchServiceTransport', + 'SearchServiceGrpcTransport', + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py new file mode 100644 index 00000000..f986834a --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import search_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SearchServiceTransport(abc.ABC): + """Abstract transport class for SearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search: gapic_v1.method.wrap_method( + self.search, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Union[ + search_service.SearchResponse, + Awaitable[search_service.SearchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SearchServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py new file mode 100644 index 00000000..04e76b79 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py @@ -0,0 +1,270 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO + + +class SearchServiceGrpcTransport(SearchServiceTransport): + """gRPC backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..26b52d69 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SearchServiceGrpcTransport + + +class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): + """gRPC AsyncIO backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Awaitable[search_service.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py new file mode 100644 index 00000000..d1a0a023 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ServingConfigServiceClient +from .async_client import ServingConfigServiceAsyncClient + +__all__ = ( + 'ServingConfigServiceClient', + 'ServingConfigServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py new file mode 100644 index 00000000..4f047853 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py @@ -0,0 +1,954 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.serving_config_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport +from .client import ServingConfigServiceClient + + +class ServingConfigServiceAsyncClient: + """Service for modifying ServingConfig.""" + + _client: ServingConfigServiceClient + + DEFAULT_ENDPOINT = ServingConfigServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ServingConfigServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(ServingConfigServiceClient.catalog_path) + parse_catalog_path = staticmethod(ServingConfigServiceClient.parse_catalog_path) + serving_config_path = staticmethod(ServingConfigServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(ServingConfigServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(ServingConfigServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ServingConfigServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ServingConfigServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ServingConfigServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ServingConfigServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ServingConfigServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ServingConfigServiceClient.common_project_path) + parse_common_project_path = staticmethod(ServingConfigServiceClient.parse_common_project_path) + common_location_path = staticmethod(ServingConfigServiceClient.common_location_path) + parse_common_location_path = staticmethod(ServingConfigServiceClient.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: + ServingConfigServiceAsyncClient: The constructed client. + """ + return ServingConfigServiceClient.from_service_account_info.__func__(ServingConfigServiceAsyncClient, 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: + ServingConfigServiceAsyncClient: The constructed client. + """ + return ServingConfigServiceClient.from_service_account_file.__func__(ServingConfigServiceAsyncClient, 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 variabel 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 ServingConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ServingConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ServingConfigServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ServingConfigServiceClient).get_transport_class, type(ServingConfigServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ServingConfigServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the serving config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ServingConfigServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ServingConfigServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_serving_config(self, + request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, + *, + parent: str = None, + serving_config: gcr_serving_config.ServingConfig = None, + serving_config_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_create_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = await client.create_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateServingConfigRequest, dict]): + The request object. Request for CreateServingConfig + method. + parent (:class:`str`): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config (:class:`google.cloud.retail_v2alpha.types.ServingConfig`): + Required. The ServingConfig to + create. + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config_id (:class:`str`): + Required. The ID to use for the ServingConfig, which + will become the final component of the ServingConfig's + resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``serving_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, serving_config, serving_config_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.CreateServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if serving_config is not None: + request.serving_config = serving_config + if serving_config_id is not None: + request.serving_config_id = serving_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_serving_config(self, + request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_delete_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_serving_config(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteServingConfigRequest, dict]): + The request object. Request for DeleteServingConfig + method. + name (:class:`str`): + Required. The resource name of the ServingConfig to + delete. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.DeleteServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_serving_config(self, + request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, + *, + serving_config: gcr_serving_config.ServingConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Updates a ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = await client.update_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateServingConfigRequest, dict]): + The request object. Request for UpdateServingConfig + method. + serving_config (:class:`google.cloud.retail_v2alpha.types.ServingConfig`): + Required. The ServingConfig to + update. + + This corresponds to the ``serving_config`` 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 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.UpdateServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config.name", request.serving_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_serving_config(self, + request: Union[serving_config_service.GetServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> serving_config.ServingConfig: + r"""Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetServingConfigRequest, dict]): + The request object. Request for GetServingConfig method. + name (:class:`str`): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.GetServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_serving_configs(self, + request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServingConfigsAsyncPager: + r"""Lists all ServingConfigs linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_list_serving_configs(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListServingConfigsRequest, dict]): + The request object. Request for ListServingConfigs + method. + parent (:class:`str`): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsAsyncPager: + Response for ListServingConfigs + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.ListServingConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_serving_configs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServingConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_control(self, + request: Union[serving_config_service.AddControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_add_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.add_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddControlRequest, dict]): + The request object. Request for AddControl method. + serving_config (:class:`str`): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.AddControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_control(self, + request: Union[serving_config_service.RemoveControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_remove_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.remove_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveControlRequest, dict]): + The request object. Request for RemoveControl method. + serving_config (:class:`str`): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.RemoveControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServingConfigServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py new file mode 100644 index 00000000..d9d8e276 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py @@ -0,0 +1,1163 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.serving_config_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ServingConfigServiceGrpcTransport +from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport + + +class ServingConfigServiceClientMeta(type): + """Metaclass for the ServingConfigService 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[ServingConfigServiceTransport]] + _transport_registry["grpc"] = ServingConfigServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ServingConfigServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ServingConfigServiceTransport]: + """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 ServingConfigServiceClient(metaclass=ServingConfigServiceClientMeta): + """Service for modifying ServingConfig.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServingConfigServiceClient: 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: + ServingConfigServiceClient: 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) -> ServingConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ServingConfigServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,catalog: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ServingConfigServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the serving config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ServingConfigServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ServingConfigServiceTransport): + # transport is a ServingConfigServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_serving_config(self, + request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, + *, + parent: str = None, + serving_config: gcr_serving_config.ServingConfig = None, + serving_config_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_create_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = client.create_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateServingConfigRequest, dict]): + The request object. Request for CreateServingConfig + method. + parent (str): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config (google.cloud.retail_v2alpha.types.ServingConfig): + Required. The ServingConfig to + create. + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config_id (str): + Required. The ID to use for the ServingConfig, which + will become the final component of the ServingConfig's + resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``serving_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, serving_config, serving_config_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.CreateServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.CreateServingConfigRequest): + request = serving_config_service.CreateServingConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if serving_config is not None: + request.serving_config = serving_config + if serving_config_id is not None: + request.serving_config_id = serving_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_serving_config(self, + request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_delete_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_serving_config(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteServingConfigRequest, dict]): + The request object. Request for DeleteServingConfig + method. + name (str): + Required. The resource name of the ServingConfig to + delete. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.DeleteServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.DeleteServingConfigRequest): + request = serving_config_service.DeleteServingConfigRequest(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_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_serving_config(self, + request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, + *, + serving_config: gcr_serving_config.ServingConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Updates a ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = client.update_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateServingConfigRequest, dict]): + The request object. Request for UpdateServingConfig + method. + serving_config (google.cloud.retail_v2alpha.types.ServingConfig): + Required. The ServingConfig to + update. + + This corresponds to the ``serving_config`` 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 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.UpdateServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.UpdateServingConfigRequest): + request = serving_config_service.UpdateServingConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config.name", request.serving_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_serving_config(self, + request: Union[serving_config_service.GetServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> serving_config.ServingConfig: + r"""Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetServingConfigRequest, dict]): + The request object. Request for GetServingConfig method. + name (str): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.GetServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.GetServingConfigRequest): + request = serving_config_service.GetServingConfigRequest(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_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_serving_configs(self, + request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServingConfigsPager: + r"""Lists all ServingConfigs linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_list_serving_configs(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListServingConfigsRequest, dict]): + The request object. Request for ListServingConfigs + method. + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsPager: + Response for ListServingConfigs + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.ListServingConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.ListServingConfigsRequest): + request = serving_config_service.ListServingConfigsRequest(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_serving_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListServingConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_control(self, + request: Union[serving_config_service.AddControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_add_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.add_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddControlRequest, dict]): + The request object. Request for AddControl method. + serving_config (str): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.AddControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.AddControlRequest): + request = serving_config_service.AddControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_control(self, + request: Union[serving_config_service.RemoveControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_remove_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.remove_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveControlRequest, dict]): + The request object. Request for RemoveControl method. + serving_config (str): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.RemoveControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.RemoveControlRequest): + request = serving_config_service.RemoveControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServingConfigServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py new file mode 100644 index 00000000..8c4975b7 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config_service + + +class ListServingConfigsPager: + """A pager for iterating through ``list_serving_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``serving_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServingConfigs`` requests and continue to iterate + through the ``serving_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` + 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[..., serving_config_service.ListServingConfigsResponse], + request: serving_config_service.ListServingConfigsRequest, + response: serving_config_service.ListServingConfigsResponse, + *, + 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.retail_v2alpha.types.ListServingConfigsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListServingConfigsResponse): + 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 = serving_config_service.ListServingConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[serving_config_service.ListServingConfigsResponse]: + 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[serving_config.ServingConfig]: + for page in self.pages: + yield from page.serving_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServingConfigsAsyncPager: + """A pager for iterating through ``list_serving_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``serving_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServingConfigs`` requests and continue to iterate + through the ``serving_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` + 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[serving_config_service.ListServingConfigsResponse]], + request: serving_config_service.ListServingConfigsRequest, + response: serving_config_service.ListServingConfigsResponse, + *, + 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.retail_v2alpha.types.ListServingConfigsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListServingConfigsResponse): + 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 = serving_config_service.ListServingConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[serving_config_service.ListServingConfigsResponse]: + 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[serving_config.ServingConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.serving_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py new file mode 100644 index 00000000..3726ac83 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ServingConfigServiceTransport +from .grpc import ServingConfigServiceGrpcTransport +from .grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ServingConfigServiceTransport]] +_transport_registry['grpc'] = ServingConfigServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ServingConfigServiceGrpcAsyncIOTransport + +__all__ = ( + 'ServingConfigServiceTransport', + 'ServingConfigServiceGrpcTransport', + 'ServingConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py new file mode 100644 index 00000000..94052dd6 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ServingConfigServiceTransport(abc.ABC): + """Abstract transport class for ServingConfigService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_serving_config: gapic_v1.method.wrap_method( + self.create_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_serving_config: gapic_v1.method.wrap_method( + self.delete_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.update_serving_config: gapic_v1.method.wrap_method( + self.update_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.get_serving_config: gapic_v1.method.wrap_method( + self.get_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.list_serving_configs: gapic_v1.method.wrap_method( + self.list_serving_configs, + default_timeout=None, + client_info=client_info, + ), + self.add_control: gapic_v1.method.wrap_method( + self.add_control, + default_timeout=None, + client_info=client_info, + ), + self.remove_control: gapic_v1.method.wrap_method( + self.remove_control, + 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 create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + Union[ + serving_config.ServingConfig, + Awaitable[serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + Union[ + serving_config_service.ListServingConfigsResponse, + Awaitable[serving_config_service.ListServingConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ServingConfigServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py new file mode 100644 index 00000000..0acec25b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py @@ -0,0 +1,440 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO + + +class ServingConfigServiceGrpcTransport(ServingConfigServiceTransport): + """gRPC backend transport for ServingConfigService. + + Service for modifying ServingConfig. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the create serving config method over gRPC. + + Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + Returns: + Callable[[~.CreateServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/CreateServingConfig', + request_serializer=serving_config_service.CreateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['create_serving_config'] + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete serving config method over gRPC. + + Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.DeleteServingConfigRequest], + ~.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_serving_config' not in self._stubs: + self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/DeleteServingConfig', + request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_serving_config'] + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the update serving config method over gRPC. + + Updates a ServingConfig. + + Returns: + Callable[[~.UpdateServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/UpdateServingConfig', + request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['update_serving_config'] + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + serving_config.ServingConfig]: + r"""Return a callable for the get serving config method over gRPC. + + Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.GetServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/GetServingConfig', + request_serializer=serving_config_service.GetServingConfigRequest.serialize, + response_deserializer=serving_config.ServingConfig.deserialize, + ) + return self._stubs['get_serving_config'] + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + serving_config_service.ListServingConfigsResponse]: + r"""Return a callable for the list serving configs method over gRPC. + + Lists all ServingConfigs linked to this catalog. + + Returns: + Callable[[~.ListServingConfigsRequest], + ~.ListServingConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: + self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/ListServingConfigs', + request_serializer=serving_config_service.ListServingConfigsRequest.serialize, + response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, + ) + return self._stubs['list_serving_configs'] + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the add control method over gRPC. + + Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + Returns: + Callable[[~.AddControlRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_control' not in self._stubs: + self._stubs['add_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/AddControl', + request_serializer=serving_config_service.AddControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['add_control'] + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the remove control method over gRPC. + + Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + Returns: + Callable[[~.RemoveControlRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_control' not in self._stubs: + self._stubs['remove_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/RemoveControl', + request_serializer=serving_config_service.RemoveControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['remove_control'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ServingConfigServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..e3d2ccca --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py @@ -0,0 +1,439 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ServingConfigServiceGrpcTransport + + +class ServingConfigServiceGrpcAsyncIOTransport(ServingConfigServiceTransport): + """gRPC AsyncIO backend transport for ServingConfigService. + + Service for modifying ServingConfig. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the create serving config method over gRPC. + + Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + Returns: + Callable[[~.CreateServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/CreateServingConfig', + request_serializer=serving_config_service.CreateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['create_serving_config'] + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete serving config method over gRPC. + + Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.DeleteServingConfigRequest], + 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_serving_config' not in self._stubs: + self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/DeleteServingConfig', + request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_serving_config'] + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the update serving config method over gRPC. + + Updates a ServingConfig. + + Returns: + Callable[[~.UpdateServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/UpdateServingConfig', + request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['update_serving_config'] + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + Awaitable[serving_config.ServingConfig]]: + r"""Return a callable for the get serving config method over gRPC. + + Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.GetServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/GetServingConfig', + request_serializer=serving_config_service.GetServingConfigRequest.serialize, + response_deserializer=serving_config.ServingConfig.deserialize, + ) + return self._stubs['get_serving_config'] + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + Awaitable[serving_config_service.ListServingConfigsResponse]]: + r"""Return a callable for the list serving configs method over gRPC. + + Lists all ServingConfigs linked to this catalog. + + Returns: + Callable[[~.ListServingConfigsRequest], + Awaitable[~.ListServingConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: + self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/ListServingConfigs', + request_serializer=serving_config_service.ListServingConfigsRequest.serialize, + response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, + ) + return self._stubs['list_serving_configs'] + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the add control method over gRPC. + + Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + Returns: + Callable[[~.AddControlRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_control' not in self._stubs: + self._stubs['add_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/AddControl', + request_serializer=serving_config_service.AddControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['add_control'] + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the remove control method over gRPC. + + Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + Returns: + Callable[[~.RemoveControlRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_control' not in self._stubs: + self._stubs['remove_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/RemoveControl', + request_serializer=serving_config_service.RemoveControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['remove_control'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ServingConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py new file mode 100644 index 00000000..5f5171c1 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py new file mode 100644 index 00000000..1f08ee18 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py @@ -0,0 +1,730 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on the customer + website. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(UserEventServiceClient.catalog_path) + parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) + product_path = staticmethod(UserEventServiceClient.product_path) + parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_write_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_collect_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_purge_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_import_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2alpha.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_rejoin_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py new file mode 100644 index 00000000..98d272ff --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py @@ -0,0 +1,930 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[UserEventServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on the customer + website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_write_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_collect_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_purge_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeUserEventsRequest): + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_import_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2alpha.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_rejoin_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.RejoinUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.RejoinUserEventsRequest): + request = user_event_service.RejoinUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py new file mode 100644 index 00000000..f53ee5d7 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py new file mode 100644 index 00000000..efd2f034 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py @@ -0,0 +1,235 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.rejoin_user_events: gapic_v1.method.wrap_method( + self.rejoin_user_events, + 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 write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + user_event.UserEvent, + Awaitable[user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py new file mode 100644 index 00000000..3ca23eca --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..72c6083a --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + 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 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py new file mode 100644 index 00000000..aa87618d --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py @@ -0,0 +1,284 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .catalog import ( + AttributesConfig, + Catalog, + CatalogAttribute, + CompletionConfig, + MerchantCenterLink, + MerchantCenterLinkingConfig, + ProductLevelConfig, +) +from .catalog_service import ( + AddCatalogAttributeRequest, + GetAttributesConfigRequest, + GetCompletionConfigRequest, + GetDefaultBranchRequest, + GetDefaultBranchResponse, + ListCatalogsRequest, + ListCatalogsResponse, + RemoveCatalogAttributeRequest, + ReplaceCatalogAttributeRequest, + SetDefaultBranchRequest, + UpdateAttributesConfigRequest, + UpdateCatalogRequest, + UpdateCompletionConfigRequest, +) +from .common import ( + Audience, + ColorInfo, + Condition, + CustomAttribute, + FulfillmentInfo, + Image, + Interval, + LocalInventory, + PriceInfo, + Rating, + Rule, + UserInfo, + AttributeConfigLevel, + SearchSolutionUseCase, + SolutionType, +) +from .completion_service import ( + CompleteQueryRequest, + CompleteQueryResponse, +) +from .control import ( + Control, +) +from .control_service import ( + CreateControlRequest, + DeleteControlRequest, + GetControlRequest, + ListControlsRequest, + ListControlsResponse, + UpdateControlRequest, +) +from .export_config import ( + ExportErrorsConfig, + ExportMetadata, + ExportProductsResponse, + ExportUserEventsResponse, +) +from .import_config import ( + BigQuerySource, + CompletionDataInputConfig, + GcsSource, + ImportCompletionDataRequest, + ImportCompletionDataResponse, + ImportErrorsConfig, + ImportMetadata, + ImportProductsRequest, + ImportProductsResponse, + ImportUserEventsRequest, + ImportUserEventsResponse, + ProductInlineSource, + ProductInputConfig, + UserEventImportSummary, + UserEventInlineSource, + UserEventInputConfig, +) +from .prediction_service import ( + PredictRequest, + PredictResponse, +) +from .product import ( + Product, +) +from .product_service import ( + AddFulfillmentPlacesMetadata, + AddFulfillmentPlacesRequest, + AddFulfillmentPlacesResponse, + AddLocalInventoriesMetadata, + AddLocalInventoriesRequest, + AddLocalInventoriesResponse, + CreateProductRequest, + DeleteProductRequest, + GetProductRequest, + ListProductsRequest, + ListProductsResponse, + RemoveFulfillmentPlacesMetadata, + RemoveFulfillmentPlacesRequest, + RemoveFulfillmentPlacesResponse, + RemoveLocalInventoriesMetadata, + RemoveLocalInventoriesRequest, + RemoveLocalInventoriesResponse, + SetInventoryMetadata, + SetInventoryRequest, + SetInventoryResponse, + UpdateProductRequest, +) +from .promotion import ( + Promotion, +) +from .purge_config import ( + PurgeMetadata, + PurgeProductsMetadata, + PurgeProductsRequest, + PurgeProductsResponse, + PurgeUserEventsRequest, + PurgeUserEventsResponse, +) +from .search_service import ( + SearchRequest, + SearchResponse, +) +from .serving_config import ( + ServingConfig, +) +from .serving_config_service import ( + AddControlRequest, + CreateServingConfigRequest, + DeleteServingConfigRequest, + GetServingConfigRequest, + ListServingConfigsRequest, + ListServingConfigsResponse, + RemoveControlRequest, + UpdateServingConfigRequest, +) +from .user_event import ( + CompletionDetail, + ProductDetail, + PurchaseTransaction, + UserEvent, +) +from .user_event_service import ( + CollectUserEventRequest, + RejoinUserEventsMetadata, + RejoinUserEventsRequest, + RejoinUserEventsResponse, + WriteUserEventRequest, +) + +__all__ = ( + 'AttributesConfig', + 'Catalog', + 'CatalogAttribute', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'ProductLevelConfig', + 'AddCatalogAttributeRequest', + 'GetAttributesConfigRequest', + 'GetCompletionConfigRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + 'SetDefaultBranchRequest', + 'UpdateAttributesConfigRequest', + 'UpdateCatalogRequest', + 'UpdateCompletionConfigRequest', + 'Audience', + 'ColorInfo', + 'Condition', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'Rule', + 'UserInfo', + 'AttributeConfigLevel', + 'SearchSolutionUseCase', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Control', + 'CreateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + 'UpdateControlRequest', + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeProductsMetadata', + 'PurgeProductsRequest', + 'PurgeProductsResponse', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'ServingConfig', + 'AddControlRequest', + 'CreateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'RemoveControlRequest', + 'UpdateServingConfigRequest', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py new file mode 100644 index 00000000..1e4a7ab5 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py @@ -0,0 +1,528 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'ProductLevelConfig', + 'CatalogAttribute', + 'AttributesConfig', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'Catalog', + }, +) + + +class ProductLevelConfig(proto.Message): + r"""Configures what level the product should be uploaded with + regards to how users will be send events and how predictions + will be made. + + Attributes: + ingestion_product_type (str): + The type of [Product][google.cloud.retail.v2alpha.Product]s + allowed to be ingested into the catalog. Acceptable values + are: + + - ``primary`` (default): You can ingest + [Product][google.cloud.retail.v2alpha.Product]s of all + types. When ingesting a + [Product][google.cloud.retail.v2alpha.Product], its type + will default to + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + if unset. + - ``variant``: You can only ingest + [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s. This + means + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] + cannot be empty. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``variant`` and + [merchant_center_product_id_field][google.cloud.retail.v2alpha.ProductLevelConfig.merchant_center_product_id_field] + is ``itemGroupId``, an INVALID_ARGUMENT error is returned. + + See `Using product + levels `__ + for more details. + merchant_center_product_id_field (str): + Which field of `Merchant Center + Product `__ + should be imported as + [Product.id][google.cloud.retail.v2alpha.Product.id]. + Acceptable values are: + + - ``offerId`` (default): Import ``offerId`` as the product + ID. + - ``itemGroupId``: Import ``itemGroupId`` as the product + ID. Notice that Retail API will choose one item from the + ones with the same ``itemGroupId``, and use it to + represent the item group. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``itemGroupId`` and + [ingestion_product_type][google.cloud.retail.v2alpha.ProductLevelConfig.ingestion_product_type] + is ``variant``, an INVALID_ARGUMENT error is returned. + + See `Using product + levels `__ + for more details. + """ + + ingestion_product_type = proto.Field( + proto.STRING, + number=1, + ) + merchant_center_product_id_field = proto.Field( + proto.STRING, + number=2, + ) + + +class CatalogAttribute(proto.Message): + r"""Catalog level attribute config for an attribute. For example, + if customers want to enable/disable facet for a specific + attribute. + + Attributes: + key (str): + Required. Attribute name. For example: ``color``, + ``brands``, ``attributes.custom_attribute``, such as + ``attributes.xyz``. + in_use (bool): + Output only. Indicates whether this attribute has been used + by any products. ``True`` if at least one + [Product][google.cloud.retail.v2alpha.Product] is using this + attribute in + [Product.attributes][google.cloud.retail.v2alpha.Product.attributes]. + Otherwise, this field is ``False``. + + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + can be pre-loaded by using [AddCatalogAttribute][], + [ImportCatalogAttributes][], or [UpdateAttributesConfig][] + APIs. This field is ``False`` for pre-loaded + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s. + + Only + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s + that are not in use by products can be deleted. + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s + that are in use by products cannot be deleted; however, + their configuration properties will reset to default values + upon removal request. + + After catalog changes, it takes about 10 minutes for this + field to update. + type_ (google.cloud.retail_v2alpha.types.CatalogAttribute.AttributeType): + Output only. The type of this attribute. This is derived + from the attribute in + [Product.attributes][google.cloud.retail.v2alpha.Product.attributes]. + indexable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.IndexableOption): + When + [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] + is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if INDEXABLE_ENABLED + attribute values are indexed so that it can be filtered, + faceted, or boosted in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + dynamic_facetable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.DynamicFacetableOption): + If DYNAMIC_FACETABLE_ENABLED, attribute values are available + for dynamic facet. Could only be DYNAMIC_FACETABLE_DISABLED + if + [CatalogAttribute.indexable_option][google.cloud.retail.v2alpha.CatalogAttribute.indexable_option] + is INDEXABLE_DISABLED. Otherwise, an INVALID_ARGUMENT error + is returned. + searchable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.SearchableOption): + When + [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] + is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if SEARCHABLE_ENABLED, + attribute values are searchable by text queries in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + If SEARCHABLE_ENABLED but attribute type is numerical, + attribute values will not be searchable by text queries in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + as there are no text values associated to numerical + attributes. + """ + class AttributeType(proto.Enum): + r"""The type of an attribute.""" + UNKNOWN = 0 + TEXTUAL = 1 + NUMERICAL = 2 + + class IndexableOption(proto.Enum): + r"""The status of the indexable option of a catalog attribute.""" + INDEXABLE_OPTION_UNSPECIFIED = 0 + INDEXABLE_ENABLED = 1 + INDEXABLE_DISABLED = 2 + + class DynamicFacetableOption(proto.Enum): + r"""The status of the dynamic facetable option of a catalog + attribute. + """ + DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 + DYNAMIC_FACETABLE_ENABLED = 1 + DYNAMIC_FACETABLE_DISABLED = 2 + + class SearchableOption(proto.Enum): + r"""The status of the searchable option of a catalog attribute.""" + SEARCHABLE_OPTION_UNSPECIFIED = 0 + SEARCHABLE_ENABLED = 1 + SEARCHABLE_DISABLED = 2 + + key = proto.Field( + proto.STRING, + number=1, + ) + in_use = proto.Field( + proto.BOOL, + number=9, + ) + type_ = proto.Field( + proto.ENUM, + number=10, + enum=AttributeType, + ) + indexable_option = proto.Field( + proto.ENUM, + number=5, + enum=IndexableOption, + ) + dynamic_facetable_option = proto.Field( + proto.ENUM, + number=6, + enum=DynamicFacetableOption, + ) + searchable_option = proto.Field( + proto.ENUM, + number=7, + enum=SearchableOption, + ) + + +class AttributesConfig(proto.Message): + r"""Catalog level attribute config. + + Attributes: + name (str): + Required. Immutable. The fully qualified resource name of + the attribute config. Format: + ``projects/*/locations/*/catalogs/*/attributesConfig`` + catalog_attributes (Mapping[str, google.cloud.retail_v2alpha.types.CatalogAttribute]): + Enable attribute(s) config at catalog level. For example, + indexable, dynamic_facetable, or searchable for each + attribute. + + The key is catalog attribute's name. For example: ``color``, + ``brands``, ``attributes.custom_attribute``, such as + ``attributes.xyz``. + + The maximum number of catalog attributes allowed in a + request is 1000. + attribute_config_level (google.cloud.retail_v2alpha.types.AttributeConfigLevel): + Output only. The + [AttributeConfigLevel][google.cloud.retail.v2alpha.AttributeConfigLevel] + used for this catalog. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + catalog_attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='CatalogAttribute', + ) + attribute_config_level = proto.Field( + proto.ENUM, + number=3, + enum=common.AttributeConfigLevel, + ) + + +class CompletionConfig(proto.Message): + r"""Catalog level autocomplete config for customers to customize + autocomplete feature's settings. + + Attributes: + name (str): + Required. Immutable. Fully qualified name + ``projects/*/locations/*/catalogs/*/completionConfig`` + matching_order (str): + Specifies the matching order for autocomplete suggestions, + e.g., a query consisting of 'sh' with 'out-of-order' + specified would suggest "women's shoes", whereas a query of + 'red s' with 'exact-prefix' specified would suggest "red + shoes". Currently supported values: + + - 'out-of-order' + - 'exact-prefix' + + Default value: 'exact-prefix'. + max_suggestions (int): + The maximum number of autocomplete + suggestions returned per term. The maximum + allowed max suggestions is 20. Default value is + 20. If left unset or set to 0, then will + fallback to default value. + min_prefix_length (int): + The minimum number of characters needed to be + typed in order to get suggestions. Default value + is 2. If left unset or set to 0, then will + fallback to default value. + auto_learning (bool): + If set to true, the auto learning function is enabled. Auto + learning uses user data to generate suggestions using ML + techniques. Default value is false. Only after enabling auto + learning can users use ``cloud-retail`` data in + [CompleteQueryRequest][google.cloud.retail.v2alpha.CompleteQueryRequest]. + suggestions_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the + autocomplete phrases uploaded by the customer. + last_suggestions_import_operation (str): + Output only. Name of the LRO corresponding to the latest + suggestion terms list import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + denylist_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the / + autocomplete denylist phrases uploaded by the + customer. + last_denylist_import_operation (str): + Output only. LRO corresponding to the latest denylist + import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + allowlist_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the + autocomplete allowlist phrases uploaded by the + customer. + last_allowlist_import_operation (str): + Output only. LRO corresponding to the latest allowlist + import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + matching_order = proto.Field( + proto.STRING, + number=2, + ) + max_suggestions = proto.Field( + proto.INT32, + number=3, + ) + min_prefix_length = proto.Field( + proto.INT32, + number=4, + ) + auto_learning = proto.Field( + proto.BOOL, + number=11, + ) + suggestions_input_config = proto.Field( + proto.MESSAGE, + number=5, + message=import_config.CompletionDataInputConfig, + ) + last_suggestions_import_operation = proto.Field( + proto.STRING, + number=6, + ) + denylist_input_config = proto.Field( + proto.MESSAGE, + number=7, + message=import_config.CompletionDataInputConfig, + ) + last_denylist_import_operation = proto.Field( + proto.STRING, + number=8, + ) + allowlist_input_config = proto.Field( + proto.MESSAGE, + number=9, + message=import_config.CompletionDataInputConfig, + ) + last_allowlist_import_operation = proto.Field( + proto.STRING, + number=10, + ) + + +class MerchantCenterLink(proto.Message): + r"""Represents a link between a Merchant Center account and a + branch. Once a link is established, products from the linked + merchant center account will be streamed to the linked branch. + + Attributes: + merchant_center_account_id (int): + Required. The linked `Merchant center account + id `__. + The account must be a standalone account or a sub-account of + a MCA. + branch_id (str): + The branch id (e.g. 0/1/2) within this catalog that products + from merchant_center_account_id are streamed to. When + updating this field, an empty value will use the currently + configured default branch. However, changing the default + branch later on won't change the linked branch here. + + A single branch id can only have one linked merchant center + account id. + destinations (Sequence[str]): + String representing the destination to import for, all if + left empty. List of possible values can be found here. + [https://support.google.com/merchants/answer/7501026] List + of allowed string values: "Shopping_ads", + "Buy_on_google_listings", "Display_ads", "Local_inventory + \_ads", "Free_listings", "Free_local_listings" NOTE: The + string values are case sensitive. + region_code (str): + Region code of offers to accept. 2-letter Uppercase ISO + 3166-1 alpha-2 code. List of values can be found + `here `__ + under the ``region`` tag. If left blank no region filtering + will be performed. + + Example value: ``US``. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. ISO + 639-1. + + This specifies the language of offers in Merchant Center + that will be accepted. If empty no language filtering will + be performed. + + Example value: ``en``. + """ + + merchant_center_account_id = proto.Field( + proto.INT64, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + destinations = proto.RepeatedField( + proto.STRING, + number=3, + ) + region_code = proto.Field( + proto.STRING, + number=4, + ) + language_code = proto.Field( + proto.STRING, + number=5, + ) + + +class MerchantCenterLinkingConfig(proto.Message): + r"""Configures Merchant Center linking. + Links contained in the config will be used to sync data from a + Merchant Center account to a Cloud Retail branch. + + Attributes: + links (Sequence[google.cloud.retail_v2alpha.types.MerchantCenterLink]): + Links between Merchant Center accounts and + branches. + """ + + links = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MerchantCenterLink', + ) + + +class Catalog(proto.Message): + r"""The catalog configuration. + + Attributes: + name (str): + Required. Immutable. The fully qualified + resource name of the catalog. + display_name (str): + Required. Immutable. The catalog display name. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + product_level_config (google.cloud.retail_v2alpha.types.ProductLevelConfig): + Required. The product level configuration. + merchant_center_linking_config (google.cloud.retail_v2alpha.types.MerchantCenterLinkingConfig): + The Merchant Center linking configuration. + Once a link is added, the data stream from + Merchant Center to Cloud Retail will be enabled + automatically. The requester must have access to + the merchant center account in order to make + changes to this field. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + product_level_config = proto.Field( + proto.MESSAGE, + number=4, + message='ProductLevelConfig', + ) + merchant_center_linking_config = proto.Field( + proto.MESSAGE, + number=6, + message='MerchantCenterLinkingConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py new file mode 100644 index 00000000..21d9b1c2 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py @@ -0,0 +1,453 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'UpdateCatalogRequest', + 'SetDefaultBranchRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'GetCompletionConfigRequest', + 'UpdateCompletionConfigRequest', + 'GetAttributesConfigRequest', + 'UpdateAttributesConfigRequest', + 'AddCatalogAttributeRequest', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + }, +) + + +class ListCatalogsRequest(proto.Message): + r"""Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + + Attributes: + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2alpha.Catalog]s under this + location, regardless of whether or not this location exists, + a PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [Catalog][google.cloud.retail.v2alpha.Catalog]s to return. + If unspecified, defaults to 50. The maximum allowed value is + 1000. Values above 1000 will be coerced to 1000. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [ListCatalogsResponse.next_page_token][google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token], + received from a previous + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCatalogsResponse(proto.Message): + r"""Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + + Attributes: + catalogs (Sequence[google.cloud.retail_v2alpha.types.Catalog]): + All the customer's + [Catalog][google.cloud.retail.v2alpha.Catalog]s. + next_page_token (str): + A token that can be sent as + [ListCatalogsRequest.page_token][google.cloud.retail.v2alpha.ListCatalogsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + catalogs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateCatalogRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] + method. + + Attributes: + catalog (google.cloud.retail_v2alpha.types.Catalog): + Required. The [Catalog][google.cloud.retail.v2alpha.Catalog] + to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2alpha.Catalog], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2alpha.Catalog] 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 + [Catalog][google.cloud.retail.v2alpha.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + catalog = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class SetDefaultBranchRequest(proto.Message): + r"""Request message to set a specified branch as new default_branch. + + Attributes: + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + branch_id (str): + The final component of the resource name of a branch. + + This field must be one of "0", "1" or "2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If there are no sufficient active products in the targeted + branch and + [force][google.cloud.retail.v2alpha.SetDefaultBranchRequest.force] + is not set, a FAILED_PRECONDITION error is returned. + note (str): + Some note on this request, this can be retrieved by + [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch] + before next valid default branch set occurs. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + force (bool): + If set to true, it permits switching to a branch with + [branch_id][google.cloud.retail.v2alpha.SetDefaultBranchRequest.branch_id] + even if it has no sufficient active products. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + force = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetDefaultBranchRequest(proto.Message): + r"""Request message to show which branch is currently the default + branch. + + Attributes: + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDefaultBranchResponse(proto.Message): + r"""Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. + + Attributes: + branch (str): + Full resource name of the branch id currently + set as default branch. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when this branch is set to default. + note (str): + This corresponds to + [SetDefaultBranchRequest.note][google.cloud.retail.v2alpha.SetDefaultBranchRequest.note] + field, when this branch was set as default. + """ + + branch = proto.Field( + proto.STRING, + number=1, + ) + set_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + + +class GetCompletionConfigRequest(proto.Message): + r"""Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] + method. + + Attributes: + name (str): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateCompletionConfigRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] + method. + + Attributes: + completion_config (google.cloud.retail_v2alpha.types.CompletionConfig): + Required. The + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + 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 + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + """ + + completion_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.CompletionConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetAttributesConfigRequest(proto.Message): + r"""Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] + method. + + Attributes: + name (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAttributesConfigRequest(proto.Message): + r"""Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] + method. + + Attributes: + attributes_config (google.cloud.retail_v2alpha.types.AttributesConfig): + Required. The + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + """ + + attributes_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.AttributesConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class AddCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + catalog_attribute (google.cloud.retail_v2alpha.types.CatalogAttribute): + Required. The + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + catalog_attribute = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_catalog.CatalogAttribute, + ) + + +class RemoveCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + key (str): + Required. The attribute name key of the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + key = proto.Field( + proto.STRING, + number=2, + ) + + +class ReplaceCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + catalog_attribute (google.cloud.retail_v2alpha.types.CatalogAttribute): + Required. The updated + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to update. The following are NOT supported: + + - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key] + + If not set, all supported fields are updated. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + catalog_attribute = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_catalog.CatalogAttribute, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py new file mode 100644 index 00000000..25fa2861 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py @@ -0,0 +1,1179 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'AttributeConfigLevel', + 'SolutionType', + 'SearchSolutionUseCase', + 'Condition', + 'Rule', + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'LocalInventory', + }, +) + + +class AttributeConfigLevel(proto.Enum): + r"""At which level we offer configuration for attributes.""" + ATTRIBUTE_CONFIG_LEVEL_UNSPECIFIED = 0 + PRODUCT_LEVEL_ATTRIBUTE_CONFIG = 1 + CATALOG_LEVEL_ATTRIBUTE_CONFIG = 2 + + +class SolutionType(proto.Enum): + r"""The type of solution.""" + SOLUTION_TYPE_UNSPECIFIED = 0 + SOLUTION_TYPE_RECOMMENDATION = 1 + SOLUTION_TYPE_SEARCH = 2 + + +class SearchSolutionUseCase(proto.Enum): + r"""The use case of Cloud Retail Search.""" + SEARCH_SOLUTION_USE_CASE_UNSPECIFIED = 0 + SEARCH_SOLUTION_USE_CASE_SEARCH = 1 + SEARCH_SOLUTION_USE_CASE_BROWSE = 2 + + +class Condition(proto.Message): + r"""Metadata that is used to define a condition that triggers an action. + A valid condition must specify at least one of 'query_terms' or + 'products_filter'. If multiple fields are specified, the condition + is met if all the fields are satisfied e.g. if a set of query terms + and product_filter are set, then only items matching the + product_filter for requests with a query matching the query terms + wil get boosted. + + Attributes: + query_terms (Sequence[google.cloud.retail_v2alpha.types.Condition.QueryTerm]): + A list (up to 10 entries) of terms to match + the query on. If not specified, match all + queries. If many query terms are specified, the + condition is matched if any of the terms is a + match (i.e. using the OR operator). + active_time_range (Sequence[google.cloud.retail_v2alpha.types.Condition.TimeRange]): + Range of time(s) specifying when Condition is + active. Condition true if any time range + matches. + """ + + class QueryTerm(proto.Message): + r"""Query terms that we want to match on. + + Attributes: + value (str): + The value of the term to match on. + Value cannot be empty. + Value can have at most 3 terms if specified as a + partial match. Each space separated string is + considered as one term. Example) "a b c" is 3 + terms and allowed, " a b c d" is 4 terms and not + allowed for partial match. + full_match (bool): + Whether this is supposed to be a full or + partial match. + """ + + value = proto.Field( + proto.STRING, + number=1, + ) + full_match = proto.Field( + proto.BOOL, + number=2, + ) + + class TimeRange(proto.Message): + r"""Used for time-dependent conditions. + Example: Want to have rule applied for week long sale. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start of time range. Range is inclusive. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End of time range. Range is inclusive. + """ + + start_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + query_terms = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=QueryTerm, + ) + active_time_range = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TimeRange, + ) + + +class Rule(proto.Message): + r"""A rule is a condition-action pair + + - A condition defines when a rule is to be triggered. + - An action specifies what occurs on that trigger. Currently only + boost rules are supported. Currently only supported by the search + endpoint. + + 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: + boost_action (google.cloud.retail_v2alpha.types.Rule.BoostAction): + A boost action. + + This field is a member of `oneof`_ ``action``. + redirect_action (google.cloud.retail_v2alpha.types.Rule.RedirectAction): + Redirects a shopper to a specific page. + + This field is a member of `oneof`_ ``action``. + oneway_synonyms_action (google.cloud.retail_v2alpha.types.Rule.OnewaySynonymsAction): + Treats specific term as a synonym with a + group of terms. Group of terms will not be + treated as synonyms with the specific term. + + This field is a member of `oneof`_ ``action``. + do_not_associate_action (google.cloud.retail_v2alpha.types.Rule.DoNotAssociateAction): + Prevents term from being associated with + other terms. + + This field is a member of `oneof`_ ``action``. + replacement_action (google.cloud.retail_v2alpha.types.Rule.ReplacementAction): + Replaces specific terms in the query. + + This field is a member of `oneof`_ ``action``. + ignore_action (google.cloud.retail_v2alpha.types.Rule.IgnoreAction): + Ignores specific terms from query during + search. + + This field is a member of `oneof`_ ``action``. + filter_action (google.cloud.retail_v2alpha.types.Rule.FilterAction): + Filters results. + + This field is a member of `oneof`_ ``action``. + twoway_synonyms_action (google.cloud.retail_v2alpha.types.Rule.TwowaySynonymsAction): + Treats a set of terms as synonyms of one + another. + + This field is a member of `oneof`_ ``action``. + condition (google.cloud.retail_v2alpha.types.Condition): + Required. The condition that triggers the + rule. If the condition is empty, the rule will + always apply. + """ + + class BoostAction(proto.Message): + r"""A boost action to apply to results matching condition + specified above. + + Attributes: + boost (float): + Strength of the condition boost, which must be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + products_filter (str): + The filter can have a max size of 5000 characters. An + expression which specifies which products to apply an action + to. The syntax and supported fields are the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": *(id: + ANY("product_1", "product_2"))* *AND* *(colorFamilies: + ANY("Red", "Blue"))* + """ + + boost = proto.Field( + proto.FLOAT, + number=1, + ) + products_filter = proto.Field( + proto.STRING, + number=2, + ) + + class FilterAction(proto.Message): + r"""- Rule Condition: + + - No [Condition][query_terms] provided is a global match. + - 1 or more [Condition][query_terms] provided is combined with + OR operator. + + - Action Input: The request query and filter that will be applied + to the retrieved products, in addition to any filters already + provided with the SearchRequest. The AND operator is used to + combine the query's existing filters with the filter rule(s). + NOTE: May result in 0 results when filters conflict. + - Action Result: Filters the returned objects to be ONLY those that + passed the filter. + + Attributes: + filter (str): + A filter to apply on the matching condition results. + Supported features: + + - [filter][google.cloud.retail.v2alpha.Rule.FilterAction.filter] + must be set. + - Filter syntax is identical to + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter]. + See more details at the Retail Search `user + guide `__. + - To filter products with product ID "product_1" or + "product_2", and color "Red" or "Blue": *(id: + ANY("product_1", "product_2"))* *AND* *(colorFamilies: + ANY("Red", "Blue"))* + """ + + filter = proto.Field( + proto.STRING, + number=1, + ) + + class RedirectAction(proto.Message): + r"""Redirects a shopper to a specific page. + + - Rule Condition: + + - Must specify [Condition][query_terms]. + + - Action Input: Request Query + - Action Result: Redirects shopper to provided uri. + + Attributes: + redirect_uri (str): + URL must have length equal or less than 2000 + characters. + """ + + redirect_uri = proto.Field( + proto.STRING, + number=1, + ) + + class TwowaySynonymsAction(proto.Message): + r"""Creates a set of terms that will be treated as synonyms of each + other. Example: synonyms of "sneakers" and "shoes". + + - "sneakers" will use a synonym of "shoes". + - "shoes" will use a synonym of "sneakers". + + Attributes: + synonyms (Sequence[str]): + Defines a set of synonyms. + Can specify up to 100 synonyms. + Must specify at least 2 synonyms. + """ + + synonyms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class OnewaySynonymsAction(proto.Message): + r"""Maps a set of terms to a set of synonyms. Set of synonyms will be + treated as synonyms of each query term only. ``query_terms`` will + not be treated as synonyms of each other. Example: "sneakers" will + use a synonym of "shoes". "shoes" will not use a synonym of + "sneakers". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. + Will treat synonyms as their synonyms. + Not themselves synonyms of the synonyms. + Can specify up to 100 terms. + synonyms (Sequence[str]): + Defines a set of synonyms. + Cannot contain duplicates. + Can specify up to 100 synonyms. + oneway_terms (Sequence[str]): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=3, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=4, + ) + oneway_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class DoNotAssociateAction(proto.Message): + r"""Prevents ``query_term`` from being associated with specified terms + during search. Example: Don't associate "gShoe" and "cheap". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. Will not consider + do_not_associate_terms for search if in search query. Can + specify up to 100 terms. + do_not_associate_terms (Sequence[str]): + Cannot contain duplicates or the query term. + Can specify up to 100 terms. + terms (Sequence[str]): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + do_not_associate_terms = proto.RepeatedField( + proto.STRING, + number=3, + ) + terms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class ReplacementAction(proto.Message): + r"""Replaces a term in the query. Multiple replacement candidates can be + specified. All ``query_terms`` will be replaced with the replacement + term. Example: Replace "gShoe" with "google shoe". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. + Will be replaced by replacement term. + Can specify up to 100 terms. + replacement_term (str): + Term that will be used for replacement. + term (str): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + replacement_term = proto.Field( + proto.STRING, + number=3, + ) + term = proto.Field( + proto.STRING, + number=1, + ) + + class IgnoreAction(proto.Message): + r"""Prevents a term in the query from being used in search. + Example: Don't search for "shoddy". + + Attributes: + ignore_terms (Sequence[str]): + Terms to ignore in the search query. + """ + + ignore_terms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + boost_action = proto.Field( + proto.MESSAGE, + number=2, + oneof='action', + message=BoostAction, + ) + redirect_action = proto.Field( + proto.MESSAGE, + number=3, + oneof='action', + message=RedirectAction, + ) + oneway_synonyms_action = proto.Field( + proto.MESSAGE, + number=6, + oneof='action', + message=OnewaySynonymsAction, + ) + do_not_associate_action = proto.Field( + proto.MESSAGE, + number=7, + oneof='action', + message=DoNotAssociateAction, + ) + replacement_action = proto.Field( + proto.MESSAGE, + number=8, + oneof='action', + message=ReplacementAction, + ) + ignore_action = proto.Field( + proto.MESSAGE, + number=9, + oneof='action', + message=IgnoreAction, + ) + filter_action = proto.Field( + proto.MESSAGE, + number=10, + oneof='action', + message=FilterAction, + ) + twoway_synonyms_action = proto.Field( + proto.MESSAGE, + number=11, + oneof='action', + message=TwowaySynonymsAction, + ) + condition = proto.Field( + proto.MESSAGE, + number=1, + message='Condition', + ) + + +class Audience(proto.Message): + r"""An intended audience of the + [Product][google.cloud.retail.v2alpha.Product] for whom it's sold. + + Attributes: + genders (Sequence[str]): + The genders of the audience. Strongly encouraged to use the + standard values: "male", "female", "unisex". + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `gender `__. + Schema.org property + `Product.audience.suggestedGender `__. + age_groups (Sequence[str]): + The age groups of the audience. Strongly encouraged to use + the standard values: "newborn" (up to 3 months old), + "infant" (3–12 months old), "toddler" (1–5 years old), + "kids" (5–13 years old), "adult" (typically teens or older). + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `age_group `__. + Schema.org property + `Product.audience.suggestedMinAge `__ + and + `Product.audience.suggestedMaxAge `__. + """ + + genders = proto.RepeatedField( + proto.STRING, + number=1, + ) + age_groups = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class ColorInfo(proto.Message): + r"""The color information of a + [Product][google.cloud.retail.v2alpha.Product]. + + Attributes: + color_families (Sequence[str]): + The standard color families. Strongly recommended to use the + following standard color groups: "Red", "Pink", "Orange", + "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", + "White", "Gray", "Black" and "Mixed". Normally it is + expected to have only 1 color family. May consider using + single "Mixed" instead of multiple values. + + A maximum of 5 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + colors (Sequence[str]): + The color display names, which may be different from + standard color family names, such as the color aliases used + in the website frontend. Normally it is expected to have + only 1 color. May consider using single "Mixed" instead of + multiple values. + + A maximum of 25 colors are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + """ + + color_families = proto.RepeatedField( + proto.STRING, + number=1, + ) + colors = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in + [Product][google.cloud.retail.v2alpha.Product]. + + Attributes: + text (Sequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an INVALID_ARGUMENT + error is returned. + + Exactly one of + [text][google.cloud.retail.v2alpha.CustomAttribute.text] or + [numbers][google.cloud.retail.v2alpha.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + numbers (Sequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [text][google.cloud.retail.v2alpha.CustomAttribute.text] or + [numbers][google.cloud.retail.v2alpha.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + searchable (bool): + This field will only be used when + [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] + of the [Catalog][google.cloud.retail.v2alpha.Catalog] is + 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute + values are searchable by text queries in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2alpha.UserEvent]. + + Only set if type + [text][google.cloud.retail.v2alpha.CustomAttribute.text] is + set. Otherwise, a INVALID_ARGUMENT error is returned. + + This field is a member of `oneof`_ ``_searchable``. + indexable (bool): + This field will only be used when + [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] + of the [Catalog][google.cloud.retail.v2alpha.Catalog] is + 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute + values are indexed, so that it can be filtered, faceted or + boosted in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2alpha.UserEvent]. + + See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter], + [SearchRequest.facet_specs][google.cloud.retail.v2alpha.SearchRequest.facet_specs] + and + [SearchRequest.boost_spec][google.cloud.retail.v2alpha.SearchRequest.boost_spec] + for more details. + + This field is a member of `oneof`_ ``_indexable``. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + searchable = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + indexable = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + +class FulfillmentInfo(proto.Message): + r"""Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + Attributes: + type_ (str): + The fulfillment type, including commonly used types (such as + pickup in store and same day delivery), and custom types. + Customers have to map custom types to their display names + before rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + place_ids (Sequence[str]): + The IDs for this + [type][google.cloud.retail.v2alpha.FulfillmentInfo.type], + such as the store IDs for + [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2alpha.FulfillmentInfo.type] + or the region IDs for + [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2alpha.FulfillmentInfo.type]. + + A maximum of 3000 values are allowed. Each value must be a + string with a length limit of 30 characters, matching the + pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". + Otherwise, an INVALID_ARGUMENT error is returned. + """ + + type_ = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class Image(proto.Message): + r"""[Product][google.cloud.retail.v2alpha.Product] image. + Recommendations AI and Retail Search do not use product images to + improve prediction and search results. However, product images can + be returned in results, and are shown in prediction or search + previews in the console. + + Attributes: + uri (str): + Required. URI of the image. + + This field must be a valid UTF-8 encoded URI with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + height (int): + Height of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + width (int): + Width of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + height = proto.Field( + proto.INT32, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + + +class Interval(proto.Message): + r"""A floating point interval. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum = proto.Field( + proto.DOUBLE, + number=1, + oneof='min', + ) + exclusive_minimum = proto.Field( + proto.DOUBLE, + number=2, + oneof='min', + ) + maximum = proto.Field( + proto.DOUBLE, + number=3, + oneof='max', + ) + exclusive_maximum = proto.Field( + proto.DOUBLE, + number=4, + oneof='max', + ) + + +class PriceInfo(proto.Message): + r"""The price information of a + [Product][google.cloud.retail.v2alpha.Product]. + + Attributes: + currency_code (str): + The 3-letter currency code defined in `ISO + 4217 `__. + + If this field is an unrecognizable currency code, an + INVALID_ARGUMENT error is returned. + + The + [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s with the + same + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] + must share the same + [currency_code][google.cloud.retail.v2alpha.PriceInfo.currency_code]. + Otherwise, a FAILED_PRECONDITION error is returned. + price (float): + Price of the product. + + Google Merchant Center property + `price `__. + Schema.org property + `Offer.price `__. + original_price (float): + Price of the product without any discount. If zero, by + default set to be the + [price][google.cloud.retail.v2alpha.PriceInfo.price]. + cost (float): + The costs associated with the sale of a particular product. + Used for gross profit reporting. + + - Profit = + [price][google.cloud.retail.v2alpha.PriceInfo.price] - + [cost][google.cloud.retail.v2alpha.PriceInfo.cost] + + Google Merchant Center property + `cost_of_goods_sold `__. + price_effective_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2alpha.PriceInfo.price] starts + to be effective. This can be set as a future timestamp, and + the [price][google.cloud.retail.v2alpha.PriceInfo.price] is + only used for search after + [price_effective_time][google.cloud.retail.v2alpha.PriceInfo.price_effective_time]. + If so, the + [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + is used before + [price_effective_time][google.cloud.retail.v2alpha.PriceInfo.price_effective_time]. + + Do not set if + [price][google.cloud.retail.v2alpha.PriceInfo.price] is + always effective because it will cause additional latency + during search. + price_expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2alpha.PriceInfo.price] stops + to be effective. The + [price][google.cloud.retail.v2alpha.PriceInfo.price] is used + for search before + [price_expire_time][google.cloud.retail.v2alpha.PriceInfo.price_expire_time]. + If this field is set, the + [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + is used after + [price_expire_time][google.cloud.retail.v2alpha.PriceInfo.price_expire_time]. + + Do not set if + [price][google.cloud.retail.v2alpha.PriceInfo.price] is + always effective because it will cause additional latency + during search. + price_range (google.cloud.retail_v2alpha.types.PriceInfo.PriceRange): + Output only. The price range of all the child + [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s grouped + together on the + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]. Only + populated for + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct]. + Do not set this field in API requests. + """ + + class PriceRange(proto.Message): + r"""The price range of all + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. + + Attributes: + price (google.cloud.retail_v2alpha.types.Interval): + The inclusive + [Product.pricing_info.price][google.cloud.retail.v2alpha.PriceInfo.price] + interval of all + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] having the + same + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. + original_price (google.cloud.retail_v2alpha.types.Interval): + The inclusive + [Product.pricing_info.original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + internal of all + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] having the + same + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. + """ + + price = proto.Field( + proto.MESSAGE, + number=1, + message='Interval', + ) + original_price = proto.Field( + proto.MESSAGE, + number=2, + message='Interval', + ) + + currency_code = proto.Field( + proto.STRING, + number=1, + ) + price = proto.Field( + proto.FLOAT, + number=2, + ) + original_price = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + price_effective_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + price_expire_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + price_range = proto.Field( + proto.MESSAGE, + number=7, + message=PriceRange, + ) + + +class Rating(proto.Message): + r"""The rating of a [Product][google.cloud.retail.v2alpha.Product]. + + Attributes: + rating_count (int): + The total number of ratings. This value is independent of + the value of + [rating_histogram][google.cloud.retail.v2alpha.Rating.rating_histogram]. + + This value must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + average_rating (float): + The average rating of the + [Product][google.cloud.retail.v2alpha.Product]. + + The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT + error is returned. + rating_histogram (Sequence[int]): + List of rating counts per rating value (index = rating - 1). + The list is empty if there is no rating. If the list is + non-empty, its size is always 5. Otherwise, an + INVALID_ARGUMENT error is returned. + + For example, [41, 14, 13, 47, 303]. It means that the + [Product][google.cloud.retail.v2alpha.Product] got 41 + ratings with 1 star, 14 ratings with 2 star, and so on. + """ + + rating_count = proto.Field( + proto.INT32, + number=1, + ) + average_rating = proto.Field( + proto.FLOAT, + number=2, + ) + rating_histogram = proto.RepeatedField( + proto.INT32, + number=3, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. + + Always use a hashed value for this ID. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + ip_address (str): + The end user's IP address. This field is used to extract + location information for personalization. + + This field must be either an IPv4 address (e.g. + "104.133.9.80") or an IPv6 address (e.g. + "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an + INVALID_ARGUMENT error is returned. + + This should not be set when: + + - setting + [SearchRequest.user_info][google.cloud.retail.v2alpha.SearchRequest.user_info]. + - using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2alpha.UserInfo.direct_user_request] + is set. + user_agent (str): + User agent as included in the HTTP header. Required for + getting + [SearchResponse.sponsored_results][google.cloud.retail.v2alpha.SearchResponse.sponsored_results]. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2alpha.UserInfo.direct_user_request] + is set. + direct_user_request (bool): + True if the request is made directly from the end user, in + which case the + [ip_address][google.cloud.retail.v2alpha.UserInfo.ip_address] + and + [user_agent][google.cloud.retail.v2alpha.UserInfo.user_agent] + can be populated from the HTTP request. This flag should be + set only if the API request is made directly from the end + user such as a mobile app (and not if a gateway or a server + is processing and pushing the user events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent]. + """ + + user_id = proto.Field( + proto.STRING, + number=1, + ) + ip_address = proto.Field( + proto.STRING, + number=2, + ) + user_agent = proto.Field( + proto.STRING, + number=3, + ) + direct_user_request = proto.Field( + proto.BOOL, + number=4, + ) + + +class LocalInventory(proto.Message): + r"""The inventory information at a place (e.g. a store) + identified by a place ID. + + Attributes: + place_id (str): + The place ID for the current set of inventory + information. + price_info (google.cloud.retail_v2alpha.types.PriceInfo): + Product price and cost information. + + Google Merchant Center property + `price `__. + attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): + Additional local inventory attributes, for example, store + name, promotion tags, etc. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - At most 30 attributes are allowed. + - The key must be a UTF-8 encoded string with a length + limit of 32 characters. + - The key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis + or KEY_1_LIKE_THIS. + - The attribute values must be of the same type (text or + number). + - Only 1 value is allowed for each attribute. + - For text values, the length limit is 256 UTF-8 + characters. + - The attribute does not support search. The ``searchable`` + field should be unset or set to false. + - The max summed total bytes of custom attribute keys and + values per product is 5MiB. + fulfillment_types (Sequence[str]): + Input only. Supported fulfillment types. Valid fulfillment + type values include commonly used types (such as pickup in + store and same day delivery), and custom types. Customers + have to map custom types to their display names before + rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + All the elements must be distinct. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + place_id = proto.Field( + proto.STRING, + number=1, + ) + price_info = proto.Field( + proto.MESSAGE, + number=2, + message='PriceInfo', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='CustomAttribute', + ) + fulfillment_types = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py new file mode 100644 index 00000000..f3bb27b3 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'CompleteQueryRequest', + 'CompleteQueryResponse', + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Auto-complete parameters. + + Attributes: + catalog (str): + Required. Catalog for which the completion is performed. + + Full resource name of catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + query (str): + Required. The query used to generate + suggestions. + The maximum number of allowed characters is 255. + visitor_id (str): + Required field. A unique identifier for tracking visitors. + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + language_codes (Sequence[str]): + The language filters applied to the output suggestions. If + set, it should contain the language of the query. If not + set, suggestions are returned without considering language + restrictions. This is the BCP-47 language code, such as + "en-US" or "sr-Latn". For more information, see `Tags for + Identifying + Languages `__. The + maximum number of language codes is 3. + device_type (str): + The device type context for completion suggestions. It is + useful to apply different suggestions on different device + types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the + suggestions are across all device types. + + Supported formats: + + - ``UNKNOWN_DEVICE_TYPE`` + + - ``DESKTOP`` + + - ``MOBILE`` + + - A customized string starts with ``OTHER_``, e.g. + ``OTHER_IPHONE``. + dataset (str): + Determines which dataset to use for fetching completion. + "user-data" will use the imported dataset through + [CompletionService.ImportCompletionData][google.cloud.retail.v2alpha.CompletionService.ImportCompletionData]. + "cloud-retail" will use the dataset generated by cloud + retail based on user events. If leave empty, it will use the + "user-data". + + Current supported values: + + - user-data + + - cloud-retail This option requires additional + allowlisting. Before using cloud-retail, contact Cloud + Retail support team first. + max_suggestions (int): + Completion max suggestions. If left unset or set to 0, then + will fallback to the configured value + [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions]. + + The maximum allowed max suggestions is 20. If it is set + higher, it will be capped by 20. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + visitor_id = proto.Field( + proto.STRING, + number=7, + ) + language_codes = proto.RepeatedField( + proto.STRING, + number=3, + ) + device_type = proto.Field( + proto.STRING, + number=4, + ) + dataset = proto.Field( + proto.STRING, + number=6, + ) + max_suggestions = proto.Field( + proto.INT32, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response of the auto-complete query. + + Attributes: + completion_results (Sequence[google.cloud.retail_v2alpha.types.CompleteQueryResponse.CompletionResult]): + Results of the matching suggestions. The + result list is ordered and the first result is + top suggestion. + attribution_token (str): + A unique complete token. This should be included in the + [UserEvent.completion_detail][google.cloud.retail.v2alpha.UserEvent.completion_detail] + for search events resulting from this completion, which + enables accurate attribution of complete model performance. + recent_search_results (Sequence[google.cloud.retail_v2alpha.types.CompleteQueryResponse.RecentSearchResult]): + Matched recent searches of this user. The maximum number of + recent searches is 10. This field is a restricted feature. + Contact Retail Search support team if you are interested in + enabling it. + + This feature is only available when + [CompleteQueryRequest.visitor_id][google.cloud.retail.v2alpha.CompleteQueryRequest.visitor_id] + field is set and + [UserEvent][google.cloud.retail.v2alpha.UserEvent] is + imported. The recent searches satisfy the follow rules: + + - They are ordered from latest to oldest. + - They are matched with + [CompleteQueryRequest.query][google.cloud.retail.v2alpha.CompleteQueryRequest.query] + case insensitively. + - They are transformed to lower cases. + - They are UTF-8 safe. + + Recent searches are deduplicated. More recent searches will + be reserved when duplication happens. + """ + + class CompletionResult(proto.Message): + r"""Resource that represents completion results. + + Attributes: + suggestion (str): + The suggestion for the query. + attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): + Custom attributes for the suggestion term. + + - For "user-data", the attributes are additional custom + attributes ingested through BigQuery. + - For "cloud-retail", the attributes are product attributes + generated by Cloud Retail. + """ + + suggestion = proto.Field( + proto.STRING, + number=1, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=common.CustomAttribute, + ) + + class RecentSearchResult(proto.Message): + r"""Recent search of this user. + + Attributes: + recent_search (str): + The recent search query. + """ + + recent_search = proto.Field( + proto.STRING, + number=1, + ) + + completion_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=CompletionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + recent_search_results = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=RecentSearchResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py new file mode 100644 index 00000000..93e84d08 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'Control', + }, +) + + +class Control(proto.Message): + r"""Configures dynamic serving time metadata that is used to pre + and post process search/recommendation model results. + + 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: + facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec): + A facet specification to perform faceted + search. + + This field is a member of `oneof`_ ``control``. + rule (google.cloud.retail_v2alpha.types.Rule): + A rule control - a condition-action pair. + Enacts a set action when the condition is + triggered. For example: Boost "gShoe" when query + full matches "Running Shoes". + + This field is a member of `oneof`_ ``control``. + name (str): + Immutable. Fully qualified name + projects/\ */locations/global/catalogs/*/controls/\* + display_name (str): + Required. The human readable control display name. Used in + Retail UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is thrown. + associated_serving_config_ids (Sequence[str]): + Output only. List of serving configuration + ids that that are associated with this control. + Note the association is managed via the + ServingConfig, this is an output only + denormalizeed view. Assumed to be in the same + catalog. + solution_types (Sequence[google.cloud.retail_v2alpha.types.SolutionType]): + Required. Immutable. The solution types that the serving + config is used for. Currently we support setting only one + type of solution at creation time. + + Only ``SOLUTION_TYPE_SEARCH`` value is supported at the + moment. If no solution type is provided at creation time, + will default to SOLUTION_TYPE_SEARCH. + search_solution_use_case (Sequence[google.cloud.retail_v2alpha.types.SearchSolutionUseCase]): + Required. Specifies the use case for the control. Affects + what condition fields can be set. Only settable by search + controls. Will default to SEARCH_SOLUTION_USE_CASE_SEARCH if + not specified. Currently only allow one + search_solution_use_case per control. + """ + + facet_spec = proto.Field( + proto.MESSAGE, + number=3, + oneof='control', + message=search_service.SearchRequest.FacetSpec, + ) + rule = proto.Field( + proto.MESSAGE, + number=4, + oneof='control', + message=common.Rule, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + associated_serving_config_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + solution_types = proto.RepeatedField( + proto.ENUM, + number=6, + enum=common.SolutionType, + ) + search_solution_use_case = proto.RepeatedField( + proto.ENUM, + number=7, + enum=common.SearchSolutionUseCase, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py new file mode 100644 index 00000000..da0c4915 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'CreateControlRequest', + 'UpdateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + }, +) + + +class CreateControlRequest(proto.Message): + r"""Request for CreateControl method. + + Attributes: + parent (str): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + control (google.cloud.retail_v2alpha.types.Control): + Required. The Control to create. + control_id (str): + Required. The ID to use for the Control, which will become + the final component of the Control's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-_/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + control = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_control.Control, + ) + control_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateControlRequest(proto.Message): + r"""Request for UpdateControl method. + + Attributes: + control (google.cloud.retail_v2alpha.types.Control): + Required. The Control to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Control][google.cloud.retail.v2alpha.Control] to update. + The following are NOT supported: + + - [Control.name][google.cloud.retail.v2alpha.Control.name] + + If not set or empty, all supported fields are updated. + """ + + control = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_control.Control, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteControlRequest(proto.Message): + r"""Request for DeleteControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetControlRequest(proto.Message): + r"""Request for GetControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListControlsRequest(proto.Message): + r"""Request for ListControls method. + + Attributes: + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 50. Max + allowed value is 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListControls`` call. Provide this to retrieve the + subsequent page. + filter (str): + Optional. A filter to apply on the list results. Supported + features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2alpha.ListControlsRequest.filter] + is unset. + - List controls that are used in a single ServingConfig: + 'serving_config = "boosted_home_page_cvr"' + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListControlsResponse(proto.Message): + r"""Response for ListControls method. + + Attributes: + controls (Sequence[google.cloud.retail_v2alpha.types.Control]): + All the Controls for a given catalog. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + controls = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_control.Control, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py new file mode 100644 index 00000000..ffb42fde --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + }, +) + + +class ExportErrorsConfig(proto.Message): + r"""Configuration of destination for Export related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage path for import errors. This must be an + empty, existing Cloud Storage bucket. Export errors will be + written to a file in this bucket, one per line, as a + JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ExportMetadata(proto.Message): + r"""Metadata related to the progress of the Export operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ExportProductsResponse(proto.Message): + r"""Response of the ExportProductsRequest. If the long running + operation is done, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2alpha.types.ExportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExportErrorsConfig', + ) + + +class ExportUserEventsResponse(proto.Message): + r"""Response of the ExportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2alpha.types.ExportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExportErrorsConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py new file mode 100644 index 00000000..b6260358 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py @@ -0,0 +1,691 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import user_event +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'GcsSource', + 'BigQuerySource', + 'ProductInlineSource', + 'UserEventInlineSource', + 'ImportErrorsConfig', + 'ImportProductsRequest', + 'ImportUserEventsRequest', + 'ImportCompletionDataRequest', + 'ProductInputConfig', + 'UserEventInputConfig', + 'CompletionDataInputConfig', + 'ImportMetadata', + 'ImportProductsResponse', + 'ImportUserEventsResponse', + 'UserEventImportSummary', + 'ImportCompletionDataResponse', + }, +) + + +class GcsSource(proto.Message): + r"""Google Cloud Storage location for input content. + format. + + Attributes: + input_uris (Sequence[str]): + Required. Google Cloud Storage URIs to input files. URI can + be up to 2000 characters long. URIs can match the full + object path (for example, + ``gs://bucket/directory/object.json``) or a pattern matching + one or more files, such as ``gs://bucket/directory/*.json``. + A request can contain at most 100 files, and each file can + be up to 2 GB. See `Importing product + information `__ + for the expected file format and setup instructions. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2alpha.Product] per line. + Each product must have a valid + [Product.id][google.cloud.retail.v2alpha.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2alpha.UserEvent] per + line. + - ``user_event_ga360``: Using + https://support.google.com/analytics/answer/3437719. + + Supported values for control imports: + + - 'control' (default): One JSON + [Control][google.cloud.retail.v2alpha.Control] per line. + + Supported values for catalog attribute imports: + + - 'catalog_attribute' (default): One CSV + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + per line. + """ + + input_uris = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID (can be project # or ID) that + the BigQuery source is in with a length limit of + 128 characters. If not specified, inherits the + project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2alpha.Product] per line. + Each product must have a valid + [Product.id][google.cloud.retail.v2alpha.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2alpha.UserEvent] per + line. + - ``user_event_ga360``: The schema is available here: + https://support.google.com/analytics/answer/3437719. + - ``user_event_ga4``: This feature is in private preview. + Please contact the support team for importing Google + Analytics 4 events. The schema is available here: + https://support.google.com/analytics/answer/7029846. + + Supported values for auto-completion imports: + + - ``suggestions`` (default): One JSON completion suggestion + per line. + - ``denylist``: One JSON deny suggestion per line. + - ``allowlist``: One JSON allow suggestion per line. + """ + + partition_date = proto.Field( + proto.MESSAGE, + number=6, + oneof='partition', + message=date_pb2.Date, + ) + project_id = proto.Field( + proto.STRING, + number=5, + ) + dataset_id = proto.Field( + proto.STRING, + number=1, + ) + table_id = proto.Field( + proto.STRING, + number=2, + ) + gcs_staging_dir = proto.Field( + proto.STRING, + number=3, + ) + data_schema = proto.Field( + proto.STRING, + number=4, + ) + + +class ProductInlineSource(proto.Message): + r"""The inline source for the input config for ImportProducts + method. + + Attributes: + products (Sequence[google.cloud.retail_v2alpha.types.Product]): + Required. A list of products to update/create. Each product + must have a valid + [Product.id][google.cloud.retail.v2alpha.Product.id]. + Recommended max of 100 items. + """ + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=product.Product, + ) + + +class UserEventInlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (Sequence[google.cloud.retail_v2alpha.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + +class ImportErrorsConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage prefix for import errors. This must be + an empty, existing Cloud Storage directory. Import errors + will be written to sharded files in this directory, one per + line, as a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportProductsRequest(proto.Message): + r"""Request message for Import methods. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` + + If no updateMask is specified, requires products.create + permission. If updateMask is specified, requires + products.update permission. + request_id (str): + Deprecated. This field has no effect. + input_config (google.cloud.retail_v2alpha.types.ProductInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported 'products' to update. If not set, will + by default update all fields. + reconciliation_mode (google.cloud.retail_v2alpha.types.ImportProductsRequest.ReconciliationMode): + The mode of reconciliation between existing products and the + products to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + """ + class ReconciliationMode(proto.Enum): + r"""Indicates how imported products are reconciled with the + existing products created or imported before. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + request_id = proto.Field( + proto.STRING, + number=6, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='ProductInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + reconciliation_mode = proto.Field( + proto.ENUM, + number=5, + enum=ReconciliationMode, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=7, + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + input_config (google.cloud.retail_v2alpha.types.UserEventInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='UserEventInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + + +class ImportCompletionDataRequest(proto.Message): + r"""Request message for ImportCompletionData methods. + + Attributes: + parent (str): + Required. The catalog which the suggestions dataset belongs + to. + + Format: + ``projects/1234/locations/global/catalogs/default_catalog``. + input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): + Required. The desired input location of the + data. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='CompletionDataInputConfig', + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=3, + ) + + +class ProductInputConfig(proto.Message): + r"""The input config source for products. + + 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: + product_inline_source (google.cloud.retail_v2alpha.types.ProductInlineSource): + The Inline source for the input content for + products. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2alpha.types.GcsSource): + Google Cloud Storage location for the input + content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + product_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='ProductInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class UserEventInputConfig(proto.Message): + r"""The input config source for user events. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user_event_inline_source (google.cloud.retail_v2alpha.types.UserEventInlineSource): + Required. The Inline source for the input + content for UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2alpha.types.GcsSource): + Required. Google Cloud Storage location for + the input content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): + Required. BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + user_event_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='UserEventInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class CompletionDataInputConfig(proto.Message): + r"""The input config source for completion data. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): + Required. BigQuery input source. + Add the IAM permission "BigQuery Data Viewer" + for + cloud-retail-customer-data-access@system.gserviceaccount.com + before using this feature otherwise an error is + thrown. + + This field is a member of `oneof`_ ``source``. + """ + + big_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='BigQuerySource', + ) + + +class ImportMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + request_id (str): + Deprecated. This field is never set. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=3, + ) + failure_count = proto.Field( + proto.INT64, + number=4, + ) + request_id = proto.Field( + proto.STRING, + number=5, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=6, + ) + + +class ImportProductsResponse(proto.Message): + r"""Response of the + [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + import_summary (google.cloud.retail_v2alpha.types.UserEventImportSummary): + Aggregated statistics of user event import + status. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + import_summary = proto.Field( + proto.MESSAGE, + number=3, + message='UserEventImportSummary', + ) + + +class UserEventImportSummary(proto.Message): + r"""A summary of import result. The UserEventImportSummary + summarizes the import status for user events. + + Attributes: + joined_events_count (int): + Count of user events imported with complete + existing catalog information. + unjoined_events_count (int): + Count of user events imported, but with + catalog information not found in the imported + catalog. + """ + + joined_events_count = proto.Field( + proto.INT64, + number=1, + ) + unjoined_events_count = proto.Field( + proto.INT64, + number=2, + ) + + +class ImportCompletionDataResponse(proto.Message): + r"""Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. + 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 (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py new file mode 100644 index 00000000..51233cae --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import user_event as gcr_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'PredictRequest', + 'PredictResponse', + }, +) + + +class PredictRequest(proto.Message): + r"""Request message for Predict method. + + Attributes: + placement (str): + Required. Full resource name of the format: + {name=projects/*/locations/global/catalogs/default_catalog/placements/*} + The ID of the Recommendations AI placement. Before you can + request predictions from your model, you must create at + least one placement for it. For more information, see + `Managing + placements `__. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements + user_event (google.cloud.retail_v2alpha.types.UserEvent): + Required. Context about the user, what they + are looking at and what action they took to + trigger the predict request. Note that this user + event detail won't be ingested to userEvent + logs. Thus, a separate userEvent write request + is required for event logging. + page_size (int): + Maximum number of results to return per page. + Set this property to the number of prediction + results needed. If zero, the service will choose + a reasonable default. The maximum allowed value + is 100. Values above 100 will be coerced to 100. + page_token (str): + The previous PredictResponse.next_page_token. + filter (str): + Filter for restricting prediction results with a length + limit of 5,000 characters. Accepts values for tags and the + ``filterOutOfStockItems`` flag. + + - Tag expressions. Restricts predictions to products that + match all of the specified tags. Boolean operators ``OR`` + and ``NOT`` are supported if the expression is enclosed + in parentheses, and must be separated from the tag values + by a space. ``-"tagA"`` is also supported and is + equivalent to ``NOT "tagA"``. Tag values must be double + quoted UTF-8 encoded strings with a size limit of 1,000 + characters. + + Note: "Recently viewed" models don't support tag + filtering at the moment. + + - filterOutOfStockItems. Restricts predictions to products + that do not have a stockState value of OUT_OF_STOCK. + + Examples: + + - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT + "promotional") + - filterOutOfStockItems tag=(-"promotional") + - filterOutOfStockItems + + If your filter blocks all prediction results, the API will + return generic (unfiltered) popular products. If you only + want results strictly matching the filters, set + ``strictFiltering`` to True in ``PredictRequest.params`` to + receive empty results instead. Note that the API will never + return items with storageStatus of "EXPIRED" or "DELETED" + regardless of filter choices. + validate_only (bool): + Use validate only mode for this prediction + query. If set to true, a dummy model will be + used that returns arbitrary products. Note that + the validate only mode should only be used for + testing the API, or if the model is not ready. + params (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific parameters for the predictions. + + Allowed values: + + - ``returnProduct``: Boolean. If set to true, the + associated product object will be returned in the + ``results.metadata`` field in the prediction response. + - ``returnScore``: Boolean. If set to true, the prediction + 'score' corresponding to each returned product will be + set in the ``results.metadata`` field in the prediction + response. The given 'score' indicates the probability of + an product being clicked/purchased given the user's + context and history. + - ``strictFiltering``: Boolean. True by default. If set to + false, the service will return generic (unfiltered) + popular products instead of empty if your filter blocks + all prediction results. + - ``priceRerankLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of + {'no-price-reranking', 'low-price-reranking', + 'medium-price-reranking', 'high-price-reranking'}. This + gives request-level control and adjusts prediction + results based on product price. + - ``diversityLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of {'no-diversity', + 'low-diversity', 'medium-diversity', 'high-diversity', + 'auto-diversity'}. This gives request-level control and + adjusts prediction results based on product category. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters, and cannot be empty. Values can + be empty, and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + placement = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + filter = proto.Field( + proto.STRING, + number=5, + ) + validate_only = proto.Field( + proto.BOOL, + number=6, + ) + params = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class PredictResponse(proto.Message): + r"""Response message for predict method. + + Attributes: + results (Sequence[google.cloud.retail_v2alpha.types.PredictResponse.PredictionResult]): + A list of recommended products. The order + represents the ranking (from the most relevant + product to the least). + attribution_token (str): + A unique attribution token. This should be included in the + [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs + resulting from this recommendation, which enables accurate + attribution of recommendation model performance. + missing_ids (Sequence[str]): + IDs of products in the request that were + missing from the inventory. + validate_only (bool): + True if the validateOnly property was set in + the request. + """ + + class PredictionResult(proto.Message): + r"""PredictionResult represents the recommendation prediction + results. + + Attributes: + id (str): + ID of the recommended product + metadata (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional product metadata / annotations. + + Possible values: + + - ``product``: JSON representation of the product. Will be + set if ``returnProduct`` is set to true in + ``PredictRequest.params``. + - ``score``: Prediction score in double value. Will be set + if ``returnScore`` is set to true in + ``PredictRequest.params``. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + metadata = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=PredictionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + missing_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py new file mode 100644 index 00000000..492a51ff --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py @@ -0,0 +1,705 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'Product', + }, +) + + +class Product(proto.Message): + r"""Product captures all metadata information of items to be + recommended or searched. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this product becomes unavailable for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + If it is set, the + [Product][google.cloud.retail.v2alpha.Product] is not + available for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + after + [expire_time][google.cloud.retail.v2alpha.Product.expire_time]. + However, the product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + [expire_time][google.cloud.retail.v2alpha.Product.expire_time] + must be later than + [available_time][google.cloud.retail.v2alpha.Product.available_time] + and + [publish_time][google.cloud.retail.v2alpha.Product.publish_time], + otherwise an INVALID_ARGUMENT error is thrown. + + Corresponding properties: Google Merchant Center property + `expiration_date `__. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Input only. The TTL (time to live) of the product. + + If it is set, it must be a non-negative value, and + [expire_time][google.cloud.retail.v2alpha.Product.expire_time] + is set as current timestamp plus + [ttl][google.cloud.retail.v2alpha.Product.ttl]. The derived + [expire_time][google.cloud.retail.v2alpha.Product.expire_time] + is returned in the output and + [ttl][google.cloud.retail.v2alpha.Product.ttl] is left blank + when retrieving the + [Product][google.cloud.retail.v2alpha.Product]. + + If it is set, the product is not available for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + after current timestamp plus + [ttl][google.cloud.retail.v2alpha.Product.ttl]. However, the + product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This field is a member of `oneof`_ ``expiration``. + name (str): + Immutable. Full resource name of the product, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. + id (str): + Immutable. [Product][google.cloud.retail.v2alpha.Product] + identifier, which is the final component of + [name][google.cloud.retail.v2alpha.Product.name]. For + example, this field is "id_1", if + [name][google.cloud.retail.v2alpha.Product.name] is + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `id `__. + Schema.org property + `Product.sku `__. + type_ (google.cloud.retail_v2alpha.types.Product.Type): + Immutable. The type of the product. Default to + [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2alpha.ProductLevelConfig.ingestion_product_type] + if unset. + primary_product_id (str): + Variant group identifier. Must be an + [id][google.cloud.retail.v2alpha.Product.id], with the same + parent branch with this product. Otherwise, an error is + thrown. + + For + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]s, this field + can only be empty or set to the same value as + [id][google.cloud.retail.v2alpha.Product.id]. + + For VARIANT [Product][google.cloud.retail.v2alpha.Product]s, + this field cannot be empty. A maximum of 2,000 products are + allowed to share the same + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]. Otherwise, + an INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `item_group_id `__. + Schema.org property + `Product.inProductGroupWithID `__. + collection_member_ids (Sequence[str]): + The [id][google.cloud.retail.v2alpha.Product.id] of the + collection members when + [type][google.cloud.retail.v2alpha.Product.type] is + [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION]. + + Non-existent product ids are allowed. The + [type][google.cloud.retail.v2alpha.Product.type] of the + members must be either + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + or + [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + otherwise and INVALID_ARGUMENT error is thrown. Should not + set it for other types. A maximum of 1000 values are + allowed. Otherwise, an INVALID_ARGUMENT error is return. + gtin (str): + The Global Trade Item Number (GTIN) of the product. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This field must be a Unigram. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `gtin `__. + Schema.org property + `Product.isbn `__, + `Product.gtin8 `__, + `Product.gtin12 `__, + `Product.gtin13 `__, or + `Product.gtin14 `__. + + If the value is not a valid GTIN, an INVALID_ARGUMENT error + is returned. + categories (Sequence[str]): + Product categories. This field is repeated for supporting + one product belonging to several parallel categories. + Strongly recommended using the full path for better search / + recommendation quality. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + For example, if a shoes product belongs to both ["Shoes & + Accessories" -> "Shoes"] and ["Sports & Fitness" -> + "Athletic Clothing" -> "Shoes"], it could be represented as: + + :: + + "categories": [ + "Shoes & Accessories > Shoes", + "Sports & Fitness > Athletic Clothing > Shoes" + ] + + Must be set for + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] otherwise an + INVALID_ARGUMENT error is returned. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. Empty values + are not allowed. Each value must be a UTF-8 encoded string + with a length limit of 5,000 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `google_product_category `__. + Schema.org property [Product.category] + (https://schema.org/category). + title (str): + Required. Product title. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `title `__. + Schema.org property + `Product.name `__. + brands (Sequence[str]): + The brands of the product. + + A maximum of 30 brands are allowed. Each brand must be a + UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `brand `__. + Schema.org property + `Product.brand `__. + description (str): + Product description. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `description `__. + Schema.org property + `Product.description `__. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. + + For product prediction, this field is ignored and the model + automatically detects the text language. The + [Product][google.cloud.retail.v2alpha.Product] can include + text in different languages, but duplicating + [Product][google.cloud.retail.v2alpha.Product]s to provide + text in multiple languages can result in degraded model + performance. + + For product search this field is in use. It defaults to + "en-US" if unset. + attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): + Highly encouraged. Extra product attributes to be included. + For example, for products, this could include the store + name, vendor, style, color, etc. These are very strong + signals for recommendation model, thus we highly recommend + providing the attributes here. + + Features that can take on one of a limited number of + possible values. Two types of features can be set are: + + Textual features. some examples would be the brand/maker of + a product, or country of a customer. Numerical features. + Some examples would be the height/weight of a product, or + age of a customer. + + For example: + ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - Max entries count: 200. + - The key must be a UTF-8 encoded string with a length + limit of 128 characters. + - For indexable attribute, the key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, + ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a + non-empty UTF-8 encoded string with a length limit of 256 + characters. + - For number attributes, at most 400 values are allowed. + tags (Sequence[str]): + Custom tags associated with the product. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. This value + must be a UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This tag can be used for filtering recommendation results by + passing the tag as part of the + [PredictRequest.filter][google.cloud.retail.v2alpha.PredictRequest.filter]. + + Corresponding properties: Google Merchant Center property + `custom_label_0–4 `__. + price_info (google.cloud.retail_v2alpha.types.PriceInfo): + Product price and cost information. + + Corresponding properties: Google Merchant Center property + `price `__. + rating (google.cloud.retail_v2alpha.types.Rating): + The rating of this product. + available_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this + [Product][google.cloud.retail.v2alpha.Product] becomes + available for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + availability (google.cloud.retail_v2alpha.types.Product.Availability): + The online availability of the + [Product][google.cloud.retail.v2alpha.Product]. Default to + [Availability.IN_STOCK][google.cloud.retail.v2alpha.Product.Availability.IN_STOCK]. + + Corresponding properties: Google Merchant Center property + `availability `__. + Schema.org property + `Offer.availability `__. + available_quantity (google.protobuf.wrappers_pb2.Int32Value): + The available quantity of the item. + fulfillment_info (Sequence[google.cloud.retail_v2alpha.types.FulfillmentInfo]): + Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + All the elements must have distinct + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type]. + Otherwise, an INVALID_ARGUMENT error is returned. + uri (str): + Canonical URL directly linking to the product detail page. + + It is strongly recommended to provide a valid uri for the + product, otherwise the service performance could be + significantly degraded. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `link `__. + Schema.org property `Offer.url `__. + images (Sequence[google.cloud.retail_v2alpha.types.Image]): + Product images for the product. We highly recommend putting + the main image first. + + A maximum of 300 images are allowed. + + Corresponding properties: Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + audience (google.cloud.retail_v2alpha.types.Audience): + The target group associated with a given + audience (e.g. male, veterans, car owners, + musicians, etc.) of the product. + color_info (google.cloud.retail_v2alpha.types.ColorInfo): + The color of the product. + + Corresponding properties: Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + sizes (Sequence[str]): + The size of the product. To represent different size systems + or size types, consider using this format: + [[[size_system:]size_type:]size_value]. + + For example, in "US:MENS:M", "US" represents size system; + "MENS" represents size type; "M" represents size value. In + "GIRLS:27", size system is empty; "GIRLS" represents size + type; "27" represents size value. In "32 inches", both size + system and size type are empty, while size value is "32 + inches". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `size `__, + `size_type `__, + and + `size_system `__. + Schema.org property + `Product.size `__. + materials (Sequence[str]): + The material of the product. For example, "leather", + "wooden". + + A maximum of 20 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 200 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `material `__. + Schema.org property + `Product.material `__. + patterns (Sequence[str]): + The pattern or graphic print of the product. For example, + "striped", "polka dot", "paisley". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `pattern `__. + Schema.org property + `Product.pattern `__. + conditions (Sequence[str]): + The condition of the product. Strongly encouraged to use the + standard values: "new", "refurbished", "used". + + A maximum of 1 value is allowed per + [Product][google.cloud.retail.v2alpha.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `condition `__. + Schema.org property + `Offer.itemCondition `__. + promotions (Sequence[google.cloud.retail_v2alpha.types.Promotion]): + The promotions applied to the product. A maximum of 10 + values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. Only + [Promotion.promotion_id][google.cloud.retail.v2alpha.Promotion.promotion_id] + will be used, other fields will be ignored if set. + publish_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the product is published by the retailer + for the first time, which indicates the freshness of the + products. Note that this field is different from + [available_time][google.cloud.retail.v2alpha.Product.available_time], + given it purely describes product freshness regardless of + when it is available on search and recommendation. + retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the + [Product][google.cloud.retail.v2alpha.Product]s are returned + in + [SearchResponse][google.cloud.retail.v2alpha.SearchResponse]. + + Supported fields for all + [type][google.cloud.retail.v2alpha.Product.type]s: + + - [audience][google.cloud.retail.v2alpha.Product.audience] + - [availability][google.cloud.retail.v2alpha.Product.availability] + - [brands][google.cloud.retail.v2alpha.Product.brands] + - [color_info][google.cloud.retail.v2alpha.Product.color_info] + - [conditions][google.cloud.retail.v2alpha.Product.conditions] + - [gtin][google.cloud.retail.v2alpha.Product.gtin] + - [materials][google.cloud.retail.v2alpha.Product.materials] + - [name][google.cloud.retail.v2alpha.Product.name] + - [patterns][google.cloud.retail.v2alpha.Product.patterns] + - [price_info][google.cloud.retail.v2alpha.Product.price_info] + - [rating][google.cloud.retail.v2alpha.Product.rating] + - [sizes][google.cloud.retail.v2alpha.Product.sizes] + - [title][google.cloud.retail.v2alpha.Product.title] + - [uri][google.cloud.retail.v2alpha.Product.uri] + + Supported fields only for + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION]: + + - [categories][google.cloud.retail.v2alpha.Product.categories] + - [description][google.cloud.retail.v2alpha.Product.description] + - [images][google.cloud.retail.v2alpha.Product.images] + + Supported fields only for + [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT]: + + - Only the first image in + [images][google.cloud.retail.v2alpha.Product.images] + + To mark + [attributes][google.cloud.retail.v2alpha.Product.attributes] + as retrievable, include paths of the form "attributes.key" + where "key" is the key of a custom attribute, as specified + in + [attributes][google.cloud.retail.v2alpha.Product.attributes]. + + For + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION], + the following fields are always returned in + [SearchResponse][google.cloud.retail.v2alpha.SearchResponse] + by default: + + - [name][google.cloud.retail.v2alpha.Product.name] + + For + [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT], + the following fields are always returned in by default: + + - [name][google.cloud.retail.v2alpha.Product.name] + - [color_info][google.cloud.retail.v2alpha.Product.color_info] + + Maximum number of paths is 30. Otherwise, an + INVALID_ARGUMENT error is returned. + + Note: Returning more fields in + [SearchResponse][google.cloud.retail.v2alpha.SearchResponse] + may increase response payload size and serving latency. + variants (Sequence[google.cloud.retail_v2alpha.types.Product]): + Output only. Product variants grouped together on primary + product which share similar product attributes. It's + automatically grouped by + [primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] + for all the product variants. Only populated for + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct]. + Do not set this field in API requests. + """ + class Type(proto.Enum): + r"""The type of this product.""" + TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + VARIANT = 2 + COLLECTION = 3 + + class Availability(proto.Enum): + r"""Product availability. If this field is unspecified, the + product is assumed to be in stock. + """ + AVAILABILITY_UNSPECIFIED = 0 + IN_STOCK = 1 + OUT_OF_STOCK = 2 + PREORDER = 3 + BACKORDER = 4 + + expire_time = proto.Field( + proto.MESSAGE, + number=16, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl = proto.Field( + proto.MESSAGE, + number=17, + oneof='expiration', + message=duration_pb2.Duration, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + type_ = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + primary_product_id = proto.Field( + proto.STRING, + number=4, + ) + collection_member_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + gtin = proto.Field( + proto.STRING, + number=6, + ) + categories = proto.RepeatedField( + proto.STRING, + number=7, + ) + title = proto.Field( + proto.STRING, + number=8, + ) + brands = proto.RepeatedField( + proto.STRING, + number=9, + ) + description = proto.Field( + proto.STRING, + number=10, + ) + language_code = proto.Field( + proto.STRING, + number=11, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message=common.CustomAttribute, + ) + tags = proto.RepeatedField( + proto.STRING, + number=13, + ) + price_info = proto.Field( + proto.MESSAGE, + number=14, + message=common.PriceInfo, + ) + rating = proto.Field( + proto.MESSAGE, + number=15, + message=common.Rating, + ) + available_time = proto.Field( + proto.MESSAGE, + number=18, + message=timestamp_pb2.Timestamp, + ) + availability = proto.Field( + proto.ENUM, + number=19, + enum=Availability, + ) + available_quantity = proto.Field( + proto.MESSAGE, + number=20, + message=wrappers_pb2.Int32Value, + ) + fulfillment_info = proto.RepeatedField( + proto.MESSAGE, + number=21, + message=common.FulfillmentInfo, + ) + uri = proto.Field( + proto.STRING, + number=22, + ) + images = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=common.Image, + ) + audience = proto.Field( + proto.MESSAGE, + number=24, + message=common.Audience, + ) + color_info = proto.Field( + proto.MESSAGE, + number=25, + message=common.ColorInfo, + ) + sizes = proto.RepeatedField( + proto.STRING, + number=26, + ) + materials = proto.RepeatedField( + proto.STRING, + number=27, + ) + patterns = proto.RepeatedField( + proto.STRING, + number=28, + ) + conditions = proto.RepeatedField( + proto.STRING, + number=29, + ) + promotions = proto.RepeatedField( + proto.MESSAGE, + number=34, + message=promotion.Promotion, + ) + publish_time = proto.Field( + proto.MESSAGE, + number=33, + message=timestamp_pb2.Timestamp, + ) + retrievable_fields = proto.Field( + proto.MESSAGE, + number=30, + message=field_mask_pb2.FieldMask, + ) + variants = proto.RepeatedField( + proto.MESSAGE, + number=31, + message='Product', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py new file mode 100644 index 00000000..ddfc08ed --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py @@ -0,0 +1,877 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'CreateProductRequest', + 'GetProductRequest', + 'UpdateProductRequest', + 'DeleteProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'SetInventoryRequest', + 'SetInventoryMetadata', + 'SetInventoryResponse', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesResponse', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesResponse', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesResponse', + }, +) + + +class CreateProductRequest(proto.Message): + r"""Request message for [CreateProduct][] method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + product (google.cloud.retail_v2alpha.types.Product): + Required. The [Product][google.cloud.retail.v2alpha.Product] + to create. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2alpha.Product], which will + become the final component of the + [Product.name][google.cloud.retail.v2alpha.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2alpha.Product]s with the + same + [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + product_id = proto.Field( + proto.STRING, + number=3, + ) + + +class GetProductRequest(proto.Message): + r"""Request message for [GetProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested + [Product][google.cloud.retail.v2alpha.Product] does not + exist, a NOT_FOUND error is returned. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateProductRequest(proto.Message): + r"""Request message for [UpdateProduct][] method. + + Attributes: + product (google.cloud.retail_v2alpha.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Product][google.cloud.retail.v2alpha.Product] to update. + The immutable and output only fields are NOT supported. If + not set, all supported fields (the fields that are neither + immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + a new [Product][google.cloud.retail.v2alpha.Product] will be + created. In this situation, ``update_mask`` is ignored. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteProductRequest(proto.Message): + r"""Request message for [DeleteProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2alpha.Product] to delete + can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] with more + than one + [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2alpha.Product] will be + deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProductsRequest(proto.Message): + r"""Request message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list products + under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2alpha.Product]s under this + branch, regardless of whether or not this branch exists, a + PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [Product][google.cloud.retail.v2alpha.Product]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 + [ListProductsResponse.next_page_token][google.cloud.retail.v2alpha.ListProductsResponse.next_page_token], + received from a previous + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + filter (str): + A filter to apply on the list results. Supported features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2alpha.ListProductsRequest.filter] + is unset. + - List + [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s sharing + the same + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]. For + example: ``primary_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2alpha.Product]s + bundled in a + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product]. For + example: ``collection_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2alpha.Product]s with + a partibular type. For example: ``type = "PRIMARY"`` + ``type = "VARIANT"`` ``type = "COLLECTION"`` + + If the field is unrecognizable, an INVALID_ARGUMENT error is + returned. + + If the specified + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] or + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product] does not + exist, a NOT_FOUND error is returned. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields of [Product][google.cloud.retail.v2alpha.Product] + to return in the responses. If not set or empty, the + following fields are returned: + + - [Product.name][google.cloud.retail.v2alpha.Product.name] + - [Product.id][google.cloud.retail.v2alpha.Product.id] + - [Product.title][google.cloud.retail.v2alpha.Product.title] + - [Product.uri][google.cloud.retail.v2alpha.Product.uri] + - [Product.images][google.cloud.retail.v2alpha.Product.images] + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.brands][google.cloud.retail.v2alpha.Product.brands] + + If "*" is provided, all fields are returned. + [Product.name][google.cloud.retail.v2alpha.Product.name] is + always returned no matter what mask is set. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + require_total_size (bool): + If true and + [page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] + is empty, + [ListProductsResponse.total_size][google.cloud.retail.v2alpha.ListProductsResponse.total_size] + is set to the total count of matched items irrespective of + pagination. + + Notice that setting this field to true affects the + performance. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + require_total_size = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListProductsResponse(proto.Message): + r"""Response message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + + Attributes: + products (Sequence[google.cloud.retail_v2alpha.types.Product]): + The [Product][google.cloud.retail.v2alpha.Product]s. + next_page_token (str): + A token that can be sent as + [ListProductsRequest.page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + total_size (int): + The total count of matched + [Product][google.cloud.retail.v2alpha.Product]s irrespective + of pagination. The total number of + [Product][google.cloud.retail.v2alpha.Product]s returned by + pagination may be less than the + [total_size][google.cloud.retail.v2alpha.ListProductsResponse.total_size] + that matches. + + This field is ignored if + [ListProductsRequest.require_total_size][google.cloud.retail.v2alpha.ListProductsRequest.require_total_size] + is not set or + [ListProductsRequest.page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] + is not empty. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + + +class SetInventoryRequest(proto.Message): + r"""Request message for [SetInventory][] method. + + Attributes: + inventory (google.cloud.retail_v2alpha.types.Product): + Required. The inventory information to update. The allowable + fields to update are: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product] named in + [Product.name][google.cloud.retail.v2alpha.Product.name], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting the + last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of fulfillment + types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear in + [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types have + empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following inventory + fields: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + + If a full overwrite of inventory information while ignoring + timestamps is needed, [UpdateProduct][] should be invoked + instead. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2alpha.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the request is issued, used to + prevent out-of-order updates on inventory fields + with the last update time recorded. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] with name + [Product.name][google.cloud.retail.v2alpha.Product.name] is + not found, the inventory update will still be processed and + retained for at most 1 day until the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + inventory = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + set_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + set_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=4, + ) + + +class SetInventoryMetadata(proto.Message): + r"""Metadata related to the progress of the SetInventory operation. + Currently empty because there is no meaningful metadata populated + from the [SetInventory][] method. + + """ + + +class SetInventoryResponse(proto.Message): + r"""Response of the SetInventoryRequest. Currently empty because there + is no meaningful response populated from the [SetInventory][] + method. + + """ + + +class AddFulfillmentPlacesRequest(proto.Message): + r"""Request message for [AddFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery" to be added for this + [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type]. + Duplicate IDs will be automatically ignored. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If the total number of place IDs exceeds 2000 for this + [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type] + after adding, then the update will be rejected. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + the fulfillment information will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + add_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class AddFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the AddFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [AddFulfillmentPlaces][] method. + + """ + + +class AddFulfillmentPlacesResponse(proto.Message): + r"""Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + + +class AddLocalInventoriesRequest(proto.Message): + r"""Request message for [AddLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + local_inventories (Sequence[google.cloud.retail_v2alpha.types.LocalInventory]): + Required. A list of inventory information at + difference places. Each place is identified by + its place ID. At most 3000 inventories are + allowed per request. + add_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided list of + [LocalInventory][google.cloud.retail.v2alpha.LocalInventory] + to update. The field is updated to the provided value. + + If a field is set while the place does not have a previous + local inventory, the local inventory at that store is + created. + + If a field is set while the value of that field is not + provided, the original field value, if it exists, is + deleted. + + If the mask is not set or set with empty paths, all + inventory fields will be updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory updates are + issued. Used to prevent out-of-order updates on + local inventory fields. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + the local inventory will still be processed and retained for + at most 1 day and processed once the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + local_inventories = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.LocalInventory, + ) + add_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + add_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=6, + ) + + +class AddLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the AddLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [AddLocalInventories][] method. + + """ + + +class AddLocalInventoriesResponse(proto.Message): + r"""Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesRequest(proto.Message): + r"""Request message for [RemoveLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + place_ids (Sequence[str]): + Required. A list of place IDs to have their + inventory deleted. At most 3000 place IDs are + allowed per request. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory deletions are + issued. Used to prevent out-of-order updates and + deletions on local inventory fields. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + the local inventory removal request will still be processed + and retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class RemoveLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesResponse(proto.Message): + r"""Response of the [RemoveLocalInventories][] API. Currently empty + because there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + + +class RemoveFulfillmentPlacesRequest(proto.Message): + r"""Request message for [RemoveFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery", to be removed for this + [type][google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type]. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + the fulfillment information will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class RemoveFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveFulfillmentPlaces][] method. + + """ + + +class RemoveFulfillmentPlacesResponse(proto.Message): + r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty + because there is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py new file mode 100644 index 00000000..bd5b8a58 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'Promotion', + }, +) + + +class Promotion(proto.Message): + r"""Promotion information. + + Attributes: + promotion_id (str): + ID of the promotion. For example, "free gift". + + The value must be a UTF-8 encoded string with a length limit + of 128 characters, and match the pattern: + ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or + ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is + returned. + + Google Merchant Center property + `promotion `__. + """ + + promotion_id = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py new file mode 100644 index 00000000..ad7ff6f6 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py @@ -0,0 +1,251 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'PurgeMetadata', + 'PurgeProductsMetadata', + 'PurgeProductsRequest', + 'PurgeProductsResponse', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + }, +) + + +class PurgeMetadata(proto.Message): + r"""Metadata related to the progress of the Purge operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + """ + + +class PurgeProductsMetadata(proto.Message): + r"""Metadata related to the progress of the PurgeProducts + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were deleted + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=3, + ) + failure_count = proto.Field( + proto.INT64, + number=4, + ) + + +class PurgeProductsRequest(proto.Message): + r"""Request message for PurgeProducts method. + + Attributes: + parent (str): + Required. The resource name of the branch under which the + products are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}/branches/${branchId}`` + filter (str): + Required. The filter string to specify the products to be + deleted with a length limit of 5,000 characters. + + Empty string filter is not allowed. "*" implies delete all + items in a branch. + + The eligible fields for filtering are: + + - ``availability``: Double quoted + [Product.availability][google.cloud.retail.v2alpha.Product.availability] + string. + - ``create_time`` : in ISO 8601 "zulu" format. + + Supported syntax: + + - Comparators (">", "<", ">=", "<=", "="). Examples: + + - create_time <= "2015-02-13T17:05:46Z" + - availability = "IN_STOCK" + + - Conjunctions ("AND") Examples: + + - create_time <= "2015-02-13T17:05:46Z" AND availability + = "PREORDER" + + - Disjunctions ("OR") Examples: + + - create_time <= "2015-02-13T17:05:46Z" OR availability + = "IN_STOCK" + + - Can support nested queries. Examples: + + - (create_time <= "2015-02-13T17:05:46Z" AND + availability = "PREORDER") OR (create_time >= + "2015-02-14T13:03:32Z" AND availability = "IN_STOCK") + + - Filter Limits: + + - Filter should not contain more than 6 conditions. + - Max nesting depth should not exceed 2 levels. + + Examples queries: + + - Delete back order products created before a timestamp. + create_time <= "2015-02-13T17:05:46Z" OR availability = + "BACKORDER". + force (bool): + Actually perform the purge. If ``force`` is set to false, + the method will return the expected purge count without + deleting any products. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeProductsResponse(proto.Message): + r"""Response of the PurgeProductsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purge_count (int): + The total count of products purged as a + result of the operation. + purge_sample (Sequence[str]): + A sample of the product names that will be deleted. Only + populated if ``force`` is set to false. A max of 100 names + will be returned and the names are chosen at random. + """ + + purge_count = proto.Field( + proto.INT64, + number=1, + ) + purge_sample = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + + Attributes: + parent (str): + Required. The resource name of the catalog under which the + events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}`` + filter (str): + Required. The filter string to specify the events to be + deleted with a length limit of 5,000 characters. Empty + string filter is not allowed. The eligible fields for + filtering are: + + - ``eventType``: Double quoted + [UserEvent.event_type][google.cloud.retail.v2alpha.UserEvent.event_type] + string. + - ``eventTime``: in ISO 8601 "zulu" format. + - ``visitorId``: Double quoted string. Specifying this will + delete all events associated with a visitor. + - ``userId``: Double quoted string. Specifying this will + delete all events associated with a user. + + Examples: + + - Deleting all events in a time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + - Deleting specific eventType in time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + - Deleting all events for a specific visitor: + ``visitorId = "visitor1024"`` + + The filtering fields are assumed to have an implicit AND. + force (bool): + Actually perform the purge. If ``force`` is set to false, + the method will return the expected purge count without + deleting any user events. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsResponse(proto.Message): + r"""Response of the PurgeUserEventsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purged_events_count (int): + The total count of events purged as a result + of the operation. + """ + + purged_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py new file mode 100644 index 00000000..e4dc0ba2 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py @@ -0,0 +1,1099 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'SearchRequest', + 'SearchResponse', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + + Attributes: + placement (str): + Required. The resource name of the search engine placement, + such as + ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` + This field is used to identify the serving configuration + name and the set of models that will be used to make the + search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + + Use "default_branch" as the branch ID or leave this field + empty, to search products under the default branch. + query (str): + Raw search query. + visitor_id (str): + Required. A unique identifier for tracking visitors. For + example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + This should be the same identifier as + [UserEvent.visitor_id][google.cloud.retail.v2alpha.UserEvent.visitor_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2alpha.types.UserInfo): + User information. + page_size (int): + Maximum number of + [Product][google.cloud.retail.v2alpha.Product]s to return. + If unspecified, defaults to a reasonable value. The maximum + allowed value is 120. Values above 120 will be coerced to + 120. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [SearchResponse.next_page_token][google.cloud.retail.v2alpha.SearchResponse.next_page_token], + received from a previous + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Product][google.cloud.retail.v2alpha.Product]s deemed by + the API as relevant) in search results. This field is only + considered if + [page_token][google.cloud.retail.v2alpha.SearchRequest.page_token] + is unset. + + If this field is negative, an INVALID_ARGUMENT is returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. Filter expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + canonical_filter (str): + The default filter that is applied when a user performs a + search without checking any filters on the search page. + + The filter applied to every search request when quality + improvement such as query expansion is needed. For example, + if a query does not have enough results, an expanded query + with + [SearchRequest.canonical_filter][google.cloud.retail.v2alpha.SearchRequest.canonical_filter] + will be returned as a supplement of the original query. This + field is strongly recommended to achieve high search + quality. + + See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for more details about filter syntax. + order_by (str): + The order in which products are returned. Products can be + ordered by a field in an + [Product][google.cloud.retail.v2alpha.Product] object. Leave + it unset if ordered by relevance. OrderBy expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + facet_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + dynamic_facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec): + Deprecated. Refer to + https://cloud.google.com/retail/docs/configs#dynamic + to enable dynamic facets. Do not set this field. + The specification for dynamically generated + facets. Notice that only textual facets can be + dynamically generated. + boost_spec (google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec): + Boost specification to boost certain products. See more + details at this `user + guide `__. + + Notice that if both + [ServingConfig.boost_control_ids][google.cloud.retail.v2alpha.ServingConfig.boost_control_ids] + and [SearchRequest.boost_spec] are set, the boost conditions + from both places are evaluated. If a search request matches + multiple boost conditions, the final boost score is equal to + the sum of the boost scores from all matched boost + conditions. + query_expansion_spec (google.cloud.retail_v2alpha.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that specifies the + conditions under which query expansion will occur. See more + details at this `user + guide `__. + relevance_threshold (google.cloud.retail_v2alpha.types.SearchRequest.RelevanceThreshold): + The relevance threshold of the search results. + + Defaults to + [RelevanceThreshold.HIGH][google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH], + which means only the most relevant results are shown, and + the least number of results are returned. See more details + at this `user + guide `__. + variant_rollup_keys (Sequence[str]): + The keys to fetch and rollup the matching + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s attributes, + [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo] + or + [LocalInventory][google.cloud.retail.v2alpha.LocalInventory]s + attributes. The attributes from all the matching + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s or + [LocalInventory][google.cloud.retail.v2alpha.LocalInventory]s + are merged and de-duplicated. Notice that rollup attributes + will lead to extra query latency. Maximum number of keys is + 30. + + For + [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], + a fulfillment type and a fulfillment ID must be provided in + the format of "fulfillmentType.fulfillmentId". E.g., in + "pickupInStore.store123", "pickupInStore" is fulfillment + type and "store123" is the store ID. + + Supported keys are: + + - colorFamilies + - price + - originalPrice + - discount + - variantId + - inventory(place_id,price) + - inventory(place_id,original_price) + - inventory(place_id,attributes.key), where key is any key + in the [Product.inventories.attributes][] map. + - attributes.key, where key is any key in the + [Product.attributes][google.cloud.retail.v2alpha.Product.attributes] + map. + - pickupInStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "pickup-in-store". + - shipToStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "ship-to-store". + - sameDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "same-day-delivery". + - nextDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "next-day-delivery". + - customFulfillment1.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-1". + - customFulfillment2.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-2". + - customFulfillment3.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-3". + - customFulfillment4.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-4". + - customFulfillment5.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-5". + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. Required for + category navigation queries to achieve good search quality. + The format should be the same as + [UserEvent.page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories]; + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + search_mode (google.cloud.retail_v2alpha.types.SearchRequest.SearchMode): + The search mode of the search request. If not + specified, a single search request triggers both + product search and faceted search. + personalization_spec (google.cloud.retail_v2alpha.types.SearchRequest.PersonalizationSpec): + The specification for personalization. + """ + class RelevanceThreshold(proto.Enum): + r"""The relevance threshold of the search results. The higher + relevance threshold is, the higher relevant results are shown + and the less number of results are returned. + """ + RELEVANCE_THRESHOLD_UNSPECIFIED = 0 + HIGH = 1 + MEDIUM = 2 + LOW = 3 + LOWEST = 4 + + class SearchMode(proto.Enum): + r"""The search mode of each search request.""" + SEARCH_MODE_UNSPECIFIED = 0 + PRODUCT_SEARCH_ONLY = 1 + FACETED_SEARCH_ONLY = 2 + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum of facet values that should be returned for this + facet. If unspecified, defaults to 20. The maximum allowed + value is 300. Values above 300 will be coerced to 300. + + If this field is negative, an INVALID_ARGUMENT is returned. + excluded_filter_keys (Sequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + For example, suppose there are 100 products with color facet + "Red" and 200 products with color facet "Blue". A query + containing the filter "colorFamilies:ANY("Red")" and have + "colorFamilies" as + [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] + will by default return the "Red" with count 100. + + If this field contains "colorFamilies", then the query + returns both the "Red" with count 100 and "Blue" with count + 200, because the "colorFamilies" key is now excluded from + the filter. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined by Google Retail Search. It will be ordered + together with dynamic facets if dynamic facets is enabled. + If set to false, the position of this facet in the response + will be the same as in the request, and it will be ranked + before the facets with dynamic position enable and all + dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response will be determined by Google Retail + Search. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enable, which will + generate a facet 'gender'. Then the final order of the + facets in the response can be ("price", "brands", "rating", + "gender") or ("price", "brands", "gender", "rating") depends + on how Google Retail Search orders "gender" and "rating" + facets. However, notice that "price" and "brands" will + always be ranked at 1st and 2nd position since their + enable_dynamic_position are false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Product][google.cloud.retail.v2alpha.Product] object, over + which the facet values are computed. Facet key is + case-sensitive. + + Allowed facet keys when + [FacetKey.query][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.query] + is not specified: + + - textual_field = + + - "brands" + - "categories" + - "genders" + - "ageGroups" + - "availability" + - "colorFamilies" + - "colors" + - "sizes" + - "materials" + - "patterns" + - "conditions" + - "attributes.key" + - "pickupInStore" + - "shipToStore" + - "sameDayDelivery" + - "nextDayDelivery" + - "customFulfillment1" + - "customFulfillment2" + - "customFulfillment3" + - "customFulfillment4" + - "customFulfillment5" + - "inventory(place_id,attributes.key)" + + - numerical_field = + + - "price" + - "discount" + - "rating" + - "ratingCount" + - "attributes.key" + - "inventory(place_id,price)" + - "inventory(place_id,original_price)" + - "inventory(place_id,attributes.key)". + intervals (Sequence[google.cloud.retail_v2alpha.types.Interval]): + Set only if values should be bucketized into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (Sequence[str]): + Only get facet for the given restricted values. For example, + when using "pickupInStore" as key and set restricted values + to ["store123", "store456"], only facets for "store123" and + "store456" are returned. Only supported on textual fields + and fulfillments. Maximum is 20. + + Must be set for the fulfillment facet keys: + + - pickupInStore + + - shipToStore + + - sameDayDelivery + + - nextDayDelivery + + - customFulfillment1 + + - customFulfillment2 + + - customFulfillment3 + + - customFulfillment4 + + - customFulfillment5 + prefixes (Sequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "categories" has three values "Women > Shoe", + "Women > Dress" and "Men > Shoe". If set + "prefixes" to "Women", the "categories" facet + will give only "Women > Shoe" and "Women > + Dress". Only supported on textual fields. + Maximum is 10. + contains (Sequence[str]): + Only get facet values that contains the given + strings. For example, suppose "categories" has + three values "Women > Shoe", "Women > Dress" and + "Men > Shoe". If set "contains" to "Shoe", the + "categories" facet will give only "Women > Shoe" + and "Men > Shoe". Only supported on textual + fields. Maximum is 10. + order_by (str): + The order in which [Facet.values][] are returned. + + Allowed values are: + + - "count desc", which means order by + [Facet.FacetValue.count][] descending. + + - "value desc", which means order by + [Facet.FacetValue.value][] descending. Only applies to + textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.intervals]; + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + are sorted in the order given by + [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.restricted_values]. + query (str): + The query that is used to compute facet for the given facet + key. When provided, it will override the default behavior of + facet computation. The query syntax is the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for detail syntax and limitations. Notice that there is no + limitation on + [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] + when query is specified. + + In the response, [FacetValue.value][] will be always "1" and + [FacetValue.count][] will be the number of results that + matches the query. + + For example, you can set a customized facet for + "shipToStore", where + [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] + is "customizedShipToStore", and + [FacetKey.query][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.query] + is "availability: ANY("IN_STOCK") AND shipToStore: + ANY("123")". Then the facet will count the products that are + both in stock and ship to store "123". + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + intervals = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes = proto.RepeatedField( + proto.STRING, + number=8, + ) + contains = proto.RepeatedField( + proto.STRING, + number=9, + ) + order_by = proto.Field( + proto.STRING, + number=4, + ) + query = proto.Field( + proto.STRING, + number=5, + ) + + facet_key = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.FacetSpec.FacetKey', + ) + limit = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position = proto.Field( + proto.BOOL, + number=4, + ) + + class DynamicFacetSpec(proto.Message): + r"""The specifications of dynamically generated facets. + + Attributes: + mode (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec.Mode): + Mode of the DynamicFacet feature. Defaults to + [Mode.DISABLED][google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec.Mode.DISABLED] + if it's unset. + """ + class Mode(proto.Enum): + r"""Enum to control DynamicFacet mode""" + MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.DynamicFacetSpec.Mode', + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain items. + + Attributes: + condition_boost_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a product + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 10. + skip_boost_spec_validation (bool): + Whether to skip boostspec validation. If this field is set + to true, invalid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] + will be ignored and valid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] + will still be applied. + + This field is a member of `oneof`_ ``_skip_boost_spec_validation``. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to products which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": + + - (id: ANY("product_1", "product_2")) AND + (colorFamilies: ANY("Red","Blue")) + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition = proto.Field( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + skip_boost_spec_validation = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.retail_v2alpha.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 3 + + condition = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.QueryExpansionSpec.Condition', + ) + pin_unexpanded_results = proto.Field( + proto.BOOL, + number=2, + ) + + class PersonalizationSpec(proto.Message): + r"""The specification for personalization. + + Attributes: + mode (google.cloud.retail_v2alpha.types.SearchRequest.PersonalizationSpec.Mode): + Defaults to + [Mode.AUTO][google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""The personalization mode of each search request.""" + MODE_UNSPECIFIED = 0 + AUTO = 1 + DISABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.PersonalizationSpec.Mode', + ) + + placement = proto.Field( + proto.STRING, + number=1, + ) + branch = proto.Field( + proto.STRING, + number=2, + ) + query = proto.Field( + proto.STRING, + number=3, + ) + visitor_id = proto.Field( + proto.STRING, + number=4, + ) + user_info = proto.Field( + proto.MESSAGE, + number=5, + message=common.UserInfo, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + offset = proto.Field( + proto.INT32, + number=9, + ) + filter = proto.Field( + proto.STRING, + number=10, + ) + canonical_filter = proto.Field( + proto.STRING, + number=28, + ) + order_by = proto.Field( + proto.STRING, + number=11, + ) + facet_specs = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=FacetSpec, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=21, + message=DynamicFacetSpec, + ) + boost_spec = proto.Field( + proto.MESSAGE, + number=13, + message=BoostSpec, + ) + query_expansion_spec = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionSpec, + ) + relevance_threshold = proto.Field( + proto.ENUM, + number=15, + enum=RelevanceThreshold, + ) + variant_rollup_keys = proto.RepeatedField( + proto.STRING, + number=17, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=23, + ) + search_mode = proto.Field( + proto.ENUM, + number=31, + enum=SearchMode, + ) + personalization_spec = proto.Field( + proto.MESSAGE, + number=32, + message=PersonalizationSpec, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + + Attributes: + results (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.SearchResult]): + A list of matched items. The order represents + the ranking. + facets (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.Facet]): + Results of facets requested by user. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.retail.v2alpha.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.retail.v2alpha.SearchResponse.total_size] + that matches. + corrected_query (str): + If spell correction applies, the corrected + query. Otherwise, empty. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs + resulting from this search, which enables accurate + attribution of search model performance. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.retail.v2alpha.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + query_expansion_info (google.cloud.retail_v2alpha.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search will be performed, and only + [redirect_uri][google.cloud.retail.v2alpha.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.retail.v2alpha.SearchResponse.attribution_token] + will be set in the response. + applied_controls (Sequence[str]): + The fully qualified resource name of applied + `controls `__. + invalid_condition_boost_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + The invalid + [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] + that are not applied during serving. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Product.id][google.cloud.retail.v2alpha.Product.id] of the + searched [Product][google.cloud.retail.v2alpha.Product]. + product (google.cloud.retail_v2alpha.types.Product): + The product data snippet in the search response. Only + [Product.name][google.cloud.retail.v2alpha.Product.name] is + guaranteed to be populated. + + [Product.variants][google.cloud.retail.v2alpha.Product.variants] + contains the product variants that match the search query. + If there are multiple product variants matching the query, + top 5 most relevant product variants are returned and + ordered by relevancy. + + If relevancy can be deternmined, use + [matching_variant_fields][google.cloud.retail.v2alpha.SearchResponse.SearchResult.matching_variant_fields] + to look up matched product variants fields. If relevancy + cannot be determined, e.g. when searching "shoe" all + products in a shoe product can be a match, 5 product + variants are returned but order is meaningless. + matching_variant_count (int): + The count of matched + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s. + matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): + If a + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] matches the + search query, this map indicates which + [Product][google.cloud.retail.v2alpha.Product] fields are + matched. The key is the + [Product.name][google.cloud.retail.v2alpha.Product.name], + the value is a field mask of the matched + [Product][google.cloud.retail.v2alpha.Product] fields. If + matched attributes cannot be determined, this map will be + empty. + + For example, a key "sku1" with field mask + "products.color_info" indicates there is a match between + "sku1" [ColorInfo][google.cloud.retail.v2alpha.ColorInfo] + and the query. + variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): + The rollup matching + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] attributes. + The key is one of the + [SearchRequest.variant_rollup_keys][google.cloud.retail.v2alpha.SearchRequest.variant_rollup_keys]. + The values are the merged and de-duplicated + [Product][google.cloud.retail.v2alpha.Product] attributes. + Notice that the rollup values are respect filter. For + example, when filtering by "colorFamilies:ANY("red")" and + rollup "colorFamilies", only "red" is returned. + + For textual and numerical attributes, the rollup values is a + list of string or double values with type + [google.protobuf.ListValue][google.protobuf.ListValue]. For + example, if there are two variants with colors "red" and + "blue", the rollup values are + + :: + + { key: "colorFamilies" + value { + list_value { + values { string_value: "red" } + values { string_value: "blue" } + } + } + } + + For + [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], + the rollup values is a double value with type + [google.protobuf.Value][google.protobuf.Value]. For example, + ``{key: "pickupInStore.store1" value { number_value: 10 }}`` + means a there are 10 variants in this product are available + in the store "store1". + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + matching_variant_count = proto.Field( + proto.INT32, + number=3, + ) + matching_variant_fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + variant_rollup_values = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. E.g., "colorFamilies" + or "price" or "attributes.attr1". + values (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Text value of a facet, such as "Black" for + facet "colorFamilies". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.retail_v2alpha.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value = proto.Field( + proto.STRING, + number=1, + oneof='facet_value', + ) + interval = proto.Field( + proto.MESSAGE, + number=2, + oneof='facet_value', + message=common.Interval, + ) + count = proto.Field( + proto.INT64, + number=3, + ) + + key = proto.Field( + proto.STRING, + number=1, + ) + values = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SearchResponse.Facet.FacetValue', + ) + dynamic_facet = proto.Field( + proto.BOOL, + number=3, + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count = proto.Field( + proto.INT64, + number=2, + ) + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + corrected_query = proto.Field( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + next_page_token = proto.Field( + proto.STRING, + number=6, + ) + query_expansion_info = proto.Field( + proto.MESSAGE, + number=7, + message=QueryExpansionInfo, + ) + redirect_uri = proto.Field( + proto.STRING, + number=10, + ) + applied_controls = proto.RepeatedField( + proto.STRING, + number=12, + ) + invalid_condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py new file mode 100644 index 00000000..c8c3ccca --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py @@ -0,0 +1,309 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'ServingConfig', + }, +) + + +class ServingConfig(proto.Message): + r"""Configures metadata that is used to generate serving time results + (e.g. search results or recommendation predictions). The + ServingConfig is passed in the search and predict request and + together with the Catalog.default_branch, generates results. + + Attributes: + name (str): + Immutable. Fully qualified name + projects/\ */locations/global/catalogs/*/servingConfig/\* + display_name (str): + Required. The human readable serving config display name. + Used in Retail UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + model_id (str): + The id of the model to use at serving time. Currently only + RecommendationModels are supported: + https://cloud.google.com/retail/recommendations-ai/docs/create-models + Can be changed but only to a compatible model (e.g. + others-you-may-like CTR to others-you-may-like CVR). + + Required when + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + price_reranking_level (str): + How much price ranking we want in serving results. Price + reranking causes product items with a similar recommendation + probability to be ordered by price, with the highest-priced + items first. This setting could result in a decrease in + click-through and conversion rates. Allowed values are: + + - 'no-price-reranking' + - 'low-price-raranking' + - 'medium-price-reranking' + - 'high-price-reranking' + + If not specified, we choose default based on model type. + Default value: 'no-price-reranking'. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + facet_control_ids (Sequence[str]): + Facet specifications for faceted search. If empty, no facets + are returned. The ids refer to the ids of + [Control][google.cloud.retail.v2alpha.Control] resources + with only the Facet control set. These controls are assumed + to be in the same + [Catalog][google.cloud.retail.v2alpha.Catalog] as the + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]. + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + dynamic_facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec): + The specification for dynamically generated facets. Notice + that only textual facets can be dynamically generated. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + boost_control_ids (Sequence[str]): + Condition boost specifications. If a product matches + multiple conditions in the specifications, boost scores from + these specifications are all applied and combined in a + non-linear way. Maximum number of specifications is 100. + + Notice that if both + [ServingConfig.boost_control_ids][google.cloud.retail.v2alpha.ServingConfig.boost_control_ids] + and [SearchRequest.boost_spec] are set, the boost conditions + from both places are evaluated. If a search request matches + multiple boost conditions, the final boost score is equal to + the sum of the boost scores from all matched boost + conditions. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + filter_control_ids (Sequence[str]): + Condition filter specifications. If a product matches + multiple conditions in the specifications, filters from + these specifications are all applied and combined via the + AND operator. Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + redirect_control_ids (Sequence[str]): + Condition redirect specifications. Only the first triggered + redirect action is applied, even if multiple apply. Maximum + number of specifications is 1000. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + twoway_synonyms_control_ids (Sequence[str]): + Condition synonyms specifications. If multiple syonyms + conditions match, all matching synonyms control in the list + will execute. Order of controls in the list will not matter. + Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + oneway_synonyms_control_ids (Sequence[str]): + Condition oneway synonyms specifications. If multiple oneway + synonyms conditions match, all matching oneway synonyms + controls in the list will execute. Order of controls in the + list will not matter. Maximum number of specifications is + 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + do_not_associate_control_ids (Sequence[str]): + Condition do not associate specifications. If multiple do + not associate conditions match, all matching do not + associate controls in the list will execute. + + - Order does not matter. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + replacement_control_ids (Sequence[str]): + Condition replacement specifications. + + - Applied according to the order in the list. + - A previously replaced term can not be re-replaced. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + ignore_control_ids (Sequence[str]): + Condition ignore specifications. If multiple ignore + conditions match, all matching ignore controls in the list + will execute. + + - Order does not matter. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + diversity_level (str): + How much diversity to use in recommendation model results + e.g. 'medium-diversity' or 'high-diversity'. Currently + supported values: + + - 'no-diversity' + - 'low-diversity' + - 'medium-diversity' + - 'high-diversity' + - 'auto-diversity' + + If not specified, we choose default based on recommendation + model type. Default value: 'no-diversity'. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + enable_category_filter_level (str): + Whether to add additional category filters on the + 'similar-items' model. If not specified, we enable it by + default. Allowed values are: + + - 'no-category-match': No additional filtering of original + results from the model and the customer's filters. + - 'relaxed-category-match': Only keep results with + categories that match at least one item categories in the + PredictRequests's context item. + + - If customer also sends filters in the PredictRequest, + then the results will satisfy both conditions (user + given and category match). + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + solution_types (Sequence[google.cloud.retail_v2alpha.types.SolutionType]): + Required. Immutable. Specifies the solution + types that a serving config can be associated + with. Currently we support setting only one type + of solution. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + model_id = proto.Field( + proto.STRING, + number=3, + ) + price_reranking_level = proto.Field( + proto.STRING, + number=4, + ) + facet_control_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=6, + message=search_service.SearchRequest.DynamicFacetSpec, + ) + boost_control_ids = proto.RepeatedField( + proto.STRING, + number=7, + ) + filter_control_ids = proto.RepeatedField( + proto.STRING, + number=9, + ) + redirect_control_ids = proto.RepeatedField( + proto.STRING, + number=10, + ) + twoway_synonyms_control_ids = proto.RepeatedField( + proto.STRING, + number=18, + ) + oneway_synonyms_control_ids = proto.RepeatedField( + proto.STRING, + number=12, + ) + do_not_associate_control_ids = proto.RepeatedField( + proto.STRING, + number=13, + ) + replacement_control_ids = proto.RepeatedField( + proto.STRING, + number=14, + ) + ignore_control_ids = proto.RepeatedField( + proto.STRING, + number=15, + ) + diversity_level = proto.Field( + proto.STRING, + number=8, + ) + enable_category_filter_level = proto.Field( + proto.STRING, + number=16, + ) + solution_types = proto.RepeatedField( + proto.ENUM, + number=19, + enum=common.SolutionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py new file mode 100644 index 00000000..635f42bb --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py @@ -0,0 +1,234 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'CreateServingConfigRequest', + 'UpdateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'AddControlRequest', + 'RemoveControlRequest', + }, +) + + +class CreateServingConfigRequest(proto.Message): + r"""Request for CreateServingConfig method. + + Attributes: + parent (str): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + serving_config (google.cloud.retail_v2alpha.types.ServingConfig): + Required. The ServingConfig to create. + serving_config_id (str): + Required. The ID to use for the ServingConfig, which will + become the final component of the ServingConfig's resource + name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-_/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + serving_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_serving_config.ServingConfig, + ) + serving_config_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateServingConfigRequest(proto.Message): + r"""Request for UpdateServingConfig method. + + Attributes: + serving_config (google.cloud.retail_v2alpha.types.ServingConfig): + Required. The ServingConfig to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] + + If not set, all supported fields are updated. + """ + + serving_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_serving_config.ServingConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteServingConfigRequest(proto.Message): + r"""Request for DeleteServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetServingConfigRequest(proto.Message): + r"""Request for GetServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListServingConfigsRequest(proto.Message): + r"""Request for ListServingConfigs method. + + Attributes: + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 100. If a + value greater than 100 is provided, at most 100 + results are returned. + page_token (str): + Optional. A page token, received from a previous + ``ListServingConfigs`` call. Provide this to retrieve the + subsequent page. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServingConfigsResponse(proto.Message): + r"""Response for ListServingConfigs method. + + Attributes: + serving_configs (Sequence[google.cloud.retail_v2alpha.types.ServingConfig]): + All the ServingConfigs for a given catalog. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + serving_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_serving_config.ServingConfig, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class AddControlRequest(proto.Message): + r"""Request for AddControl method. + + Attributes: + serving_config (str): + Required. The source ServingConfig resource name . Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + control_id (str): + Required. The id of the control to apply. Assumed to be in + the same catalog as the serving config - if id is not found + a NOT_FOUND error is returned. + """ + + serving_config = proto.Field( + proto.STRING, + number=1, + ) + control_id = proto.Field( + proto.STRING, + number=2, + ) + + +class RemoveControlRequest(proto.Message): + r"""Request for RemoveControl method. + + Attributes: + serving_config (str): + Required. The source ServingConfig resource name . Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + control_id (str): + Required. The id of the control to apply. + Assumed to be in the same catalog as the serving + config. + """ + + serving_config = proto.Field( + proto.STRING, + number=1, + ) + control_id = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py new file mode 100644 index 00000000..f9d6a684 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py @@ -0,0 +1,507 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'UserEvent', + 'ProductDetail', + 'CompletionDetail', + 'PurchaseTransaction', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Retail API needs + to know about how end users interact with customers' website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + - ``add-to-cart``: Products being added to cart. + - ``category-page-view``: Special pages such as sale or + promotion pages viewed. + - ``detail-page-view``: Products detail page viewed. + - ``home-page-view``: Homepage viewed. + - ``promotion-offered``: Promotion is offered to a user. + - ``promotion-not-offered``: Promotion is not offered to a + user. + - ``purchase-complete``: User finishing a purchase. + - ``search``: Product search. + - ``shopping-cart-page-view``: User viewing a shopping + cart. + visitor_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + The field should not contain PII or user-data. We recommend + to use Google Analystics `Client + ID `__ + for this field. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the sesion_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add visitor_id as prefix. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.retail.v2alpha.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + experiment_ids (Sequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups + (e.g. using Retail API, using different + recommendation models). + attribution_token (str): + Highly recommended for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2alpha.PredictionService.Predict]. + This field enables accurate attribution of recommendation + model performance. + + The value must be a valid + [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] + for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2alpha.PredictionService.Predict]. + The value must be a valid + [SearchResponse.attribution_token][google.cloud.retail.v2alpha.SearchResponse.attribution_token] + for user events that are the result of + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + This token enables us to accurately attribute page view or + purchase back to the event and the particular predict + response containing this clicked/purchased product. If user + clicks on product K in the recommendation results, pass + [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] + as a URL parameter to product K's page. When recording + events on product K's page, log the + [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] + to this field. + product_details (Sequence[google.cloud.retail_v2alpha.types.ProductDetail]): + The main product details related to the event. + + This field is required for the following event types: + + - ``add-to-cart`` + - ``detail-page-view`` + - ``purchase-complete`` + - ``search`` + + In a ``search`` event, this field represents the products + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [product_details][google.cloud.retail.v2alpha.UserEvent.product_details] + is desired. The end user may have not finished browsing the + whole page yet. + completion_detail (google.cloud.retail_v2alpha.types.CompletionDetail): + The main auto-completion details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Retail API use those + custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - The key must be a UTF-8 encoded string with a length + limit of 5,000 characters. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a UTF-8 + encoded string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is traffic_channel, which is how a user arrives + at the site. Users can arrive at the site by coming to the + site directly, coming through Google search, or in other + ways. + cart_id (str): + The ID or name of the associated shopping cart. This ID is + used to associate multiple items added or present in the + cart before purchase. + + This can only be set for ``add-to-cart``, + ``purchase-complete``, or ``shopping-cart-page-view`` + events. + purchase_transaction (google.cloud.retail_v2alpha.types.PurchaseTransaction): + A transaction represents the entire purchase transaction. + + Required for ``purchase-complete`` events. Other event types + should not set this field. Otherwise, an INVALID_ARGUMENT + error is returned. + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.retail.v2alpha.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + At least one of + [search_query][google.cloud.retail.v2alpha.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. + + See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + order_by (str): + The order in which products are returned. + + See + [SearchRequest.order_by][google.cloud.retail.v2alpha.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.retail.v2alpha.SearchRequest.offset] + for definition. + + If this field is negative, an INVALID_ARGUMENT is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + + Required for ``category-page-view`` events. At least one of + [search_query][google.cloud.retail.v2alpha.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2alpha.types.UserInfo): + User information. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. + page_view_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageViewId`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + """ + + event_type = proto.Field( + proto.STRING, + number=1, + ) + visitor_id = proto.Field( + proto.STRING, + number=2, + ) + session_id = proto.Field( + proto.STRING, + number=21, + ) + event_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + experiment_ids = proto.RepeatedField( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + product_details = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ProductDetail', + ) + completion_detail = proto.Field( + proto.MESSAGE, + number=22, + message='CompletionDetail', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=common.CustomAttribute, + ) + cart_id = proto.Field( + proto.STRING, + number=8, + ) + purchase_transaction = proto.Field( + proto.MESSAGE, + number=9, + message='PurchaseTransaction', + ) + search_query = proto.Field( + proto.STRING, + number=10, + ) + filter = proto.Field( + proto.STRING, + number=16, + ) + order_by = proto.Field( + proto.STRING, + number=17, + ) + offset = proto.Field( + proto.INT32, + number=18, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=11, + ) + user_info = proto.Field( + proto.MESSAGE, + number=12, + message=common.UserInfo, + ) + uri = proto.Field( + proto.STRING, + number=13, + ) + referrer_uri = proto.Field( + proto.STRING, + number=14, + ) + page_view_id = proto.Field( + proto.STRING, + number=15, + ) + + +class ProductDetail(proto.Message): + r"""Detailed product information associated with a user event. + + Attributes: + product (google.cloud.retail_v2alpha.types.Product): + Required. [Product][google.cloud.retail.v2alpha.Product] + information. + + Required field(s): + + - [Product.id][google.cloud.retail.v2alpha.Product.id] + + Optional override field(s): + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + + If any supported optional fields are provided, we will treat + them as a full override when looking up product information + from the catalog. Thus, it is important to ensure that the + overriding fields are accurate and complete. + + All other product fields are ignored and instead populated + via catalog lookup after event ingestion. + quantity (google.protobuf.wrappers_pb2.Int32Value): + Quantity of the product associated with the user event. + + For example, this field will be 2 if two products are added + to the shopping cart for ``purchase-complete`` event. + Required for ``add-to-cart`` and ``purchase-complete`` event + types. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + quantity = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +class CompletionDetail(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + completion_attribution_token (str): + Completion attribution token in + [CompleteQueryResponse.attribution_token][google.cloud.retail.v2alpha.CompleteQueryResponse.attribution_token]. + selected_suggestion (str): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2alpha.CompleteQueryResponse.CompletionResult.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2alpha.CompleteQueryResponse.CompletionResult.suggestion] + position, starting from 0. + """ + + completion_attribution_token = proto.Field( + proto.STRING, + number=1, + ) + selected_suggestion = proto.Field( + proto.STRING, + number=2, + ) + selected_position = proto.Field( + proto.INT32, + number=3, + ) + + +class PurchaseTransaction(proto.Message): + r"""A transaction represents the entire purchase transaction. + + Attributes: + id (str): + The transaction ID with a length limit of 128 + characters. + revenue (float): + Required. Total non-zero revenue or grand + total associated with the transaction. This + value include shipping, tax, or other + adjustments to total revenue that you want to + include as part of your revenue calculations. + tax (float): + All the taxes associated with the + transaction. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [revenue][google.cloud.retail.v2alpha.PurchaseTransaction.revenue] + - + [tax][google.cloud.retail.v2alpha.PurchaseTransaction.tax] + - + [cost][google.cloud.retail.v2alpha.PurchaseTransaction.cost] + currency_code (str): + Required. Currency code. Use three-character + ISO-4217 code. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + revenue = proto.Field( + proto.FLOAT, + number=2, + ) + tax = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + currency_code = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py new file mode 100644 index 00000000..0e679b22 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import user_event as gcr_user_event + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'WriteUserEventRequest', + 'CollectUserEventRequest', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'RejoinUserEventsMetadata', + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (google.cloud.retail_v2alpha.types.UserEvent): + Required. User event to write. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for 3rd party requests. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.STRING, + number=2, + ) + uri = proto.Field( + proto.STRING, + number=3, + ) + ets = proto.Field( + proto.INT64, + number=4, + ) + + +class RejoinUserEventsRequest(proto.Message): + r"""Request message for RejoinUserEvents method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event_rejoin_scope (google.cloud.retail_v2alpha.types.RejoinUserEventsRequest.UserEventRejoinScope): + The type of the user event rejoin to define the scope and + range of the user events to be rejoined with the latest + product catalog. Defaults to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not + set, or set to an invalid integer value. + """ + class UserEventRejoinScope(proto.Enum): + r"""The scope of user events to be rejoined with the latest product + catalog. If the rejoining aims at reducing number of unjoined + events, set UserEventRejoinScope to UNJOINED_EVENTS. If the + rejoining aims at correcting product catalog information in joined + events, set UserEventRejoinScope to JOINED_EVENTS. If all events + needs to be rejoined, set UserEventRejoinScope to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. + """ + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 + JOINED_EVENTS = 1 + UNJOINED_EVENTS = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event_rejoin_scope = proto.Field( + proto.ENUM, + number=2, + enum=UserEventRejoinScope, + ) + + +class RejoinUserEventsResponse(proto.Message): + r"""Response message for RejoinUserEvents method. + + Attributes: + rejoined_user_events_count (int): + Number of user events that were joined with + latest product catalog. + """ + + rejoined_user_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +class RejoinUserEventsMetadata(proto.Message): + r"""Metadata for RejoinUserEvents method. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/mypy.ini b/owl-bot-staging/v2alpha/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v2alpha/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2alpha/noxfile.py b/owl-bot-staging/v2alpha/noxfile.py new file mode 100644 index 00000000..9f7eeaa1 --- /dev/null +++ b/owl-bot-staging/v2alpha/noxfile.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.6", + "3.7", + "3.8", + "3.9", + "3.10", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==19.10b0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.9" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/retail_v2alpha/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py new file mode 100644 index 00000000..9b5622c2 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async] +from google.cloud import retail_v2alpha + + +async def sample_add_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py new file mode 100644 index 00000000..ec76bc9f --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync] +from google.cloud import retail_v2alpha + + +def sample_add_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py new file mode 100644 index 00000000..d2f66638 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetAttributesConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_get_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetAttributesConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py new file mode 100644 index 00000000..91c914b3 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_get_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py new file mode 100644 index 00000000..9da8e840 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetCompletionConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_get_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetCompletionConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py new file mode 100644 index 00000000..5da5cd9f --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_get_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py new file mode 100644 index 00000000..2134a810 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetDefaultBranch_async] +from google.cloud import retail_v2alpha + + +async def sample_get_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py new file mode 100644 index 00000000..d233b424 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync] +from google.cloud import retail_v2alpha + + +def sample_get_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py new file mode 100644 index 00000000..7e7fbf33 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_ListCatalogs_async] +from google.cloud import retail_v2alpha + + +async def sample_list_catalogs(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py new file mode 100644 index 00000000..8165c25b --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_ListCatalogs_sync] +from google.cloud import retail_v2alpha + + +def sample_list_catalogs(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py new file mode 100644 index 00000000..f79bd768 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async] +from google.cloud import retail_v2alpha + + +async def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = await client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py new file mode 100644 index 00000000..35b6611c --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync] +from google.cloud import retail_v2alpha + + +def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py new file mode 100644 index 00000000..c42a8bb1 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReplaceCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async] +from google.cloud import retail_v2alpha + + +async def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py new file mode 100644 index 00000000..56e779ab --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReplaceCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync] +from google.cloud import retail_v2alpha + + +def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py new file mode 100644 index 00000000..9ddf2f8e --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_SetDefaultBranch_async] +from google.cloud import retail_v2alpha + + +async def sample_set_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + +# [END retail_v2alpha_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py new file mode 100644 index 00000000..6fa13ce6 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync] +from google.cloud import retail_v2alpha + + +def sample_set_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + +# [END retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py new file mode 100644 index 00000000..c4654be4 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_update_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + attributes_config = retail_v2alpha.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2alpha.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = await client.update_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py new file mode 100644 index 00000000..1f4d3432 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_update_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + attributes_config = retail_v2alpha.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2alpha.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = client.update_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py new file mode 100644 index 00000000..6035f718 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateCatalog_async] +from google.cloud import retail_v2alpha + + +async def sample_update_catalog(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2alpha.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2alpha.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py new file mode 100644 index 00000000..35fff0d1 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateCatalog_sync] +from google.cloud import retail_v2alpha + + +def sample_update_catalog(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2alpha.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2alpha.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py new file mode 100644 index 00000000..26cac134 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_update_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + completion_config = retail_v2alpha.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2alpha.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = await client.update_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py new file mode 100644 index 00000000..b9e11448 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_update_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + completion_config = retail_v2alpha.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2alpha.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = client.update_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py new file mode 100644 index 00000000..13dce99f --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CompletionService_CompleteQuery_async] +from google.cloud import retail_v2alpha + + +async def sample_complete_query(): + # Create a client + client = retail_v2alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py new file mode 100644 index 00000000..20687e33 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CompletionService_CompleteQuery_sync] +from google.cloud import retail_v2alpha + + +def sample_complete_query(): + # Create a client + client = retail_v2alpha.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py new file mode 100644 index 00000000..d1a515f2 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CompletionService_ImportCompletionData_async] +from google.cloud import retail_v2alpha + + +async def sample_import_completion_data(): + # Create a client + client = retail_v2alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2alpha.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py new file mode 100644 index 00000000..3c6ddc55 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CompletionService_ImportCompletionData_sync] +from google.cloud import retail_v2alpha + + +def sample_import_completion_data(): + # Create a client + client = retail_v2alpha.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2alpha.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py new file mode 100644 index 00000000..131de87e --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_CreateControl_async] +from google.cloud import retail_v2alpha + + +async def sample_create_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = await client.create_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_CreateControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py new file mode 100644 index 00000000..8fee66d8 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_CreateControl_sync] +from google.cloud import retail_v2alpha + + +def sample_create_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = client.create_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_CreateControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py new file mode 100644 index 00000000..ae438a78 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_DeleteControl_async] +from google.cloud import retail_v2alpha + + +async def sample_delete_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteControlRequest( + name="name_value", + ) + + # Make the request + await client.delete_control(request=request) + + +# [END retail_v2alpha_generated_ControlService_DeleteControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py new file mode 100644 index 00000000..b83ddcd5 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_DeleteControl_sync] +from google.cloud import retail_v2alpha + + +def sample_delete_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteControlRequest( + name="name_value", + ) + + # Make the request + client.delete_control(request=request) + + +# [END retail_v2alpha_generated_ControlService_DeleteControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py new file mode 100644 index 00000000..588c8955 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_GetControl_async] +from google.cloud import retail_v2alpha + + +async def sample_get_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetControlRequest( + name="name_value", + ) + + # Make the request + response = await client.get_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_GetControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py new file mode 100644 index 00000000..f04eb36b --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_GetControl_sync] +from google.cloud import retail_v2alpha + + +def sample_get_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetControlRequest( + name="name_value", + ) + + # Make the request + response = client.get_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_GetControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py new file mode 100644 index 00000000..005329c1 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListControls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_ListControls_async] +from google.cloud import retail_v2alpha + + +async def sample_list_controls(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ControlService_ListControls_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py new file mode 100644 index 00000000..301c6036 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListControls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_ListControls_sync] +from google.cloud import retail_v2alpha + + +def sample_list_controls(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ControlService_ListControls_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py new file mode 100644 index 00000000..dc422066 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_UpdateControl_async] +from google.cloud import retail_v2alpha + + +async def sample_update_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.UpdateControlRequest( + control=control, + ) + + # Make the request + response = await client.update_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_UpdateControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py new file mode 100644 index 00000000..cf7823fd --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_UpdateControl_sync] +from google.cloud import retail_v2alpha + + +def sample_update_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.UpdateControlRequest( + control=control, + ) + + # Make the request + response = client.update_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_UpdateControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py new file mode 100644 index 00000000..7d3c4540 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_PredictionService_Predict_async] +from google.cloud import retail_v2alpha + + +async def sample_predict(): + # Create a client + client = retail_v2alpha.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py new file mode 100644 index 00000000..c3dbd187 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_PredictionService_Predict_sync] +from google.cloud import retail_v2alpha + + +def sample_predict(): + # Create a client + client = retail_v2alpha.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py new file mode 100644 index 00000000..4ef15987 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async] +from google.cloud import retail_v2alpha + + +async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py new file mode 100644 index 00000000..03f0cd6d --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync] +from google.cloud import retail_v2alpha + + +def sample_add_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py new file mode 100644 index 00000000..c3b7dfdf --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_AddLocalInventories_async] +from google.cloud import retail_v2alpha + + +async def sample_add_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py new file mode 100644 index 00000000..b91b57f3 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_AddLocalInventories_sync] +from google.cloud import retail_v2alpha + + +def sample_add_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py new file mode 100644 index 00000000..8ca45663 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_CreateProduct_async] +from google.cloud import retail_v2alpha + + +async def sample_create_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py new file mode 100644 index 00000000..b2946508 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_CreateProduct_sync] +from google.cloud import retail_v2alpha + + +def sample_create_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py new file mode 100644 index 00000000..1ae74222 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_DeleteProduct_async] +from google.cloud import retail_v2alpha + + +async def sample_delete_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + +# [END retail_v2alpha_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py new file mode 100644 index 00000000..faebc2e4 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_DeleteProduct_sync] +from google.cloud import retail_v2alpha + + +def sample_delete_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + +# [END retail_v2alpha_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py new file mode 100644 index 00000000..70903b9e --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_GetProduct_async] +from google.cloud import retail_v2alpha + + +async def sample_get_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py new file mode 100644 index 00000000..25fccda2 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_GetProduct_sync] +from google.cloud import retail_v2alpha + + +def sample_get_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py new file mode 100644 index 00000000..5cfaf031 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_ImportProducts_async] +from google.cloud import retail_v2alpha + + +async def sample_import_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2alpha.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py new file mode 100644 index 00000000..ca54ea57 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_ImportProducts_sync] +from google.cloud import retail_v2alpha + + +def sample_import_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2alpha.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py new file mode 100644 index 00000000..8dcf7a71 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_ListProducts_async] +from google.cloud import retail_v2alpha + + +async def sample_list_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py new file mode 100644 index 00000000..aa96e9c2 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_ListProducts_sync] +from google.cloud import retail_v2alpha + + +def sample_list_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py new file mode 100644 index 00000000..8adf6af4 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_PurgeProducts_async] +from google.cloud import retail_v2alpha + + +async def sample_purge_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeProductsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_PurgeProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py new file mode 100644 index 00000000..72c32c88 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_PurgeProducts_sync] +from google.cloud import retail_v2alpha + + +def sample_purge_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeProductsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_PurgeProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py new file mode 100644 index 00000000..da379da0 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async] +from google.cloud import retail_v2alpha + + +async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py new file mode 100644 index 00000000..55bf6522 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync] +from google.cloud import retail_v2alpha + + +def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py new file mode 100644 index 00000000..bc0b9406 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_RemoveLocalInventories_async] +from google.cloud import retail_v2alpha + + +async def sample_remove_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py new file mode 100644 index 00000000..40e0b2bb --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync] +from google.cloud import retail_v2alpha + + +def sample_remove_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py new file mode 100644 index 00000000..64dc769c --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_SetInventory_async] +from google.cloud import retail_v2alpha + + +async def sample_set_inventory(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2alpha.Product() + inventory.title = "title_value" + + request = retail_v2alpha.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py new file mode 100644 index 00000000..9dbf88b6 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_SetInventory_sync] +from google.cloud import retail_v2alpha + + +def sample_set_inventory(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2alpha.Product() + inventory.title = "title_value" + + request = retail_v2alpha.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py new file mode 100644 index 00000000..35df5c2b --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_UpdateProduct_async] +from google.cloud import retail_v2alpha + + +async def sample_update_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py new file mode 100644 index 00000000..6248e977 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_UpdateProduct_sync] +from google.cloud import retail_v2alpha + + +def sample_update_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py new file mode 100644 index 00000000..75520b76 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_SearchService_Search_async] +from google.cloud import retail_v2alpha + + +async def sample_search(): + # Create a client + client = retail_v2alpha.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py new file mode 100644 index 00000000..2b2853a3 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_SearchService_Search_sync] +from google.cloud import retail_v2alpha + + +def sample_search(): + # Create a client + client = retail_v2alpha.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py new file mode 100644 index 00000000..0694590c --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_AddControl_async] +from google.cloud import retail_v2alpha + + +async def sample_add_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.add_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_AddControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py new file mode 100644 index 00000000..10d50ff7 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_AddControl_sync] +from google.cloud import retail_v2alpha + + +def sample_add_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.add_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_AddControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py new file mode 100644 index 00000000..33b080fc --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_create_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = await client.create_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py new file mode 100644 index 00000000..e7b0e80e --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_create_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = client.create_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py new file mode 100644 index 00000000..f8259bdf --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_delete_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_serving_config(request=request) + + +# [END retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py new file mode 100644 index 00000000..621916ef --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_delete_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_serving_config(request=request) + + +# [END retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py new file mode 100644 index 00000000..fdfd4d80 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_GetServingConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_get_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_GetServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py new file mode 100644 index 00000000..a1408016 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_get_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py new file mode 100644 index 00000000..c8244f95 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServingConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async] +from google.cloud import retail_v2alpha + + +async def sample_list_serving_configs(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py new file mode 100644 index 00000000..86e02687 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServingConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync] +from google.cloud import retail_v2alpha + + +def sample_list_serving_configs(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py new file mode 100644 index 00000000..66e07902 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_RemoveControl_async] +from google.cloud import retail_v2alpha + + +async def sample_remove_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.remove_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_RemoveControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py new file mode 100644 index 00000000..8b39362b --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_RemoveControl_sync] +from google.cloud import retail_v2alpha + + +def sample_remove_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.remove_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_RemoveControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py new file mode 100644 index 00000000..64e82dba --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_update_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = await client.update_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py new file mode 100644 index 00000000..46d2d65c --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_update_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = client.update_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 00000000..f8aa3f78 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_CollectUserEvent_async] +from google.cloud import retail_v2alpha + + +async def sample_collect_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 00000000..026972b1 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_CollectUserEvent_sync] +from google.cloud import retail_v2alpha + + +def sample_collect_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py new file mode 100644 index 00000000..540ce130 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_ImportUserEvents_async] +from google.cloud import retail_v2alpha + + +async def sample_import_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2alpha.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 00000000..fe9310db --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_ImportUserEvents_sync] +from google.cloud import retail_v2alpha + + +def sample_import_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2alpha.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py new file mode 100644 index 00000000..17d5c66d --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_PurgeUserEvents_async] +from google.cloud import retail_v2alpha + + +async def sample_purge_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py new file mode 100644 index 00000000..d8b2ae83 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync] +from google.cloud import retail_v2alpha + + +def sample_purge_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py new file mode 100644 index 00000000..d38bb5f4 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_RejoinUserEvents_async] +from google.cloud import retail_v2alpha + + +async def sample_rejoin_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py new file mode 100644 index 00000000..f88f6437 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync] +from google.cloud import retail_v2alpha + + +def sample_rejoin_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py new file mode 100644 index 00000000..2dda0e65 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_WriteUserEvent_async] +from google.cloud import retail_v2alpha + + +async def sample_write_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 00000000..a121bdbd --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_WriteUserEvent_sync] +from google.cloud import retail_v2alpha + + +def sample_write_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json b/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json new file mode 100644 index 00000000..ea2cf419 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json @@ -0,0 +1,7066 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.retail.v2alpha", + "version": "v2alpha" + } + ], + "language": "PYTHON", + "name": "google-cloud-retail" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.add_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "AddCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "add_catalog_attribute" + }, + "description": "Sample for AddCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.add_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "AddCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "add_catalog_attribute" + }, + "description": "Sample for AddCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetAttributesConfigRequest" + }, + { + "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.retail_v2alpha.types.AttributesConfig", + "shortName": "get_attributes_config" + }, + "description": "Sample for GetAttributesConfig", + "file": "retail_v2alpha_generated_catalog_service_get_attributes_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetAttributesConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_attributes_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetAttributesConfigRequest" + }, + { + "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.retail_v2alpha.types.AttributesConfig", + "shortName": "get_attributes_config" + }, + "description": "Sample for GetAttributesConfig", + "file": "retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_completion_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetCompletionConfigRequest" + }, + { + "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.retail_v2alpha.types.CompletionConfig", + "shortName": "get_completion_config" + }, + "description": "Sample for GetCompletionConfig", + "file": "retail_v2alpha_generated_catalog_service_get_completion_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetCompletionConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_completion_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_completion_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetCompletionConfigRequest" + }, + { + "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.retail_v2alpha.types.CompletionConfig", + "shortName": "get_completion_config" + }, + "description": "Sample for GetCompletionConfig", + "file": "retail_v2alpha_generated_catalog_service_get_completion_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_completion_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2alpha_generated_catalog_service_get_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetDefaultBranch_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2alpha_generated_catalog_service_get_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListCatalogsRequest" + }, + { + "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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsAsyncPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2alpha_generated_catalog_service_list_catalogs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_ListCatalogs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_list_catalogs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListCatalogsRequest" + }, + { + "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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2alpha_generated_catalog_service_list_catalogs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_ListCatalogs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_list_catalogs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.remove_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "RemoveCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "remove_catalog_attribute" + }, + "description": "Sample for RemoveCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.remove_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "RemoveCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "remove_catalog_attribute" + }, + "description": "Sample for RemoveCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.replace_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ReplaceCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "replace_catalog_attribute" + }, + "description": "Sample for ReplaceCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.replace_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ReplaceCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "replace_catalog_attribute" + }, + "description": "Sample for ReplaceCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2alpha_generated_catalog_service_set_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_SetDefaultBranch_async", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_set_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2alpha_generated_catalog_service_set_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_set_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest" + }, + { + "name": "attributes_config", + "type": "google.cloud.retail_v2alpha.types.AttributesConfig" + }, + { + "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.retail_v2alpha.types.AttributesConfig", + "shortName": "update_attributes_config" + }, + "description": "Sample for UpdateAttributesConfig", + "file": "retail_v2alpha_generated_catalog_service_update_attributes_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_attributes_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest" + }, + { + "name": "attributes_config", + "type": "google.cloud.retail_v2alpha.types.AttributesConfig" + }, + { + "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.retail_v2alpha.types.AttributesConfig", + "shortName": "update_attributes_config" + }, + "description": "Sample for UpdateAttributesConfig", + "file": "retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2alpha.types.Catalog" + }, + { + "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.retail_v2alpha.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2alpha_generated_catalog_service_update_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCatalog_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2alpha.types.Catalog" + }, + { + "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.retail_v2alpha.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2alpha_generated_catalog_service_update_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCatalog_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_completion_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest" + }, + { + "name": "completion_config", + "type": "google.cloud.retail_v2alpha.types.CompletionConfig" + }, + { + "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.retail_v2alpha.types.CompletionConfig", + "shortName": "update_completion_config" + }, + "description": "Sample for UpdateCompletionConfig", + "file": "retail_v2alpha_generated_catalog_service_update_completion_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_completion_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_completion_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest" + }, + { + "name": "completion_config", + "type": "google.cloud.retail_v2alpha.types.CompletionConfig" + }, + { + "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.retail_v2alpha.types.CompletionConfig", + "shortName": "update_completion_config" + }, + "description": "Sample for UpdateCompletionConfig", + "file": "retail_v2alpha_generated_catalog_service_update_completion_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_completion_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2alpha.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2alpha_generated_completion_service_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CompletionService_CompleteQuery_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_completion_service_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2alpha.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2alpha_generated_completion_service_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CompletionService_CompleteQuery_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_completion_service_complete_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2alpha.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2alpha_generated_completion_service_import_completion_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CompletionService_ImportCompletionData_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_completion_service_import_completion_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2alpha.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2alpha_generated_completion_service_import_completion_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CompletionService_ImportCompletionData_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_completion_service_import_completion_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.create_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.CreateControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "CreateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateControlRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "control", + "type": "google.cloud.retail_v2alpha.types.Control" + }, + { + "name": "control_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.retail_v2alpha.types.Control", + "shortName": "create_control" + }, + "description": "Sample for CreateControl", + "file": "retail_v2alpha_generated_control_service_create_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_CreateControl_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_create_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.create_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.CreateControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "CreateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateControlRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "control", + "type": "google.cloud.retail_v2alpha.types.Control" + }, + { + "name": "control_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.retail_v2alpha.types.Control", + "shortName": "create_control" + }, + "description": "Sample for CreateControl", + "file": "retail_v2alpha_generated_control_service_create_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_CreateControl_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_create_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.delete_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.DeleteControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "DeleteControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteControlRequest" + }, + { + "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_control" + }, + "description": "Sample for DeleteControl", + "file": "retail_v2alpha_generated_control_service_delete_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_DeleteControl_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_delete_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.delete_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.DeleteControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "DeleteControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteControlRequest" + }, + { + "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_control" + }, + "description": "Sample for DeleteControl", + "file": "retail_v2alpha_generated_control_service_delete_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_DeleteControl_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_delete_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.get_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.GetControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "GetControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetControlRequest" + }, + { + "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.retail_v2alpha.types.Control", + "shortName": "get_control" + }, + "description": "Sample for GetControl", + "file": "retail_v2alpha_generated_control_service_get_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_GetControl_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_get_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.get_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.GetControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "GetControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetControlRequest" + }, + { + "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.retail_v2alpha.types.Control", + "shortName": "get_control" + }, + "description": "Sample for GetControl", + "file": "retail_v2alpha_generated_control_service_get_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_GetControl_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_get_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.list_controls", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.ListControls", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListControlsRequest" + }, + { + "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.retail_v2alpha.services.control_service.pagers.ListControlsAsyncPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "retail_v2alpha_generated_control_service_list_controls_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_ListControls_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_list_controls_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.list_controls", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.ListControls", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListControlsRequest" + }, + { + "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.retail_v2alpha.services.control_service.pagers.ListControlsPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "retail_v2alpha_generated_control_service_list_controls_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_ListControls_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_list_controls_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.update_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.UpdateControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "UpdateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateControlRequest" + }, + { + "name": "control", + "type": "google.cloud.retail_v2alpha.types.Control" + }, + { + "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.retail_v2alpha.types.Control", + "shortName": "update_control" + }, + "description": "Sample for UpdateControl", + "file": "retail_v2alpha_generated_control_service_update_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_UpdateControl_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_update_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.update_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.UpdateControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "UpdateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateControlRequest" + }, + { + "name": "control", + "type": "google.cloud.retail_v2alpha.types.Control" + }, + { + "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.retail_v2alpha.types.Control", + "shortName": "update_control" + }, + "description": "Sample for UpdateControl", + "file": "retail_v2alpha_generated_control_service_update_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_UpdateControl_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_update_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.PredictionServiceAsyncClient", + "shortName": "PredictionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.PredictionServiceAsyncClient.predict", + "method": { + "fullName": "google.cloud.retail.v2alpha.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2alpha.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2alpha_generated_prediction_service_predict_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_PredictionService_Predict_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_prediction_service_predict_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.PredictionServiceClient", + "shortName": "PredictionServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.PredictionServiceClient.predict", + "method": { + "fullName": "google.cloud.retail.v2alpha.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2alpha.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2alpha_generated_prediction_service_predict_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_PredictionService_Predict_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_prediction_service_predict_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2alpha_generated_product_service_add_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_add_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2alpha_generated_product_service_add_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_AddLocalInventories_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_add_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2alpha_generated_product_service_add_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_AddLocalInventories_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_add_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "name": "product_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.retail_v2alpha.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2alpha_generated_product_service_create_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_CreateProduct_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_create_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "name": "product_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.retail_v2alpha.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2alpha_generated_product_service_create_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_CreateProduct_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_create_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2alpha_generated_product_service_delete_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_DeleteProduct_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_delete_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2alpha_generated_product_service_delete_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_DeleteProduct_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_delete_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetProductRequest" + }, + { + "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.retail_v2alpha.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2alpha_generated_product_service_get_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_GetProduct_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_get_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetProductRequest" + }, + { + "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.retail_v2alpha.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2alpha_generated_product_service_get_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_GetProduct_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_get_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2alpha_generated_product_service_import_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_ImportProducts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_import_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2alpha_generated_product_service_import_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_ImportProducts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_import_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListProductsRequest" + }, + { + "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.retail_v2alpha.services.product_service.pagers.ListProductsAsyncPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2alpha_generated_product_service_list_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_ListProducts_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_list_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListProductsRequest" + }, + { + "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.retail_v2alpha.services.product_service.pagers.ListProductsPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2alpha_generated_product_service_list_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_ListProducts_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_list_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.purge_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.PurgeProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "PurgeProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PurgeProductsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_products" + }, + "description": "Sample for PurgeProducts", + "file": "retail_v2alpha_generated_product_service_purge_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_PurgeProducts_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_purge_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.purge_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.PurgeProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "PurgeProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PurgeProductsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_products" + }, + "description": "Sample for PurgeProducts", + "file": "retail_v2alpha_generated_product_service_purge_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_PurgeProducts_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_purge_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2alpha_generated_product_service_remove_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_RemoveLocalInventories_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_remove_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2alpha_generated_product_service_remove_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_remove_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2alpha_generated_product_service_set_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_SetInventory_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_set_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2alpha_generated_product_service_set_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_SetInventory_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_set_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "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.retail_v2alpha.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2alpha_generated_product_service_update_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_UpdateProduct_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_update_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "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.retail_v2alpha.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2alpha_generated_product_service_update_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_UpdateProduct_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_update_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.SearchServiceAsyncClient.search", + "method": { + "fullName": "google.cloud.retail.v2alpha.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2alpha.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2alpha_generated_search_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_SearchService_Search_async", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_search_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.SearchServiceClient", + "shortName": "SearchServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.SearchServiceClient.search", + "method": { + "fullName": "google.cloud.retail.v2alpha.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2alpha.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.services.search_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2alpha_generated_search_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_SearchService_Search_sync", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_search_service_search_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.add_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.AddControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "AddControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "add_control" + }, + "description": "Sample for AddControl", + "file": "retail_v2alpha_generated_serving_config_service_add_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_AddControl_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_add_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.add_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.AddControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "AddControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "add_control" + }, + "description": "Sample for AddControl", + "file": "retail_v2alpha_generated_serving_config_service_add_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_AddControl_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_add_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.create_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.CreateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "CreateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateServingConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2alpha.types.ServingConfig" + }, + { + "name": "serving_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "create_serving_config" + }, + "description": "Sample for CreateServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_create_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_create_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.create_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.CreateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "CreateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateServingConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2alpha.types.ServingConfig" + }, + { + "name": "serving_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "create_serving_config" + }, + "description": "Sample for CreateServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.delete_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.DeleteServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "DeleteServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteServingConfigRequest" + }, + { + "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_serving_config" + }, + "description": "Sample for DeleteServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.delete_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.DeleteServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "DeleteServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteServingConfigRequest" + }, + { + "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_serving_config" + }, + "description": "Sample for DeleteServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.get_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.GetServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "GetServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetServingConfigRequest" + }, + { + "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.retail_v2alpha.types.ServingConfig", + "shortName": "get_serving_config" + }, + "description": "Sample for GetServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_get_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_GetServingConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_get_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.get_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.GetServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "GetServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetServingConfigRequest" + }, + { + "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.retail_v2alpha.types.ServingConfig", + "shortName": "get_serving_config" + }, + "description": "Sample for GetServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.list_serving_configs", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.ListServingConfigs", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "ListServingConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListServingConfigsRequest" + }, + { + "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.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsAsyncPager", + "shortName": "list_serving_configs" + }, + "description": "Sample for ListServingConfigs", + "file": "retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.list_serving_configs", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.ListServingConfigs", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "ListServingConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListServingConfigsRequest" + }, + { + "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.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsPager", + "shortName": "list_serving_configs" + }, + "description": "Sample for ListServingConfigs", + "file": "retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.remove_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.RemoveControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "RemoveControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "remove_control" + }, + "description": "Sample for RemoveControl", + "file": "retail_v2alpha_generated_serving_config_service_remove_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_RemoveControl_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_remove_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.remove_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.RemoveControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "RemoveControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "remove_control" + }, + "description": "Sample for RemoveControl", + "file": "retail_v2alpha_generated_serving_config_service_remove_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_RemoveControl_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_remove_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.update_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.UpdateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "UpdateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateServingConfigRequest" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2alpha.types.ServingConfig" + }, + { + "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.retail_v2alpha.types.ServingConfig", + "shortName": "update_serving_config" + }, + "description": "Sample for UpdateServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_update_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_update_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.update_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.UpdateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "UpdateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateServingConfigRequest" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2alpha.types.ServingConfig" + }, + { + "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.retail_v2alpha.types.ServingConfig", + "shortName": "update_serving_config" + }, + "description": "Sample for UpdateServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2alpha_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_CollectUserEvent_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2alpha_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_CollectUserEvent_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2alpha_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_ImportUserEvents_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2alpha_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_ImportUserEvents_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2alpha_generated_user_event_service_purge_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_PurgeUserEvents_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_purge_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2alpha_generated_user_event_service_purge_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_purge_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_RejoinUserEvents_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2alpha_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_WriteUserEvent_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2alpha_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_WriteUserEvent_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py b/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py new file mode 100644 index 00000000..5fbe2d4d --- /dev/null +++ b/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py @@ -0,0 +1,219 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class retailCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_catalog_attribute': ('attributes_config', 'catalog_attribute', ), + 'add_control': ('serving_config', 'control_id', ), + 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), + 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), + 'create_control': ('parent', 'control', 'control_id', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'create_serving_config': ('parent', 'serving_config', 'serving_config_id', ), + 'delete_control': ('name', ), + 'delete_product': ('name', ), + 'delete_serving_config': ('name', ), + 'get_attributes_config': ('name', ), + 'get_completion_config': ('name', ), + 'get_control': ('name', ), + 'get_default_branch': ('catalog', ), + 'get_product': ('name', ), + 'get_serving_config': ('name', ), + 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), + 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), + 'import_user_events': ('parent', 'input_config', 'errors_config', ), + 'list_catalogs': ('parent', 'page_size', 'page_token', ), + 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', 'require_total_size', ), + 'list_serving_configs': ('parent', 'page_size', 'page_token', ), + 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), + 'purge_products': ('parent', 'filter', 'force', ), + 'purge_user_events': ('parent', 'filter', 'force', ), + 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), + 'remove_catalog_attribute': ('attributes_config', 'key', ), + 'remove_control': ('serving_config', 'control_id', ), + 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), + 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), + 'replace_catalog_attribute': ('attributes_config', 'catalog_attribute', 'update_mask', ), + 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'relevance_threshold', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), + 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), + 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), + 'update_attributes_config': ('attributes_config', 'update_mask', ), + 'update_catalog': ('catalog', 'update_mask', ), + 'update_completion_config': ('completion_config', 'update_mask', ), + 'update_control': ('control', 'update_mask', ), + 'update_product': ('product', 'update_mask', 'allow_missing', ), + 'update_serving_config': ('serving_config', 'update_mask', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=retailCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the retail client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2alpha/setup.py b/owl-bot-staging/v2alpha/setup.py new file mode 100644 index 00000000..1103510b --- /dev/null +++ b/owl-bot-staging/v2alpha/setup.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-retail', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-retail", + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 2.8.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'googleapis-common-protos >= 1.55.0, <2.0.0dev', + 'proto-plus >= 1.19.7', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2alpha/tests/__init__.py b/owl-bot-staging/v2alpha/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/tests/unit/__init__.py b/owl-bot-staging/v2alpha/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py new file mode 100644 index 00000000..8815d72e --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py @@ -0,0 +1,3844 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.catalog_service import CatalogServiceAsyncClient +from google.cloud.retail_v2alpha.services.catalog_service import CatalogServiceClient +from google.cloud.retail_v2alpha.services.catalog_service import pagers +from google.cloud.retail_v2alpha.services.catalog_service import transports +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CatalogServiceClient._get_default_mtls_endpoint(None) is None + assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CatalogServiceGrpcTransport, "grpc"), + (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_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", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_catalog_service_client_get_transport_class(): + transport = CatalogServiceClient.get_transport_class() + available_transports = [ + transports.CatalogServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CatalogServiceClient.get_transport_class("grpc") + assert transport == transports.CatalogServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CatalogServiceClient, CatalogServiceAsyncClient +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_catalog_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ListCatalogsRequest, + dict, +]) +def test_list_catalogs(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_catalogs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalogs), + '__call__') as call: + client.list_catalogs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + +@pytest.mark.asyncio +async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_catalogs_async_from_dict(): + await test_list_catalogs_async(request_type=dict) + + +def test_list_catalogs_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = catalog_service.ListCatalogsResponse() + client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_catalogs( + 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_catalogs_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_catalogs_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_catalogs( + 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_catalogs_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + + +def test_list_catalogs_pager(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_catalogs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, catalog.Catalog) + for i in results) +def test_list_catalogs_pages(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = list(client.list_catalogs(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_catalogs_async_pager(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_catalogs(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, catalog.Catalog) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_catalogs_async_pages(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCatalogRequest, + dict, +]) +def test_update_catalog(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + ) + response = client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_catalog_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalog), + '__call__') as call: + client.update_catalog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + +@pytest.mark.asyncio +async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_catalog_async_from_dict(): + await test_update_catalog_async(request_type=dict) + + +def test_update_catalog_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = gcr_catalog.Catalog() + client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_catalog_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +def test_update_catalog_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_catalog_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.SetDefaultBranchRequest, + dict, +]) +def test_set_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_set_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + client.set_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_set_default_branch_async_from_dict(): + await test_set_default_branch_async(request_type=dict) + + +def test_set_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = None + client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_set_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_set_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetDefaultBranchRequest, + dict, +]) +def test_get_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + ) + response = client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +def test_get_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_default_branch), + '__call__') as call: + client.get_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + )) + response = await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +@pytest.mark.asyncio +async def test_get_default_branch_async_from_dict(): + await test_get_default_branch_async(request_type=dict) + + +def test_get_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = catalog_service.GetDefaultBranchResponse() + client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_get_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_get_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetCompletionConfigRequest, + dict, +]) +def test_get_completion_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + ) + response = client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +def test_get_completion_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_completion_config), + '__call__') as call: + client.get_completion_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + +@pytest.mark.asyncio +async def test_get_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCompletionConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + )) + response = await client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +@pytest.mark.asyncio +async def test_get_completion_config_async_from_dict(): + await test_get_completion_config_async(request_type=dict) + + +def test_get_completion_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCompletionConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + call.return_value = catalog.CompletionConfig() + client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_completion_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCompletionConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + await client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_completion_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_completion_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_completion_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_completion_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_completion_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_completion_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCompletionConfigRequest, + dict, +]) +def test_update_completion_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + ) + response = client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +def test_update_completion_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_completion_config), + '__call__') as call: + client.update_completion_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + +@pytest.mark.asyncio +async def test_update_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCompletionConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + )) + response = await client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +@pytest.mark.asyncio +async def test_update_completion_config_async_from_dict(): + await test_update_completion_config_async(request_type=dict) + + +def test_update_completion_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCompletionConfigRequest() + + request.completion_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + call.return_value = catalog.CompletionConfig() + client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'completion_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_completion_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCompletionConfigRequest() + + request.completion_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + await client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'completion_config.name=name_value', + ) in kw['metadata'] + + +def test_update_completion_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_completion_config( + completion_config=catalog.CompletionConfig(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].completion_config + mock_val = catalog.CompletionConfig(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_completion_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_completion_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_completion_config( + completion_config=catalog.CompletionConfig(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].completion_config + mock_val = catalog.CompletionConfig(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_completion_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetAttributesConfigRequest, + dict, +]) +def test_get_attributes_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_get_attributes_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_attributes_config), + '__call__') as call: + client.get_attributes_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + +@pytest.mark.asyncio +async def test_get_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetAttributesConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_get_attributes_config_async_from_dict(): + await test_get_attributes_config_async(request_type=dict) + + +def test_get_attributes_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetAttributesConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_attributes_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetAttributesConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_attributes_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_attributes_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_attributes_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_attributes_config( + catalog_service.GetAttributesConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_attributes_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_attributes_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_attributes_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_attributes_config( + catalog_service.GetAttributesConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateAttributesConfigRequest, + dict, +]) +def test_update_attributes_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_update_attributes_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_attributes_config), + '__call__') as call: + client.update_attributes_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + +@pytest.mark.asyncio +async def test_update_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateAttributesConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_update_attributes_config_async_from_dict(): + await test_update_attributes_config_async(request_type=dict) + + +def test_update_attributes_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateAttributesConfigRequest() + + request.attributes_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_attributes_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateAttributesConfigRequest() + + request.attributes_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config.name=name_value', + ) in kw['metadata'] + + +def test_update_attributes_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_attributes_config( + attributes_config=catalog.AttributesConfig(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].attributes_config + mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_attributes_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_attributes_config( + attributes_config=catalog.AttributesConfig(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].attributes_config + mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.AddCatalogAttributeRequest, + dict, +]) +def test_add_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_add_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + client.add_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_add_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.AddCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_add_catalog_attribute_async_from_dict(): + await test_add_catalog_attribute_async(request_type=dict) + + +def test_add_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.AddCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.AddCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + catalog_service.RemoveCatalogAttributeRequest, + dict, +]) +def test_remove_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_remove_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + client.remove_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.RemoveCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_async_from_dict(): + await test_remove_catalog_attribute_async(request_type=dict) + + +def test_remove_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.RemoveCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.RemoveCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ReplaceCatalogAttributeRequest, + dict, +]) +def test_replace_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_replace_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + client.replace_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ReplaceCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_async_from_dict(): + await test_replace_catalog_attribute_async(request_type=dict) + + +def test_replace_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ReplaceCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ReplaceCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CatalogServiceClient.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 = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CatalogServiceGrpcTransport, + ) + +def test_catalog_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_catalog_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_catalogs', + 'update_catalog', + 'set_default_branch', + 'get_default_branch', + 'get_completion_config', + 'update_completion_config', + 'get_attributes_config', + 'update_attributes_config', + 'add_catalog_attribute', + 'remove_catalog_attribute', + 'replace_catalog_attribute', + ) + 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_catalog_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.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport( + 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_catalog_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.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport() + adc.assert_called_once() + + +def test_catalog_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) + CatalogServiceClient() + 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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +def test_catalog_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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + transports.CatalogServiceRestTransport, + ], +) +def test_catalog_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.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_catalog_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_no_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_with_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_catalog_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcTransport( + 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_catalog_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcAsyncIOTransport( + 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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_attributes_config_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.attributes_config_path(project, location, catalog) + assert expected == actual + + +def test_parse_attributes_config_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CatalogServiceClient.attributes_config_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_attributes_config_path(path) + assert expected == actual + +def test_branch_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = CatalogServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "branch": "clam", + } + path = CatalogServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_branch_path(path) + assert expected == actual + +def test_catalog_path(): + project = "whelk" + location = "octopus" + catalog = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + } + path = CatalogServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_completion_config_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.completion_config_path(project, location, catalog) + assert expected == actual + + +def test_parse_completion_config_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + } + path = CatalogServiceClient.completion_config_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_completion_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CatalogServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = CatalogServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = CatalogServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CatalogServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CatalogServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CatalogServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = CatalogServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CatalogServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CatalogServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CatalogServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py new file mode 100644 index 00000000..b6ce8b74 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py @@ -0,0 +1,1502 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.completion_service import CompletionServiceAsyncClient +from google.cloud.retail_v2alpha.services.completion_service import CompletionServiceClient +from google.cloud.retail_v2alpha.services.completion_service import transports +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CompletionServiceClient._get_default_mtls_endpoint(None) is None + assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CompletionServiceGrpcTransport, "grpc"), + (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_completion_service_client_get_transport_class(): + transport = CompletionServiceClient.get_transport_class() + available_transports = [ + transports.CompletionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CompletionServiceClient.get_transport_class("grpc") + assert transport == transports.CompletionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CompletionServiceClient, CompletionServiceAsyncClient +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_completion_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CompletionServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + ) + response = client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +def test_complete_query_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + client.complete_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + +@pytest.mark.asyncio +async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + )) + response = await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +@pytest.mark.asyncio +async def test_complete_query_async_from_dict(): + await test_complete_query_async(request_type=dict) + + +def test_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) + await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportCompletionDataRequest, + dict, +]) +def test_import_completion_data(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_completion_data_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + client.import_completion_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + +@pytest.mark.asyncio +async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_completion_data_async_from_dict(): + await test_import_completion_data_async(request_type=dict) + + +def test_import_completion_data_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # 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_completion_data_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CompletionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CompletionServiceGrpcTransport, + ) + +def test_completion_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_completion_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'complete_query', + 'import_completion_data', + ) + 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_completion_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_completion_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport() + adc.assert_called_once() + + +def test_completion_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CompletionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, + ], +) +def test_completion_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionServiceGrpcTransport, grpc_helpers), + (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_completion_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_no_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_with_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_completion_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_completion_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_completion_service_grpc_lro_client(): + client = CompletionServiceClient( + 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_completion_service_grpc_lro_async_client(): + client = CompletionServiceAsyncClient( + 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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CompletionServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CompletionServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CompletionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CompletionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = CompletionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CompletionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CompletionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CompletionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = CompletionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CompletionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CompletionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CompletionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CompletionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py new file mode 100644 index 00000000..158ed377 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py @@ -0,0 +1,2617 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.control_service import ControlServiceAsyncClient +from google.cloud.retail_v2alpha.services.control_service import ControlServiceClient +from google.cloud.retail_v2alpha.services.control_service import pagers +from google.cloud.retail_v2alpha.services.control_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.cloud.retail_v2alpha.types import search_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ControlServiceClient._get_default_mtls_endpoint(None) is None + assert ControlServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ControlServiceClient, "grpc"), + (ControlServiceAsyncClient, "grpc_asyncio"), +]) +def test_control_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ControlServiceGrpcTransport, "grpc"), + (transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_control_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", [ + (ControlServiceClient, "grpc"), + (ControlServiceAsyncClient, "grpc_asyncio"), +]) +def test_control_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_control_service_client_get_transport_class(): + transport = ControlServiceClient.get_transport_class() + available_transports = [ + transports.ControlServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ControlServiceClient.get_transport_class("grpc") + assert transport == transports.ControlServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +def test_control_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(ControlServiceClient, '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(ControlServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "true"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "false"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_control_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ControlServiceClient, ControlServiceAsyncClient +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +def test_control_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_control_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_control_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_control_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.control_service.transports.ControlServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ControlServiceClient( + 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", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_control_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.CreateControlRequest, + dict, +]) +def test_create_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +def test_create_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.create_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + +@pytest.mark.asyncio +async def test_create_control_async(transport: str = 'grpc_asyncio', request_type=control_service.CreateControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + )) + response = await client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +@pytest.mark.asyncio +async def test_create_control_async_from_dict(): + await test_create_control_async(request_type=dict) + + +def test_create_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.CreateControlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + call.return_value = gcr_control.Control() + client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.CreateControlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + await client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_control( + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) + assert arg == mock_val + arg = args[0].control_id + mock_val = 'control_id_value' + assert arg == mock_val + + +def test_create_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.CreateControlRequest(), + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_id_value', + ) + +@pytest.mark.asyncio +async def test_create_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_control( + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) + assert arg == mock_val + arg = args[0].control_id + mock_val = 'control_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.CreateControlRequest(), + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.DeleteControlRequest, + dict, +]) +def test_delete_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.delete_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + +@pytest.mark.asyncio +async def test_delete_control_async(transport: str = 'grpc_asyncio', request_type=control_service.DeleteControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_control_async_from_dict(): + await test_delete_control_async(request_type=dict) + + +def test_delete_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.DeleteControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__call__') as call: + call.return_value = None + client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.DeleteControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__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_control( + 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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.DeleteControlRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__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_control( + 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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.DeleteControlRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.UpdateControlRequest, + dict, +]) +def test_update_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +def test_update_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.update_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + +@pytest.mark.asyncio +async def test_update_control_async(transport: str = 'grpc_asyncio', request_type=control_service.UpdateControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + )) + response = await client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +@pytest.mark.asyncio +async def test_update_control_async_from_dict(): + await test_update_control_async(request_type=dict) + + +def test_update_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.UpdateControlRequest() + + request.control.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + call.return_value = gcr_control.Control() + client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'control.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.UpdateControlRequest() + + request.control.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + await client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'control.name=name_value', + ) in kw['metadata'] + + +def test_update_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_control( + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_control( + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.GetControlRequest, + dict, +]) +def test_get_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +def test_get_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.get_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + +@pytest.mark.asyncio +async def test_get_control_async(transport: str = 'grpc_asyncio', request_type=control_service.GetControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + )) + response = await client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +@pytest.mark.asyncio +async def test_get_control_async_from_dict(): + await test_get_control_async(request_type=dict) + + +def test_get_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.GetControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + call.return_value = control.Control() + client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.GetControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) + await client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_control( + 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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.GetControlRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_control( + 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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.GetControlRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.ListControlsRequest, + dict, +]) +def test_list_controls(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_controls_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_controls), + '__call__') as call: + client.list_controls() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + +@pytest.mark.asyncio +async def test_list_controls_async(transport: str = 'grpc_asyncio', request_type=control_service.ListControlsRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_controls_async_from_dict(): + await test_list_controls_async(request_type=dict) + + +def test_list_controls_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.ListControlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + call.return_value = control_service.ListControlsResponse() + client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_controls_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.ListControlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) + await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_controls_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_controls( + 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_controls_flattened_error(): + client = ControlServiceClient( + credentials=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_controls( + control_service.ListControlsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_controls_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_controls( + 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_controls_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_controls( + control_service.ListControlsRequest(), + parent='parent_value', + ) + + +def test_list_controls_pager(transport_name: str = "grpc"): + client = ControlServiceClient( + 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_controls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_controls(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, control.Control) + for i in results) +def test_list_controls_pages(transport_name: str = "grpc"): + client = ControlServiceClient( + 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_controls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + pages = list(client.list_controls(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_controls_async_pager(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_controls(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, control.Control) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_controls_async_pages(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_controls(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ControlServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ControlServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ControlServiceClient.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 = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ControlServiceGrpcTransport, + ) + +def test_control_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ControlServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_control_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.control_service.transports.ControlServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ControlServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_control', + 'delete_control', + 'update_control', + 'get_control', + 'list_controls', + ) + 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_control_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.retail_v2alpha.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ControlServiceTransport( + 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_control_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.retail_v2alpha.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ControlServiceTransport() + adc.assert_called_once() + + +def test_control_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) + ControlServiceClient() + 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.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + ], +) +def test_control_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.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + transports.ControlServiceRestTransport, + ], +) +def test_control_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.ControlServiceGrpcTransport, grpc_helpers), + (transports.ControlServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_control_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_control_service_host_no_port(transport_name): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_control_service_host_with_port(transport_name): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_control_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ControlServiceGrpcTransport( + 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_control_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ControlServiceGrpcAsyncIOTransport( + 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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = ControlServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = ControlServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_control_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + control = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) + actual = ControlServiceClient.control_path(project, location, catalog, control) + assert expected == actual + + +def test_parse_control_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "control": "clam", + } + path = ControlServiceClient.control_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_control_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ControlServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ControlServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ControlServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ControlServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ControlServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ControlServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ControlServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ControlServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.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 = ControlServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ControlServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.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.ControlServiceTransport, '_prep_wrapped_messages') as prep: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ControlServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ControlServiceClient.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 = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ControlServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ControlServiceClient( + 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", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py new file mode 100644 index 00000000..92f4d20d --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py @@ -0,0 +1,1330 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.prediction_service import PredictionServiceAsyncClient +from google.cloud.retail_v2alpha.services.prediction_service import PredictionServiceClient +from google.cloud.retail_v2alpha.services.prediction_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import prediction_service +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import user_event +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PredictionServiceClient._get_default_mtls_endpoint(None) is None + assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionServiceGrpcTransport, "grpc"), + (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_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", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_prediction_service_client_get_transport_class(): + transport = PredictionServiceClient.get_transport_class() + available_transports = [ + transports.PredictionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = PredictionServiceClient.get_transport_class("grpc") + assert transport == transports.PredictionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + PredictionServiceClient, PredictionServiceAsyncClient +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_prediction_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_service.PredictRequest, + dict, +]) +def test_predict(request_type, transport: str = 'grpc'): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + response = client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_predict_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + client.predict() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + +@pytest.mark.asyncio +async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + )) + response = await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +@pytest.mark.asyncio +async def test_predict_async_from_dict(): + await test_predict_async(request_type=dict) + + +def test_predict_field_headers(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_predict_field_headers_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) + await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = PredictionServiceClient.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 = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'predict', + ) + 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport( + 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport() + adc.assert_called_once() + + +def test_prediction_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) + PredictionServiceClient() + 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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +def test_prediction_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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + transports.PredictionServiceRestTransport, + ], +) +def test_prediction_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.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_prediction_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_no_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_with_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_prediction_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcTransport( + 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_prediction_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcAsyncIOTransport( + 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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_product_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + product = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + "branch": "winkle", + "product": "nautilus", + } + path = PredictionServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PredictionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = PredictionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = PredictionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = PredictionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PredictionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = PredictionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = PredictionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = PredictionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = PredictionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PredictionServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py new file mode 100644 index 00000000..b6106cae --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py @@ -0,0 +1,4288 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.product_service import ProductServiceAsyncClient +from google.cloud.retail_v2alpha.services.product_service import ProductServiceClient +from google.cloud.retail_v2alpha.services.product_service import pagers +from google.cloud.retail_v2alpha.services.product_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import purge_config +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProductServiceClient._get_default_mtls_endpoint(None) is None + assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProductServiceGrpcTransport, "grpc"), + (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_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", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_product_service_client_get_transport_class(): + transport = ProductServiceClient.get_transport_class() + available_transports = [ + transports.ProductServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ProductServiceClient.get_transport_class("grpc") + assert transport == transports.ProductServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_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(ProductServiceClient, '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(ProductServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ProductServiceClient, ProductServiceAsyncClient +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_product_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.CreateProductRequest, + dict, +]) +def test_create_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_create_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.create_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + +@pytest.mark.asyncio +async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_create_product_async_from_dict(): + await test_create_product_async(request_type=dict) + + +def test_create_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + + +def test_create_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + +@pytest.mark.asyncio +async def test_create_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_get_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.get_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + +@pytest.mark.asyncio +async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_get_product_async_from_dict(): + await test_get_product_async(request_type=dict) + + +def test_get_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = product.Product() + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.GetProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.GetProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.list_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + +@pytest.mark.asyncio +async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_products_async_from_dict(): + await test_list_products_async(request_type=dict) + + +def test_list_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = product_service.ListProductsResponse() + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products( + 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_products_flattened_error(): + client = ProductServiceClient( + credentials=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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products( + 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_products_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + + +def test_list_products_pager(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_products(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, product.Product) + for i in results) +def test_list_products_pages(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(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_products_async_pager(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(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, product.Product) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_products(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + product_service.UpdateProductRequest, + dict, +]) +def test_update_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_update_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.update_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + +@pytest.mark.asyncio +async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_update_product_async_from_dict(): + await test_update_product_async(request_type=dict) + + +def test_update_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +def test_update_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.DeleteProductRequest, + dict, +]) +def test_delete_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.delete_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + +@pytest.mark.asyncio +async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_product_async_from_dict(): + await test_delete_product_async(request_type=dict) + + +def test_delete_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = None + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeProductsRequest, + dict, +]) +def test_purge_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + client.purge_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeProductsRequest() + +@pytest.mark.asyncio +async def test_purge_products_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_products_async_from_dict(): + await test_purge_products_async(request_type=dict) + + +def test_purge_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_purge_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportProductsRequest, + dict, +]) +def test_import_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.import_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + +@pytest.mark.asyncio +async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__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_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_products_async_from_dict(): + await test_import_products_async(request_type=dict) + + +def test_import_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + product_service.SetInventoryRequest, + dict, +]) +def test_set_inventory(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_inventory_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + client.set_inventory() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + +@pytest.mark.asyncio +async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_set_inventory_async_from_dict(): + await test_set_inventory_async(request_type=dict) + + +def test_set_inventory_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_inventory_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +def test_set_inventory_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_set_inventory_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_set_inventory_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_inventory_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddFulfillmentPlacesRequest, + dict, +]) +def test_add_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + client.add_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async_from_dict(): + await test_add_fulfillment_places_async(request_type=dict) + + +def test_add_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveFulfillmentPlacesRequest, + dict, +]) +def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + client.remove_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async_from_dict(): + await test_remove_fulfillment_places_async(request_type=dict) + + +def test_remove_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddLocalInventoriesRequest, + dict, +]) +def test_add_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + client.add_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_local_inventories_async_from_dict(): + await test_add_local_inventories_async(request_type=dict) + + +def test_add_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveLocalInventoriesRequest, + dict, +]) +def test_remove_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + client.remove_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_local_inventories_async_from_dict(): + await test_remove_local_inventories_async(request_type=dict) + + +def test_remove_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ProductServiceClient.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 = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProductServiceGrpcTransport, + ) + +def test_product_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_product_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.product_service.transports.ProductServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_product', + 'get_product', + 'list_products', + 'update_product', + 'delete_product', + 'purge_products', + 'import_products', + 'set_inventory', + 'add_fulfillment_places', + 'remove_fulfillment_places', + 'add_local_inventories', + 'remove_local_inventories', + ) + 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_product_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.retail_v2alpha.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport( + 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_product_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.retail_v2alpha.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport() + adc.assert_called_once() + + +def test_product_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) + ProductServiceClient() + 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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + ], +) +def test_product_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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + transports.ProductServiceRestTransport, + ], +) +def test_product_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.ProductServiceGrpcTransport, grpc_helpers), + (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_product_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_no_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_with_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_product_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcTransport( + 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_product_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcAsyncIOTransport( + 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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_product_service_grpc_lro_client(): + client = ProductServiceClient( + 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_product_service_grpc_lro_async_client(): + client = ProductServiceAsyncClient( + 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" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = ProductServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = ProductServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = ProductServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = ProductServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProductServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ProductServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProductServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ProductServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProductServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ProductServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ProductServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ProductServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ProductServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ProductServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ProductServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py new file mode 100644 index 00000000..1060de11 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py @@ -0,0 +1,1547 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.search_service import SearchServiceAsyncClient +from google.cloud.retail_v2alpha.services.search_service import SearchServiceClient +from google.cloud.retail_v2alpha.services.search_service import pagers +from google.cloud.retail_v2alpha.services.search_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SearchServiceClient._get_default_mtls_endpoint(None) is None + assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SearchServiceGrpcTransport, "grpc"), + (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_search_service_client_get_transport_class(): + transport = SearchServiceClient.get_transport_class() + available_transports = [ + transports.SearchServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SearchServiceClient.get_transport_class("grpc") + assert transport == transports.SearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SearchServiceClient, SearchServiceAsyncClient +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SearchServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + search_service.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + + +def test_search_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = search_service.SearchResponse() + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_search_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('placement', ''), + )), + ) + pager = client.search(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_async_pager(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = SearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_search_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_search_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport() + adc.assert_called_once() + + +def test_search_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SearchServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + transports.SearchServiceRestTransport, + ], +) +def test_search_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SearchServiceGrpcTransport, grpc_helpers), + (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_search_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_no_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_with_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_branch_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = SearchServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = SearchServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = SearchServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = SearchServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py new file mode 100644 index 00000000..8cfe1d67 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py @@ -0,0 +1,3330 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.serving_config_service import ServingConfigServiceAsyncClient +from google.cloud.retail_v2alpha.services.serving_config_service import ServingConfigServiceClient +from google.cloud.retail_v2alpha.services.serving_config_service import pagers +from google.cloud.retail_v2alpha.services.serving_config_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ServingConfigServiceClient._get_default_mtls_endpoint(None) is None + assert ServingConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ServingConfigServiceClient, "grpc"), + (ServingConfigServiceAsyncClient, "grpc_asyncio"), +]) +def test_serving_config_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ServingConfigServiceGrpcTransport, "grpc"), + (transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_serving_config_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", [ + (ServingConfigServiceClient, "grpc"), + (ServingConfigServiceAsyncClient, "grpc_asyncio"), +]) +def test_serving_config_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_serving_config_service_client_get_transport_class(): + transport = ServingConfigServiceClient.get_transport_class() + available_transports = [ + transports.ServingConfigServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ServingConfigServiceClient.get_transport_class("grpc") + assert transport == transports.ServingConfigServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +def test_serving_config_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(ServingConfigServiceClient, '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(ServingConfigServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "true"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "false"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_serving_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ServingConfigServiceClient, ServingConfigServiceAsyncClient +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +def test_serving_config_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_serving_config_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_serving_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_serving_config_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ServingConfigServiceClient( + 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", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_serving_config_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.CreateServingConfigRequest, + dict, +]) +def test_create_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_create_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.create_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + +@pytest.mark.asyncio +async def test_create_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.CreateServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_create_serving_config_async_from_dict(): + await test_create_serving_config_async(request_type=dict) + + +def test_create_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.CreateServingConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.CreateServingConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_serving_config( + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].serving_config + mock_val = gcr_serving_config.ServingConfig(name='name_value') + assert arg == mock_val + arg = args[0].serving_config_id + mock_val = 'serving_config_id_value' + assert arg == mock_val + + +def test_create_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.CreateServingConfigRequest(), + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_serving_config( + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].serving_config + mock_val = gcr_serving_config.ServingConfig(name='name_value') + assert arg == mock_val + arg = args[0].serving_config_id + mock_val = 'serving_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.CreateServingConfigRequest(), + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.DeleteServingConfigRequest, + dict, +]) +def test_delete_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.delete_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + +@pytest.mark.asyncio +async def test_delete_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.DeleteServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_serving_config_async_from_dict(): + await test_delete_serving_config_async(request_type=dict) + + +def test_delete_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.DeleteServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__call__') as call: + call.return_value = None + client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.DeleteServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__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_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.DeleteServingConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__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_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.DeleteServingConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.UpdateServingConfigRequest, + dict, +]) +def test_update_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_update_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.update_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + +@pytest.mark.asyncio +async def test_update_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.UpdateServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_update_serving_config_async_from_dict(): + await test_update_serving_config_async(request_type=dict) + + +def test_update_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.UpdateServingConfigRequest() + + request.serving_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.UpdateServingConfigRequest() + + request.serving_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config.name=name_value', + ) in kw['metadata'] + + +def test_update_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_serving_config( + serving_config=gcr_serving_config.ServingConfig(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].serving_config + mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_serving_config( + serving_config=gcr_serving_config.ServingConfig(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].serving_config + mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.GetServingConfigRequest, + dict, +]) +def test_get_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_get_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.get_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + +@pytest.mark.asyncio +async def test_get_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.GetServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_get_serving_config_async_from_dict(): + await test_get_serving_config_async(request_type=dict) + + +def test_get_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.GetServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + call.return_value = serving_config.ServingConfig() + client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.GetServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) + await client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.GetServingConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.GetServingConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.ListServingConfigsRequest, + dict, +]) +def test_list_serving_configs(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_serving_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_configs), + '__call__') as call: + client.list_serving_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + +@pytest.mark.asyncio +async def test_list_serving_configs_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.ListServingConfigsRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_serving_configs_async_from_dict(): + await test_list_serving_configs_async(request_type=dict) + + +def test_list_serving_configs_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.ListServingConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + call.return_value = serving_config_service.ListServingConfigsResponse() + client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_serving_configs_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.ListServingConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) + await client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_serving_configs_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_serving_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_serving_configs_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_serving_configs_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_serving_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_serving_configs_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent='parent_value', + ) + + +def test_list_serving_configs_pager(transport_name: str = "grpc"): + client = ServingConfigServiceClient( + 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_serving_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_serving_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, serving_config.ServingConfig) + for i in results) +def test_list_serving_configs_pages(transport_name: str = "grpc"): + client = ServingConfigServiceClient( + 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_serving_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_serving_configs(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_serving_configs_async_pager(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_serving_configs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, serving_config.ServingConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_serving_configs_async_pages(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_serving_configs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + serving_config_service.AddControlRequest, + dict, +]) +def test_add_control(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_add_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + client.add_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + +@pytest.mark.asyncio +async def test_add_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.AddControlRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_add_control_async_from_dict(): + await test_add_control_async(request_type=dict) + + +def test_add_control_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.AddControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_control_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.AddControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_add_control_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + + +def test_add_control_flattened_error(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_control( + serving_config_service.AddControlRequest(), + serving_config='serving_config_value', + ) + +@pytest.mark.asyncio +async def test_add_control_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_control_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_control( + serving_config_service.AddControlRequest(), + serving_config='serving_config_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.RemoveControlRequest, + dict, +]) +def test_remove_control(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_remove_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + client.remove_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + +@pytest.mark.asyncio +async def test_remove_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.RemoveControlRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_remove_control_async_from_dict(): + await test_remove_control_async(request_type=dict) + + +def test_remove_control_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.RemoveControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_control_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.RemoveControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_remove_control_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + + +def test_remove_control_flattened_error(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config='serving_config_value', + ) + +@pytest.mark.asyncio +async def test_remove_control_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_control_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config='serving_config_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServingConfigServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ServingConfigServiceClient.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 = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ServingConfigServiceGrpcTransport, + ) + +def test_serving_config_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ServingConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_serving_config_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ServingConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_serving_config', + 'delete_serving_config', + 'update_serving_config', + 'get_serving_config', + 'list_serving_configs', + 'add_control', + 'remove_control', + ) + 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_serving_config_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.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServingConfigServiceTransport( + 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_serving_config_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.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServingConfigServiceTransport() + adc.assert_called_once() + + +def test_serving_config_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) + ServingConfigServiceClient() + 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.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + ], +) +def test_serving_config_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.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + transports.ServingConfigServiceRestTransport, + ], +) +def test_serving_config_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.ServingConfigServiceGrpcTransport, grpc_helpers), + (transports.ServingConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_serving_config_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_serving_config_service_host_no_port(transport_name): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_serving_config_service_host_with_port(transport_name): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_serving_config_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServingConfigServiceGrpcTransport( + 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_serving_config_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + 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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = ServingConfigServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = ServingConfigServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + serving_config = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, serving_config=serving_config, ) + actual = ServingConfigServiceClient.serving_config_path(project, location, catalog, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "serving_config": "clam", + } + path = ServingConfigServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ServingConfigServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ServingConfigServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ServingConfigServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ServingConfigServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ServingConfigServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ServingConfigServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ServingConfigServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ServingConfigServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.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 = ServingConfigServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ServingConfigServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.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.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ServingConfigServiceClient.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 = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ServingConfigServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ServingConfigServiceClient( + 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", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py new file mode 100644 index 00000000..358ae900 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py @@ -0,0 +1,2039 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.retail_v2alpha.services.user_event_service import UserEventServiceClient +from google.cloud.retail_v2alpha.services.user_event_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + ) + response = client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +def test_write_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) + await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeUserEventsRequest, + dict, +]) +def test_purge_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + client.purge_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + +@pytest.mark.asyncio +async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_user_events_async_from_dict(): + await test_purge_user_events_async(request_type=dict) + + +def test_purge_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_purge_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.RejoinUserEventsRequest, + dict, +]) +def test_rejoin_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_rejoin_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + client.rejoin_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + +@pytest.mark.asyncio +async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_rejoin_user_events_async_from_dict(): + await test_rejoin_user_events_async(request_type=dict) + + +def test_rejoin_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_rejoin_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'purge_user_events', + 'import_user_events', + 'rejoin_user_events', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_user_event_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_user_event_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +def test_user_event_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + UserEventServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +def test_user_event_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = UserEventServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = UserEventServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_product_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + product = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + "branch": "whelk", + "product": "octopus", + } + path = UserEventServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/.coveragerc b/owl-bot-staging/v2beta/.coveragerc new file mode 100644 index 00000000..a8b114f0 --- /dev/null +++ b/owl-bot-staging/v2beta/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/retail/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2beta/.flake8 b/owl-bot-staging/v2beta/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v2beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v2beta/MANIFEST.in b/owl-bot-staging/v2beta/MANIFEST.in new file mode 100644 index 00000000..43074617 --- /dev/null +++ b/owl-bot-staging/v2beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/retail *.py +recursive-include google/cloud/retail_v2beta *.py diff --git a/owl-bot-staging/v2beta/README.rst b/owl-bot-staging/v2beta/README.rst new file mode 100644 index 00000000..cb039760 --- /dev/null +++ b/owl-bot-staging/v2beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Retail API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Retail API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2beta/docs/conf.py b/owl-bot-staging/v2beta/docs/conf.py new file mode 100644 index 00000000..5be9eb4b --- /dev/null +++ b/owl-bot-staging/v2beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-retail documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-retail" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-retail-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-retail.tex", + u"google-cloud-retail Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-retail", + u"Google Cloud Retail Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-retail", + u"google-cloud-retail Documentation", + author, + "google-cloud-retail", + "GAPIC library for Google Cloud Retail API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v2beta/docs/index.rst b/owl-bot-staging/v2beta/docs/index.rst new file mode 100644 index 00000000..fd60fc85 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + retail_v2beta/services + retail_v2beta/types diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst new file mode 100644 index 00000000..3a7c19e6 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst @@ -0,0 +1,10 @@ +CatalogService +-------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.catalog_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.catalog_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst new file mode 100644 index 00000000..1f6782ed --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst @@ -0,0 +1,6 @@ +CompletionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.completion_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst new file mode 100644 index 00000000..86cfcba1 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst @@ -0,0 +1,10 @@ +ControlService +-------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.control_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.control_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst new file mode 100644 index 00000000..903c951d --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst @@ -0,0 +1,6 @@ +PredictionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.prediction_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst new file mode 100644 index 00000000..489daa22 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst @@ -0,0 +1,10 @@ +ProductService +-------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.product_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.product_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst new file mode 100644 index 00000000..591f5c86 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst @@ -0,0 +1,10 @@ +SearchService +------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst new file mode 100644 index 00000000..04251720 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst @@ -0,0 +1,13 @@ +Services for Google Cloud Retail v2beta API +=========================================== +.. toctree:: + :maxdepth: 2 + + catalog_service + completion_service + control_service + prediction_service + product_service + search_service + serving_config_service + user_event_service diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst new file mode 100644 index 00000000..c074749c --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst @@ -0,0 +1,10 @@ +ServingConfigService +-------------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.serving_config_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.serving_config_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst new file mode 100644 index 00000000..ae17ce43 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Retail v2beta API +======================================== + +.. automodule:: google.cloud.retail_v2beta.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst new file mode 100644 index 00000000..11ab3794 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst @@ -0,0 +1,6 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.user_event_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/google/cloud/retail/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail/__init__.py new file mode 100644 index 00000000..07f795e3 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail/__init__.py @@ -0,0 +1,275 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.retail_v2beta.services.catalog_service.client import CatalogServiceClient +from google.cloud.retail_v2beta.services.catalog_service.async_client import CatalogServiceAsyncClient +from google.cloud.retail_v2beta.services.completion_service.client import CompletionServiceClient +from google.cloud.retail_v2beta.services.completion_service.async_client import CompletionServiceAsyncClient +from google.cloud.retail_v2beta.services.control_service.client import ControlServiceClient +from google.cloud.retail_v2beta.services.control_service.async_client import ControlServiceAsyncClient +from google.cloud.retail_v2beta.services.prediction_service.client import PredictionServiceClient +from google.cloud.retail_v2beta.services.prediction_service.async_client import PredictionServiceAsyncClient +from google.cloud.retail_v2beta.services.product_service.client import ProductServiceClient +from google.cloud.retail_v2beta.services.product_service.async_client import ProductServiceAsyncClient +from google.cloud.retail_v2beta.services.search_service.client import SearchServiceClient +from google.cloud.retail_v2beta.services.search_service.async_client import SearchServiceAsyncClient +from google.cloud.retail_v2beta.services.serving_config_service.client import ServingConfigServiceClient +from google.cloud.retail_v2beta.services.serving_config_service.async_client import ServingConfigServiceAsyncClient +from google.cloud.retail_v2beta.services.user_event_service.client import UserEventServiceClient +from google.cloud.retail_v2beta.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.retail_v2beta.types.catalog import AttributesConfig +from google.cloud.retail_v2beta.types.catalog import Catalog +from google.cloud.retail_v2beta.types.catalog import CatalogAttribute +from google.cloud.retail_v2beta.types.catalog import CompletionConfig +from google.cloud.retail_v2beta.types.catalog import MerchantCenterLink +from google.cloud.retail_v2beta.types.catalog import MerchantCenterLinkingConfig +from google.cloud.retail_v2beta.types.catalog import ProductLevelConfig +from google.cloud.retail_v2beta.types.catalog_service import AddCatalogAttributeRequest +from google.cloud.retail_v2beta.types.catalog_service import GetAttributesConfigRequest +from google.cloud.retail_v2beta.types.catalog_service import GetCompletionConfigRequest +from google.cloud.retail_v2beta.types.catalog_service import GetDefaultBranchRequest +from google.cloud.retail_v2beta.types.catalog_service import GetDefaultBranchResponse +from google.cloud.retail_v2beta.types.catalog_service import ListCatalogsRequest +from google.cloud.retail_v2beta.types.catalog_service import ListCatalogsResponse +from google.cloud.retail_v2beta.types.catalog_service import RemoveCatalogAttributeRequest +from google.cloud.retail_v2beta.types.catalog_service import ReplaceCatalogAttributeRequest +from google.cloud.retail_v2beta.types.catalog_service import SetDefaultBranchRequest +from google.cloud.retail_v2beta.types.catalog_service import UpdateAttributesConfigRequest +from google.cloud.retail_v2beta.types.catalog_service import UpdateCatalogRequest +from google.cloud.retail_v2beta.types.catalog_service import UpdateCompletionConfigRequest +from google.cloud.retail_v2beta.types.common import Audience +from google.cloud.retail_v2beta.types.common import ColorInfo +from google.cloud.retail_v2beta.types.common import Condition +from google.cloud.retail_v2beta.types.common import CustomAttribute +from google.cloud.retail_v2beta.types.common import FulfillmentInfo +from google.cloud.retail_v2beta.types.common import Image +from google.cloud.retail_v2beta.types.common import Interval +from google.cloud.retail_v2beta.types.common import LocalInventory +from google.cloud.retail_v2beta.types.common import PriceInfo +from google.cloud.retail_v2beta.types.common import Rating +from google.cloud.retail_v2beta.types.common import Rule +from google.cloud.retail_v2beta.types.common import UserInfo +from google.cloud.retail_v2beta.types.common import AttributeConfigLevel +from google.cloud.retail_v2beta.types.common import SearchSolutionUseCase +from google.cloud.retail_v2beta.types.common import SolutionType +from google.cloud.retail_v2beta.types.completion_service import CompleteQueryRequest +from google.cloud.retail_v2beta.types.completion_service import CompleteQueryResponse +from google.cloud.retail_v2beta.types.control import Control +from google.cloud.retail_v2beta.types.control_service import CreateControlRequest +from google.cloud.retail_v2beta.types.control_service import DeleteControlRequest +from google.cloud.retail_v2beta.types.control_service import GetControlRequest +from google.cloud.retail_v2beta.types.control_service import ListControlsRequest +from google.cloud.retail_v2beta.types.control_service import ListControlsResponse +from google.cloud.retail_v2beta.types.control_service import UpdateControlRequest +from google.cloud.retail_v2beta.types.export_config import ExportErrorsConfig +from google.cloud.retail_v2beta.types.export_config import ExportMetadata +from google.cloud.retail_v2beta.types.export_config import ExportProductsResponse +from google.cloud.retail_v2beta.types.export_config import ExportUserEventsResponse +from google.cloud.retail_v2beta.types.import_config import BigQuerySource +from google.cloud.retail_v2beta.types.import_config import CompletionDataInputConfig +from google.cloud.retail_v2beta.types.import_config import GcsSource +from google.cloud.retail_v2beta.types.import_config import ImportCompletionDataRequest +from google.cloud.retail_v2beta.types.import_config import ImportCompletionDataResponse +from google.cloud.retail_v2beta.types.import_config import ImportErrorsConfig +from google.cloud.retail_v2beta.types.import_config import ImportMetadata +from google.cloud.retail_v2beta.types.import_config import ImportProductsRequest +from google.cloud.retail_v2beta.types.import_config import ImportProductsResponse +from google.cloud.retail_v2beta.types.import_config import ImportUserEventsRequest +from google.cloud.retail_v2beta.types.import_config import ImportUserEventsResponse +from google.cloud.retail_v2beta.types.import_config import ProductInlineSource +from google.cloud.retail_v2beta.types.import_config import ProductInputConfig +from google.cloud.retail_v2beta.types.import_config import UserEventImportSummary +from google.cloud.retail_v2beta.types.import_config import UserEventInlineSource +from google.cloud.retail_v2beta.types.import_config import UserEventInputConfig +from google.cloud.retail_v2beta.types.prediction_service import PredictRequest +from google.cloud.retail_v2beta.types.prediction_service import PredictResponse +from google.cloud.retail_v2beta.types.product import Product +from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesMetadata +from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesRequest +from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesResponse +from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesMetadata +from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesRequest +from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesResponse +from google.cloud.retail_v2beta.types.product_service import CreateProductRequest +from google.cloud.retail_v2beta.types.product_service import DeleteProductRequest +from google.cloud.retail_v2beta.types.product_service import GetProductRequest +from google.cloud.retail_v2beta.types.product_service import ListProductsRequest +from google.cloud.retail_v2beta.types.product_service import ListProductsResponse +from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesMetadata +from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesRequest +from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesResponse +from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesMetadata +from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesRequest +from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesResponse +from google.cloud.retail_v2beta.types.product_service import SetInventoryMetadata +from google.cloud.retail_v2beta.types.product_service import SetInventoryRequest +from google.cloud.retail_v2beta.types.product_service import SetInventoryResponse +from google.cloud.retail_v2beta.types.product_service import UpdateProductRequest +from google.cloud.retail_v2beta.types.promotion import Promotion +from google.cloud.retail_v2beta.types.purge_config import PurgeMetadata +from google.cloud.retail_v2beta.types.purge_config import PurgeUserEventsRequest +from google.cloud.retail_v2beta.types.purge_config import PurgeUserEventsResponse +from google.cloud.retail_v2beta.types.search_service import SearchRequest +from google.cloud.retail_v2beta.types.search_service import SearchResponse +from google.cloud.retail_v2beta.types.serving_config import ServingConfig +from google.cloud.retail_v2beta.types.serving_config_service import AddControlRequest +from google.cloud.retail_v2beta.types.serving_config_service import CreateServingConfigRequest +from google.cloud.retail_v2beta.types.serving_config_service import DeleteServingConfigRequest +from google.cloud.retail_v2beta.types.serving_config_service import GetServingConfigRequest +from google.cloud.retail_v2beta.types.serving_config_service import ListServingConfigsRequest +from google.cloud.retail_v2beta.types.serving_config_service import ListServingConfigsResponse +from google.cloud.retail_v2beta.types.serving_config_service import RemoveControlRequest +from google.cloud.retail_v2beta.types.serving_config_service import UpdateServingConfigRequest +from google.cloud.retail_v2beta.types.user_event import CompletionDetail +from google.cloud.retail_v2beta.types.user_event import ProductDetail +from google.cloud.retail_v2beta.types.user_event import PurchaseTransaction +from google.cloud.retail_v2beta.types.user_event import UserEvent +from google.cloud.retail_v2beta.types.user_event_service import CollectUserEventRequest +from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsMetadata +from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsRequest +from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsResponse +from google.cloud.retail_v2beta.types.user_event_service import WriteUserEventRequest + +__all__ = ('CatalogServiceClient', + 'CatalogServiceAsyncClient', + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', + 'ControlServiceClient', + 'ControlServiceAsyncClient', + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', + 'ProductServiceClient', + 'ProductServiceAsyncClient', + 'SearchServiceClient', + 'SearchServiceAsyncClient', + 'ServingConfigServiceClient', + 'ServingConfigServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'AttributesConfig', + 'Catalog', + 'CatalogAttribute', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'ProductLevelConfig', + 'AddCatalogAttributeRequest', + 'GetAttributesConfigRequest', + 'GetCompletionConfigRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + 'SetDefaultBranchRequest', + 'UpdateAttributesConfigRequest', + 'UpdateCatalogRequest', + 'UpdateCompletionConfigRequest', + 'Audience', + 'ColorInfo', + 'Condition', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'Rule', + 'UserInfo', + 'AttributeConfigLevel', + 'SearchSolutionUseCase', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Control', + 'CreateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + 'UpdateControlRequest', + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'ServingConfig', + 'AddControlRequest', + 'CreateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'RemoveControlRequest', + 'UpdateServingConfigRequest', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail/py.typed b/owl-bot-staging/v2beta/google/cloud/retail/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py new file mode 100644 index 00000000..3ad83ab4 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.catalog_service import CatalogServiceClient +from .services.catalog_service import CatalogServiceAsyncClient +from .services.completion_service import CompletionServiceClient +from .services.completion_service import CompletionServiceAsyncClient +from .services.control_service import ControlServiceClient +from .services.control_service import ControlServiceAsyncClient +from .services.prediction_service import PredictionServiceClient +from .services.prediction_service import PredictionServiceAsyncClient +from .services.product_service import ProductServiceClient +from .services.product_service import ProductServiceAsyncClient +from .services.search_service import SearchServiceClient +from .services.search_service import SearchServiceAsyncClient +from .services.serving_config_service import ServingConfigServiceClient +from .services.serving_config_service import ServingConfigServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.catalog import AttributesConfig +from .types.catalog import Catalog +from .types.catalog import CatalogAttribute +from .types.catalog import CompletionConfig +from .types.catalog import MerchantCenterLink +from .types.catalog import MerchantCenterLinkingConfig +from .types.catalog import ProductLevelConfig +from .types.catalog_service import AddCatalogAttributeRequest +from .types.catalog_service import GetAttributesConfigRequest +from .types.catalog_service import GetCompletionConfigRequest +from .types.catalog_service import GetDefaultBranchRequest +from .types.catalog_service import GetDefaultBranchResponse +from .types.catalog_service import ListCatalogsRequest +from .types.catalog_service import ListCatalogsResponse +from .types.catalog_service import RemoveCatalogAttributeRequest +from .types.catalog_service import ReplaceCatalogAttributeRequest +from .types.catalog_service import SetDefaultBranchRequest +from .types.catalog_service import UpdateAttributesConfigRequest +from .types.catalog_service import UpdateCatalogRequest +from .types.catalog_service import UpdateCompletionConfigRequest +from .types.common import Audience +from .types.common import ColorInfo +from .types.common import Condition +from .types.common import CustomAttribute +from .types.common import FulfillmentInfo +from .types.common import Image +from .types.common import Interval +from .types.common import LocalInventory +from .types.common import PriceInfo +from .types.common import Rating +from .types.common import Rule +from .types.common import UserInfo +from .types.common import AttributeConfigLevel +from .types.common import SearchSolutionUseCase +from .types.common import SolutionType +from .types.completion_service import CompleteQueryRequest +from .types.completion_service import CompleteQueryResponse +from .types.control import Control +from .types.control_service import CreateControlRequest +from .types.control_service import DeleteControlRequest +from .types.control_service import GetControlRequest +from .types.control_service import ListControlsRequest +from .types.control_service import ListControlsResponse +from .types.control_service import UpdateControlRequest +from .types.export_config import ExportErrorsConfig +from .types.export_config import ExportMetadata +from .types.export_config import ExportProductsResponse +from .types.export_config import ExportUserEventsResponse +from .types.import_config import BigQuerySource +from .types.import_config import CompletionDataInputConfig +from .types.import_config import GcsSource +from .types.import_config import ImportCompletionDataRequest +from .types.import_config import ImportCompletionDataResponse +from .types.import_config import ImportErrorsConfig +from .types.import_config import ImportMetadata +from .types.import_config import ImportProductsRequest +from .types.import_config import ImportProductsResponse +from .types.import_config import ImportUserEventsRequest +from .types.import_config import ImportUserEventsResponse +from .types.import_config import ProductInlineSource +from .types.import_config import ProductInputConfig +from .types.import_config import UserEventImportSummary +from .types.import_config import UserEventInlineSource +from .types.import_config import UserEventInputConfig +from .types.prediction_service import PredictRequest +from .types.prediction_service import PredictResponse +from .types.product import Product +from .types.product_service import AddFulfillmentPlacesMetadata +from .types.product_service import AddFulfillmentPlacesRequest +from .types.product_service import AddFulfillmentPlacesResponse +from .types.product_service import AddLocalInventoriesMetadata +from .types.product_service import AddLocalInventoriesRequest +from .types.product_service import AddLocalInventoriesResponse +from .types.product_service import CreateProductRequest +from .types.product_service import DeleteProductRequest +from .types.product_service import GetProductRequest +from .types.product_service import ListProductsRequest +from .types.product_service import ListProductsResponse +from .types.product_service import RemoveFulfillmentPlacesMetadata +from .types.product_service import RemoveFulfillmentPlacesRequest +from .types.product_service import RemoveFulfillmentPlacesResponse +from .types.product_service import RemoveLocalInventoriesMetadata +from .types.product_service import RemoveLocalInventoriesRequest +from .types.product_service import RemoveLocalInventoriesResponse +from .types.product_service import SetInventoryMetadata +from .types.product_service import SetInventoryRequest +from .types.product_service import SetInventoryResponse +from .types.product_service import UpdateProductRequest +from .types.promotion import Promotion +from .types.purge_config import PurgeMetadata +from .types.purge_config import PurgeUserEventsRequest +from .types.purge_config import PurgeUserEventsResponse +from .types.search_service import SearchRequest +from .types.search_service import SearchResponse +from .types.serving_config import ServingConfig +from .types.serving_config_service import AddControlRequest +from .types.serving_config_service import CreateServingConfigRequest +from .types.serving_config_service import DeleteServingConfigRequest +from .types.serving_config_service import GetServingConfigRequest +from .types.serving_config_service import ListServingConfigsRequest +from .types.serving_config_service import ListServingConfigsResponse +from .types.serving_config_service import RemoveControlRequest +from .types.serving_config_service import UpdateServingConfigRequest +from .types.user_event import CompletionDetail +from .types.user_event import ProductDetail +from .types.user_event import PurchaseTransaction +from .types.user_event import UserEvent +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import RejoinUserEventsMetadata +from .types.user_event_service import RejoinUserEventsRequest +from .types.user_event_service import RejoinUserEventsResponse +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CatalogServiceAsyncClient', + 'CompletionServiceAsyncClient', + 'ControlServiceAsyncClient', + 'PredictionServiceAsyncClient', + 'ProductServiceAsyncClient', + 'SearchServiceAsyncClient', + 'ServingConfigServiceAsyncClient', + 'UserEventServiceAsyncClient', +'AddCatalogAttributeRequest', +'AddControlRequest', +'AddFulfillmentPlacesMetadata', +'AddFulfillmentPlacesRequest', +'AddFulfillmentPlacesResponse', +'AddLocalInventoriesMetadata', +'AddLocalInventoriesRequest', +'AddLocalInventoriesResponse', +'AttributeConfigLevel', +'AttributesConfig', +'Audience', +'BigQuerySource', +'Catalog', +'CatalogAttribute', +'CatalogServiceClient', +'CollectUserEventRequest', +'ColorInfo', +'CompleteQueryRequest', +'CompleteQueryResponse', +'CompletionConfig', +'CompletionDataInputConfig', +'CompletionDetail', +'CompletionServiceClient', +'Condition', +'Control', +'ControlServiceClient', +'CreateControlRequest', +'CreateProductRequest', +'CreateServingConfigRequest', +'CustomAttribute', +'DeleteControlRequest', +'DeleteProductRequest', +'DeleteServingConfigRequest', +'ExportErrorsConfig', +'ExportMetadata', +'ExportProductsResponse', +'ExportUserEventsResponse', +'FulfillmentInfo', +'GcsSource', +'GetAttributesConfigRequest', +'GetCompletionConfigRequest', +'GetControlRequest', +'GetDefaultBranchRequest', +'GetDefaultBranchResponse', +'GetProductRequest', +'GetServingConfigRequest', +'Image', +'ImportCompletionDataRequest', +'ImportCompletionDataResponse', +'ImportErrorsConfig', +'ImportMetadata', +'ImportProductsRequest', +'ImportProductsResponse', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'Interval', +'ListCatalogsRequest', +'ListCatalogsResponse', +'ListControlsRequest', +'ListControlsResponse', +'ListProductsRequest', +'ListProductsResponse', +'ListServingConfigsRequest', +'ListServingConfigsResponse', +'LocalInventory', +'MerchantCenterLink', +'MerchantCenterLinkingConfig', +'PredictRequest', +'PredictResponse', +'PredictionServiceClient', +'PriceInfo', +'Product', +'ProductDetail', +'ProductInlineSource', +'ProductInputConfig', +'ProductLevelConfig', +'ProductServiceClient', +'Promotion', +'PurchaseTransaction', +'PurgeMetadata', +'PurgeUserEventsRequest', +'PurgeUserEventsResponse', +'Rating', +'RejoinUserEventsMetadata', +'RejoinUserEventsRequest', +'RejoinUserEventsResponse', +'RemoveCatalogAttributeRequest', +'RemoveControlRequest', +'RemoveFulfillmentPlacesMetadata', +'RemoveFulfillmentPlacesRequest', +'RemoveFulfillmentPlacesResponse', +'RemoveLocalInventoriesMetadata', +'RemoveLocalInventoriesRequest', +'RemoveLocalInventoriesResponse', +'ReplaceCatalogAttributeRequest', +'Rule', +'SearchRequest', +'SearchResponse', +'SearchServiceClient', +'SearchSolutionUseCase', +'ServingConfig', +'ServingConfigServiceClient', +'SetDefaultBranchRequest', +'SetInventoryMetadata', +'SetInventoryRequest', +'SetInventoryResponse', +'SolutionType', +'UpdateAttributesConfigRequest', +'UpdateCatalogRequest', +'UpdateCompletionConfigRequest', +'UpdateControlRequest', +'UpdateProductRequest', +'UpdateServingConfigRequest', +'UserEvent', +'UserEventImportSummary', +'UserEventInlineSource', +'UserEventInputConfig', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json new file mode 100644 index 00000000..bf3205b9 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json @@ -0,0 +1,551 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.retail_v2beta", + "protoPackage": "google.cloud.retail.v2beta", + "schema": "1.0", + "services": { + "CatalogService": { + "clients": { + "grpc": { + "libraryClient": "CatalogServiceClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "add_catalog_attribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "get_attributes_config" + ] + }, + "GetCompletionConfig": { + "methods": [ + "get_completion_config" + ] + }, + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "remove_catalog_attribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "replace_catalog_attribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "update_attributes_config" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "update_completion_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CatalogServiceAsyncClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "add_catalog_attribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "get_attributes_config" + ] + }, + "GetCompletionConfig": { + "methods": [ + "get_completion_config" + ] + }, + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "remove_catalog_attribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "replace_catalog_attribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "update_attributes_config" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "update_completion_config" + ] + } + } + } + } + }, + "CompletionService": { + "clients": { + "grpc": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CompletionServiceAsyncClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + } + } + }, + "ControlService": { + "clients": { + "grpc": { + "libraryClient": "ControlServiceClient", + "rpcs": { + "CreateControl": { + "methods": [ + "create_control" + ] + }, + "DeleteControl": { + "methods": [ + "delete_control" + ] + }, + "GetControl": { + "methods": [ + "get_control" + ] + }, + "ListControls": { + "methods": [ + "list_controls" + ] + }, + "UpdateControl": { + "methods": [ + "update_control" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ControlServiceAsyncClient", + "rpcs": { + "CreateControl": { + "methods": [ + "create_control" + ] + }, + "DeleteControl": { + "methods": [ + "delete_control" + ] + }, + "GetControl": { + "methods": [ + "get_control" + ] + }, + "ListControls": { + "methods": [ + "list_controls" + ] + }, + "UpdateControl": { + "methods": [ + "update_control" + ] + } + } + } + } + }, + "PredictionService": { + "clients": { + "grpc": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionServiceAsyncClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + } + } + }, + "ProductService": { + "clients": { + "grpc": { + "libraryClient": "ProductServiceClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductServiceAsyncClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + } + } + }, + "SearchService": { + "clients": { + "grpc": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SearchServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + }, + "ServingConfigService": { + "clients": { + "grpc": { + "libraryClient": "ServingConfigServiceClient", + "rpcs": { + "AddControl": { + "methods": [ + "add_control" + ] + }, + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, + "RemoveControl": { + "methods": [ + "remove_control" + ] + }, + "UpdateServingConfig": { + "methods": [ + "update_serving_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServingConfigServiceAsyncClient", + "rpcs": { + "AddControl": { + "methods": [ + "add_control" + ] + }, + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, + "RemoveControl": { + "methods": [ + "remove_control" + ] + }, + "UpdateServingConfig": { + "methods": [ + "update_serving_config" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py new file mode 100644 index 00000000..d276b897 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CatalogServiceClient +from .async_client import CatalogServiceAsyncClient + +__all__ = ( + 'CatalogServiceClient', + 'CatalogServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py new file mode 100644 index 00000000..dfff033b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py @@ -0,0 +1,1350 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.catalog_service import pagers +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport +from .client import CatalogServiceClient + + +class CatalogServiceAsyncClient: + """Service for managing catalog configuration.""" + + _client: CatalogServiceClient + + DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT + + attributes_config_path = staticmethod(CatalogServiceClient.attributes_config_path) + parse_attributes_config_path = staticmethod(CatalogServiceClient.parse_attributes_config_path) + branch_path = staticmethod(CatalogServiceClient.branch_path) + parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) + catalog_path = staticmethod(CatalogServiceClient.catalog_path) + parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) + completion_config_path = staticmethod(CatalogServiceClient.completion_config_path) + parse_completion_config_path = staticmethod(CatalogServiceClient.parse_completion_config_path) + common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CatalogServiceClient.common_project_path) + parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) + common_location_path = staticmethod(CatalogServiceClient.common_location_path) + parse_common_location_path = staticmethod(CatalogServiceClient.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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CatalogServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsAsyncPager: + r"""Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_list_catalogs(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + parent (:class:`str`): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2beta.Catalog]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.retail_v2beta.services.catalog_service.pagers.ListCatalogsAsyncPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.ListCatalogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_catalogs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCatalogsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_catalog(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2beta.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2beta.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] + method. + catalog (:class:`google.cloud.retail_v2beta.types.Catalog`): + Required. The + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2beta.Catalog], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Catalog][google.cloud.retail.v2beta.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_catalog, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_set_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (:class:`str`): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.SetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (:class:`str`): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # 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_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_completion_config(self, + request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Gets a + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] + method. + name (:class:`str`): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + + 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.retail_v2beta.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetCompletionConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_completion_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_completion_config(self, + request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, + *, + completion_config: catalog.CompletionConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Updates the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + completion_config = retail_v2beta.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2beta.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = await client.update_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] + method. + completion_config (:class:`google.cloud.retail_v2beta.types.CompletionConfig`): + Required. The + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``completion_config`` 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 + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([completion_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCompletionConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if completion_config is not None: + request.completion_config = completion_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_completion_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("completion_config.name", request.completion_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_attributes_config(self, + request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Gets an + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] + method. + name (:class:`str`): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + + 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.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetAttributesConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_attributes_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_attributes_config(self, + request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, + *, + attributes_config: catalog.AttributesConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Updates the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + attributes_config = retail_v2beta.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2beta.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = await client.update_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] + method. + attributes_config (:class:`google.cloud.retail_v2beta.types.AttributesConfig`): + Required. The + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. + + This corresponds to the ``attributes_config`` 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 + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attributes_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateAttributesConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attributes_config is not None: + request.attributes_config = attributes_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_attributes_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config.name", request.attributes_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_catalog_attribute(self, + request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Adds the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_add_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.AddCatalogAttributeRequest(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.add_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_catalog_attribute(self, + request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Removes the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = await client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.RemoveCatalogAttributeRequest(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.remove_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def replace_catalog_attribute(self, + request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Replaces the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.ReplaceCatalogAttributeRequest(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.replace_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py new file mode 100644 index 00000000..c95200de --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py @@ -0,0 +1,1580 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.catalog_service import pagers +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CatalogServiceGrpcTransport +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +class CatalogServiceClientMeta(type): + """Metaclass for the CatalogService 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[CatalogServiceTransport]] + _transport_registry["grpc"] = CatalogServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CatalogServiceTransport]: + """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): + """Service for managing catalog configuration.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CatalogServiceClient: 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: + CatalogServiceClient: 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) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def attributes_config_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified attributes_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_attributes_config_path(path: str) -> Dict[str,str]: + """Parses a attributes_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/attributesConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def completion_config_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified completion_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_completion_config_path(path: str) -> Dict[str,str]: + """Parses a completion_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/completionConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CatalogServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CatalogServiceTransport): + # transport is a CatalogServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsPager: + r"""Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_list_catalogs(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2beta.Catalog]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.retail_v2beta.services.catalog_service.pagers.ListCatalogsPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ListCatalogsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ListCatalogsRequest): + request = catalog_service.ListCatalogsRequest(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_catalogs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCatalogsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_catalog(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2beta.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2beta.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] + method. + catalog (google.cloud.retail_v2beta.types.Catalog): + Required. The + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2beta.Catalog], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Catalog][google.cloud.retail.v2beta.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCatalogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCatalogRequest): + request = catalog_service.UpdateCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + 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_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_set_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.SetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.SetDefaultBranchRequest): + request = catalog_service.SetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetDefaultBranchRequest): + request = catalog_service.GetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_completion_config(self, + request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Gets a + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] + method. + name (str): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + + 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.retail_v2beta.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetCompletionConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetCompletionConfigRequest): + request = catalog_service.GetCompletionConfigRequest(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_completion_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_completion_config(self, + request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, + *, + completion_config: catalog.CompletionConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Updates the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + completion_config = retail_v2beta.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2beta.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = client.update_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] + method. + completion_config (google.cloud.retail_v2beta.types.CompletionConfig): + Required. The + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``completion_config`` 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 + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([completion_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCompletionConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCompletionConfigRequest): + request = catalog_service.UpdateCompletionConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if completion_config is not None: + request.completion_config = completion_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_completion_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("completion_config.name", request.completion_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_attributes_config(self, + request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Gets an + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] + method. + name (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + + 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.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetAttributesConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetAttributesConfigRequest): + request = catalog_service.GetAttributesConfigRequest(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_attributes_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_attributes_config(self, + request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, + *, + attributes_config: catalog.AttributesConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Updates the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + attributes_config = retail_v2beta.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2beta.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = client.update_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] + method. + attributes_config (google.cloud.retail_v2beta.types.AttributesConfig): + Required. The + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. + + This corresponds to the ``attributes_config`` 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 + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attributes_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateAttributesConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateAttributesConfigRequest): + request = catalog_service.UpdateAttributesConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attributes_config is not None: + request.attributes_config = attributes_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_attributes_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config.name", request.attributes_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_catalog_attribute(self, + request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Adds the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_add_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.AddCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.AddCatalogAttributeRequest): + request = catalog_service.AddCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_catalog_attribute(self, + request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Removes the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.RemoveCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.RemoveCatalogAttributeRequest): + request = catalog_service.RemoveCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def replace_catalog_attribute(self, + request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Replaces the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ReplaceCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ReplaceCatalogAttributeRequest): + request = catalog_service.ReplaceCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.replace_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py new file mode 100644 index 00000000..0ca25546 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog_service + + +class ListCatalogsPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` + 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[..., catalog_service.ListCatalogsResponse], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2beta.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + for page in self.pages: + yield from page.catalogs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCatalogsAsyncPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` + 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[catalog_service.ListCatalogsResponse]], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2beta.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + async def async_generator(): + async for page in self.pages: + for response in page.catalogs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py new file mode 100644 index 00000000..0cffa336 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 CatalogServiceTransport +from .grpc import CatalogServiceGrpcTransport +from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] +_transport_registry['grpc'] = CatalogServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport + +__all__ = ( + 'CatalogServiceTransport', + 'CatalogServiceGrpcTransport', + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py new file mode 100644 index 00000000..90964f49 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py @@ -0,0 +1,297 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CatalogServiceTransport(abc.ABC): + """Abstract transport class for CatalogService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_catalogs: gapic_v1.method.wrap_method( + self.list_catalogs, + default_timeout=None, + client_info=client_info, + ), + self.update_catalog: gapic_v1.method.wrap_method( + self.update_catalog, + default_timeout=None, + client_info=client_info, + ), + self.set_default_branch: gapic_v1.method.wrap_method( + self.set_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_default_branch: gapic_v1.method.wrap_method( + self.get_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_completion_config: gapic_v1.method.wrap_method( + self.get_completion_config, + default_timeout=None, + client_info=client_info, + ), + self.update_completion_config: gapic_v1.method.wrap_method( + self.update_completion_config, + default_timeout=None, + client_info=client_info, + ), + self.get_attributes_config: gapic_v1.method.wrap_method( + self.get_attributes_config, + default_timeout=None, + client_info=client_info, + ), + self.update_attributes_config: gapic_v1.method.wrap_method( + self.update_attributes_config, + default_timeout=None, + client_info=client_info, + ), + self.add_catalog_attribute: gapic_v1.method.wrap_method( + self.add_catalog_attribute, + default_timeout=None, + client_info=client_info, + ), + self.remove_catalog_attribute: gapic_v1.method.wrap_method( + self.remove_catalog_attribute, + default_timeout=None, + client_info=client_info, + ), + self.replace_catalog_attribute: gapic_v1.method.wrap_method( + self.replace_catalog_attribute, + 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Union[ + catalog_service.ListCatalogsResponse, + Awaitable[catalog_service.ListCatalogsResponse] + ]]: + raise NotImplementedError() + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Union[ + gcr_catalog.Catalog, + Awaitable[gcr_catalog.Catalog] + ]]: + raise NotImplementedError() + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Union[ + catalog_service.GetDefaultBranchResponse, + Awaitable[catalog_service.GetDefaultBranchResponse] + ]]: + raise NotImplementedError() + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + Union[ + catalog.CompletionConfig, + Awaitable[catalog.CompletionConfig] + ]]: + raise NotImplementedError() + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + Union[ + catalog.CompletionConfig, + Awaitable[catalog.CompletionConfig] + ]]: + raise NotImplementedError() + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CatalogServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py new file mode 100644 index 00000000..9ae369d1 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py @@ -0,0 +1,600 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO + + +class CatalogServiceGrpcTransport(CatalogServiceTransport): + """gRPC backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + catalog_service.ListCatalogsResponse]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + ~.ListCatalogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + gcr_catalog.Catalog]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + ~.Catalog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + empty_pb2.Empty]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + ~.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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + catalog_service.GetDefaultBranchResponse]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + ~.GetDefaultBranchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + catalog.CompletionConfig]: + r"""Return a callable for the get completion config method over gRPC. + + Gets a + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. + + Returns: + Callable[[~.GetCompletionConfigRequest], + ~.CompletionConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetCompletionConfig', + request_serializer=catalog_service.GetCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['get_completion_config'] + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + catalog.CompletionConfig]: + r"""Return a callable for the update completion config method over gRPC. + + Updates the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. + + Returns: + Callable[[~.UpdateCompletionConfigRequest], + ~.CompletionConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateCompletionConfig', + request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['update_completion_config'] + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + catalog.AttributesConfig]: + r"""Return a callable for the get attributes config method over gRPC. + + Gets an + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + Returns: + Callable[[~.GetAttributesConfigRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetAttributesConfig', + request_serializer=catalog_service.GetAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['get_attributes_config'] + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + catalog.AttributesConfig]: + r"""Return a callable for the update attributes config method over gRPC. + + Updates the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + Returns: + Callable[[~.UpdateAttributesConfigRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateAttributesConfig', + request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['update_attributes_config'] + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the add catalog attribute method over gRPC. + + Adds the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.AddCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_catalog_attribute' not in self._stubs: + self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/AddCatalogAttribute', + request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['add_catalog_attribute'] + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the remove catalog attribute method over gRPC. + + Removes the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.RemoveCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_catalog_attribute' not in self._stubs: + self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/RemoveCatalogAttribute', + request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['remove_catalog_attribute'] + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the replace catalog attribute method over gRPC. + + Replaces the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.ReplaceCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_catalog_attribute' not in self._stubs: + self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/ReplaceCatalogAttribute', + request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['replace_catalog_attribute'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CatalogServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..37eaea4b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py @@ -0,0 +1,599 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CatalogServiceGrpcTransport + + +class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): + """gRPC AsyncIO backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Awaitable[catalog_service.ListCatalogsResponse]]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + Awaitable[~.ListCatalogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Awaitable[gcr_catalog.Catalog]]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + Awaitable[~.Catalog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + 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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Awaitable[catalog_service.GetDefaultBranchResponse]]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + Awaitable[~.GetDefaultBranchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + Awaitable[catalog.CompletionConfig]]: + r"""Return a callable for the get completion config method over gRPC. + + Gets a + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. + + Returns: + Callable[[~.GetCompletionConfigRequest], + Awaitable[~.CompletionConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetCompletionConfig', + request_serializer=catalog_service.GetCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['get_completion_config'] + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + Awaitable[catalog.CompletionConfig]]: + r"""Return a callable for the update completion config method over gRPC. + + Updates the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. + + Returns: + Callable[[~.UpdateCompletionConfigRequest], + Awaitable[~.CompletionConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateCompletionConfig', + request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['update_completion_config'] + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the get attributes config method over gRPC. + + Gets an + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + Returns: + Callable[[~.GetAttributesConfigRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetAttributesConfig', + request_serializer=catalog_service.GetAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['get_attributes_config'] + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the update attributes config method over gRPC. + + Updates the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + Returns: + Callable[[~.UpdateAttributesConfigRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateAttributesConfig', + request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['update_attributes_config'] + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the add catalog attribute method over gRPC. + + Adds the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.AddCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_catalog_attribute' not in self._stubs: + self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/AddCatalogAttribute', + request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['add_catalog_attribute'] + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the remove catalog attribute method over gRPC. + + Removes the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.RemoveCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_catalog_attribute' not in self._stubs: + self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/RemoveCatalogAttribute', + request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['remove_catalog_attribute'] + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the replace catalog attribute method over gRPC. + + Replaces the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.ReplaceCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_catalog_attribute' not in self._stubs: + self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/ReplaceCatalogAttribute', + request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['replace_catalog_attribute'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py new file mode 100644 index 00000000..b8af95bd --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CompletionServiceClient +from .async_client import CompletionServiceAsyncClient + +__all__ = ( + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py new file mode 100644 index 00000000..66c91320 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .client import CompletionServiceClient + + +class CompletionServiceAsyncClient: + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: CompletionServiceClient + + DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(CompletionServiceClient.catalog_path) + parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) + common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CompletionServiceClient.common_project_path) + parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) + common_location_path = staticmethod(CompletionServiceClient.common_location_path) + parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CompletionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_complete_query(): + # Create a client + client = retail_v2beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_query, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_import_completion_data(): + # Create a client + client = retail_v2beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2beta.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. + 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. + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_completion_data, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py new file mode 100644 index 00000000..5766b6b2 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CompletionServiceGrpcTransport +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +class CompletionServiceClientMeta(type): + """Metaclass for the CompletionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] + _transport_registry["grpc"] = CompletionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CompletionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CompletionServiceClient(metaclass=CompletionServiceClientMeta): + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CompletionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CompletionServiceTransport): + # transport is a CompletionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_complete_query(): + # Create a client + client = retail_v2beta.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a completion_service.CompleteQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, completion_service.CompleteQueryRequest): + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_import_completion_data(): + # Create a client + client = retail_v2beta.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2beta.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. + 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. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportCompletionDataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportCompletionDataRequest): + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_completion_data] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py new file mode 100644 index 00000000..a0c9542f --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CompletionServiceTransport +from .grpc import CompletionServiceGrpcTransport +from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] +_transport_registry['grpc'] = CompletionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport + +__all__ = ( + 'CompletionServiceTransport', + 'CompletionServiceGrpcTransport', + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py new file mode 100644 index 00000000..6a5d8425 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CompletionServiceTransport(abc.ABC): + """Abstract transport class for CompletionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.complete_query: gapic_v1.method.wrap_method( + self.complete_query, + default_timeout=None, + client_info=client_info, + ), + self.import_completion_data: gapic_v1.method.wrap_method( + self.import_completion_data, + 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Union[ + completion_service.CompleteQueryResponse, + Awaitable[completion_service.CompleteQueryResponse] + ]]: + raise NotImplementedError() + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CompletionServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py new file mode 100644 index 00000000..d3ee0929 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py @@ -0,0 +1,325 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO + + +class CompletionServiceGrpcTransport(CompletionServiceTransport): + """gRPC backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + ~.CompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + operations_pb2.Operation]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CompletionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..56463003 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py @@ -0,0 +1,324 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CompletionServiceGrpcTransport + + +class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): + """gRPC AsyncIO backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Awaitable[completion_service.CompleteQueryResponse]]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + Awaitable[~.CompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + 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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py new file mode 100644 index 00000000..e9a7be2f --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ControlServiceClient +from .async_client import ControlServiceAsyncClient + +__all__ = ( + 'ControlServiceClient', + 'ControlServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py new file mode 100644 index 00000000..5d3cfeb7 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py @@ -0,0 +1,742 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.control_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.cloud.retail_v2beta.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport +from .client import ControlServiceClient + + +class ControlServiceAsyncClient: + """Service for modifying Control.""" + + _client: ControlServiceClient + + DEFAULT_ENDPOINT = ControlServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ControlServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(ControlServiceClient.catalog_path) + parse_catalog_path = staticmethod(ControlServiceClient.parse_catalog_path) + control_path = staticmethod(ControlServiceClient.control_path) + parse_control_path = staticmethod(ControlServiceClient.parse_control_path) + common_billing_account_path = staticmethod(ControlServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ControlServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ControlServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ControlServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ControlServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ControlServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ControlServiceClient.common_project_path) + parse_common_project_path = staticmethod(ControlServiceClient.parse_common_project_path) + common_location_path = staticmethod(ControlServiceClient.common_location_path) + parse_common_location_path = staticmethod(ControlServiceClient.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: + ControlServiceAsyncClient: The constructed client. + """ + return ControlServiceClient.from_service_account_info.__func__(ControlServiceAsyncClient, 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: + ControlServiceAsyncClient: The constructed client. + """ + return ControlServiceClient.from_service_account_file.__func__(ControlServiceAsyncClient, 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 variabel 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 ControlServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ControlServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ControlServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ControlServiceClient).get_transport_class, type(ControlServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ControlServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the control service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ControlServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ControlServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_control(self, + request: Union[control_service.CreateControlRequest, dict] = None, + *, + parent: str = None, + control: gcr_control.Control = None, + control_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Creates a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_create_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = await client.create_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateControlRequest, dict]): + The request object. Request for CreateControl method. + parent (:class:`str`): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control (:class:`google.cloud.retail_v2beta.types.Control`): + Required. The Control to create. + This corresponds to the ``control`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control_id (:class:`str`): + Required. The ID to use for the Control, which will + become the final component of the Control's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``control_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.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, control, control_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.CreateControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if control is not None: + request.control = control + if control_id is not None: + request.control_id = control_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_control(self, + request: Union[control_service.DeleteControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_delete_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteControlRequest( + name="name_value", + ) + + # Make the request + await client.delete_control(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteControlRequest, dict]): + The request object. Request for DeleteControl method. + name (:class:`str`): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.DeleteControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_control(self, + request: Union[control_service.UpdateControlRequest, dict] = None, + *, + control: gcr_control.Control = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Updates a Control. + + [Control][google.cloud.retail.v2beta.Control] cannot be set to a + different oneof field, if so an INVALID_ARGUMENT is returned. If + the [Control][google.cloud.retail.v2beta.Control] to delete does + not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateControlRequest( + control=control, + ) + + # Make the request + response = await client.update_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateControlRequest, dict]): + The request object. Request for UpdateControl method. + control (:class:`google.cloud.retail_v2beta.types.Control`): + Required. The Control to update. + This corresponds to the ``control`` 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 + [Control][google.cloud.retail.v2beta.Control] to update. + The following are NOT supported: + + - [Control.name][google.cloud.retail.v2beta.Control.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([control, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.UpdateControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if control is not None: + request.control = control + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("control.name", request.control.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_control(self, + request: Union[control_service.GetControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> control.Control: + r"""Gets a Control. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetControlRequest( + name="name_value", + ) + + # Make the request + response = await client.get_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetControlRequest, dict]): + The request object. Request for GetControl method. + name (:class:`str`): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.GetControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_controls(self, + request: Union[control_service.ListControlsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListControlsAsyncPager: + r"""Lists all Controls linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_list_controls(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListControlsRequest, dict]): + The request object. Request for ListControls method. + parent (:class:`str`): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.control_service.pagers.ListControlsAsyncPager: + Response for ListControls method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.ListControlsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_controls, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListControlsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ControlServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py new file mode 100644 index 00000000..fbad615b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py @@ -0,0 +1,951 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.control_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.cloud.retail_v2beta.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ControlServiceGrpcTransport +from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport + + +class ControlServiceClientMeta(type): + """Metaclass for the ControlService 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[ControlServiceTransport]] + _transport_registry["grpc"] = ControlServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ControlServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ControlServiceTransport]: + """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 ControlServiceClient(metaclass=ControlServiceClientMeta): + """Service for modifying Control.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ControlServiceClient: 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: + ControlServiceClient: 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) -> ControlServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ControlServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def control_path(project: str,location: str,catalog: str,control: str,) -> str: + """Returns a fully-qualified control string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) + + @staticmethod + def parse_control_path(path: str) -> Dict[str,str]: + """Parses a control path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/controls/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ControlServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the control service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ControlServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ControlServiceTransport): + # transport is a ControlServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_control(self, + request: Union[control_service.CreateControlRequest, dict] = None, + *, + parent: str = None, + control: gcr_control.Control = None, + control_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Creates a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_create_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = client.create_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateControlRequest, dict]): + The request object. Request for CreateControl method. + parent (str): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control (google.cloud.retail_v2beta.types.Control): + Required. The Control to create. + This corresponds to the ``control`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control_id (str): + Required. The ID to use for the Control, which will + become the final component of the Control's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``control_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.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, control, control_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.CreateControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.CreateControlRequest): + request = control_service.CreateControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if control is not None: + request.control = control + if control_id is not None: + request.control_id = control_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_control(self, + request: Union[control_service.DeleteControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_delete_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteControlRequest( + name="name_value", + ) + + # Make the request + client.delete_control(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteControlRequest, dict]): + The request object. Request for DeleteControl method. + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.DeleteControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.DeleteControlRequest): + request = control_service.DeleteControlRequest(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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_control(self, + request: Union[control_service.UpdateControlRequest, dict] = None, + *, + control: gcr_control.Control = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Updates a Control. + + [Control][google.cloud.retail.v2beta.Control] cannot be set to a + different oneof field, if so an INVALID_ARGUMENT is returned. If + the [Control][google.cloud.retail.v2beta.Control] to delete does + not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateControlRequest( + control=control, + ) + + # Make the request + response = client.update_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateControlRequest, dict]): + The request object. Request for UpdateControl method. + control (google.cloud.retail_v2beta.types.Control): + Required. The Control to update. + This corresponds to the ``control`` 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 + [Control][google.cloud.retail.v2beta.Control] to update. + The following are NOT supported: + + - [Control.name][google.cloud.retail.v2beta.Control.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([control, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.UpdateControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.UpdateControlRequest): + request = control_service.UpdateControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if control is not None: + request.control = control + 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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("control.name", request.control.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_control(self, + request: Union[control_service.GetControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> control.Control: + r"""Gets a Control. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetControlRequest( + name="name_value", + ) + + # Make the request + response = client.get_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetControlRequest, dict]): + The request object. Request for GetControl method. + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.GetControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.GetControlRequest): + request = control_service.GetControlRequest(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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_controls(self, + request: Union[control_service.ListControlsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListControlsPager: + r"""Lists all Controls linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_list_controls(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListControlsRequest, dict]): + The request object. Request for ListControls method. + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.control_service.pagers.ListControlsPager: + Response for ListControls method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.ListControlsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.ListControlsRequest): + request = control_service.ListControlsRequest(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_controls] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListControlsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ControlServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py new file mode 100644 index 00000000..f51a3970 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control_service + + +class ListControlsPager: + """A pager for iterating through ``list_controls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListControlsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``controls`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListControls`` requests and continue to iterate + through the ``controls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListControlsResponse` + 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[..., control_service.ListControlsResponse], + request: control_service.ListControlsRequest, + response: control_service.ListControlsResponse, + *, + 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.retail_v2beta.types.ListControlsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListControlsResponse): + 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 = control_service.ListControlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[control_service.ListControlsResponse]: + 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[control.Control]: + for page in self.pages: + yield from page.controls + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListControlsAsyncPager: + """A pager for iterating through ``list_controls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListControlsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``controls`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListControls`` requests and continue to iterate + through the ``controls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListControlsResponse` + 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[control_service.ListControlsResponse]], + request: control_service.ListControlsRequest, + response: control_service.ListControlsResponse, + *, + 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.retail_v2beta.types.ListControlsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListControlsResponse): + 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 = control_service.ListControlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[control_service.ListControlsResponse]: + 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[control.Control]: + async def async_generator(): + async for page in self.pages: + for response in page.controls: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py new file mode 100644 index 00000000..3622876b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ControlServiceTransport +from .grpc import ControlServiceGrpcTransport +from .grpc_asyncio import ControlServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ControlServiceTransport]] +_transport_registry['grpc'] = ControlServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ControlServiceGrpcAsyncIOTransport + +__all__ = ( + 'ControlServiceTransport', + 'ControlServiceGrpcTransport', + 'ControlServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py new file mode 100644 index 00000000..2424eb4a --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ControlServiceTransport(abc.ABC): + """Abstract transport class for ControlService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_control: gapic_v1.method.wrap_method( + self.create_control, + default_timeout=None, + client_info=client_info, + ), + self.delete_control: gapic_v1.method.wrap_method( + self.delete_control, + default_timeout=None, + client_info=client_info, + ), + self.update_control: gapic_v1.method.wrap_method( + self.update_control, + default_timeout=None, + client_info=client_info, + ), + self.get_control: gapic_v1.method.wrap_method( + self.get_control, + default_timeout=None, + client_info=client_info, + ), + self.list_controls: gapic_v1.method.wrap_method( + self.list_controls, + 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 create_control(self) -> Callable[ + [control_service.CreateControlRequest], + Union[ + gcr_control.Control, + Awaitable[gcr_control.Control] + ]]: + raise NotImplementedError() + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + Union[ + gcr_control.Control, + Awaitable[gcr_control.Control] + ]]: + raise NotImplementedError() + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + Union[ + control.Control, + Awaitable[control.Control] + ]]: + raise NotImplementedError() + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + Union[ + control_service.ListControlsResponse, + Awaitable[control_service.ListControlsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ControlServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py new file mode 100644 index 00000000..64b13dfb --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py @@ -0,0 +1,382 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO + + +class ControlServiceGrpcTransport(ControlServiceTransport): + """gRPC backend transport for ControlService. + + Service for modifying Control. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_control(self) -> Callable[ + [control_service.CreateControlRequest], + gcr_control.Control]: + r"""Return a callable for the create control method over gRPC. + + Creates a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['create_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/CreateControl', + request_serializer=control_service.CreateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['create_control'] + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete control method over gRPC. + + Deletes a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteControlRequest], + ~.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_control' not in self._stubs: + self._stubs['delete_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/DeleteControl', + request_serializer=control_service.DeleteControlRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_control'] + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + gcr_control.Control]: + r"""Return a callable for the update control method over gRPC. + + Updates a Control. + + [Control][google.cloud.retail.v2beta.Control] cannot be set to a + different oneof field, if so an INVALID_ARGUMENT is returned. If + the [Control][google.cloud.retail.v2beta.Control] to delete does + not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['update_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/UpdateControl', + request_serializer=control_service.UpdateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['update_control'] + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + control.Control]: + r"""Return a callable for the get control method over gRPC. + + Gets a Control. + + Returns: + Callable[[~.GetControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['get_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/GetControl', + request_serializer=control_service.GetControlRequest.serialize, + response_deserializer=control.Control.deserialize, + ) + return self._stubs['get_control'] + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + control_service.ListControlsResponse]: + r"""Return a callable for the list controls method over gRPC. + + Lists all Controls linked to this catalog. + + Returns: + Callable[[~.ListControlsRequest], + ~.ListControlsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_controls' not in self._stubs: + self._stubs['list_controls'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/ListControls', + request_serializer=control_service.ListControlsRequest.serialize, + response_deserializer=control_service.ListControlsResponse.deserialize, + ) + return self._stubs['list_controls'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ControlServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..701a8de1 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ControlServiceGrpcTransport + + +class ControlServiceGrpcAsyncIOTransport(ControlServiceTransport): + """gRPC AsyncIO backend transport for ControlService. + + Service for modifying Control. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_control(self) -> Callable[ + [control_service.CreateControlRequest], + Awaitable[gcr_control.Control]]: + r"""Return a callable for the create control method over gRPC. + + Creates a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['create_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/CreateControl', + request_serializer=control_service.CreateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['create_control'] + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete control method over gRPC. + + Deletes a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteControlRequest], + 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_control' not in self._stubs: + self._stubs['delete_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/DeleteControl', + request_serializer=control_service.DeleteControlRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_control'] + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + Awaitable[gcr_control.Control]]: + r"""Return a callable for the update control method over gRPC. + + Updates a Control. + + [Control][google.cloud.retail.v2beta.Control] cannot be set to a + different oneof field, if so an INVALID_ARGUMENT is returned. If + the [Control][google.cloud.retail.v2beta.Control] to delete does + not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['update_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/UpdateControl', + request_serializer=control_service.UpdateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['update_control'] + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + Awaitable[control.Control]]: + r"""Return a callable for the get control method over gRPC. + + Gets a Control. + + Returns: + Callable[[~.GetControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['get_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/GetControl', + request_serializer=control_service.GetControlRequest.serialize, + response_deserializer=control.Control.deserialize, + ) + return self._stubs['get_control'] + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + Awaitable[control_service.ListControlsResponse]]: + r"""Return a callable for the list controls method over gRPC. + + Lists all Controls linked to this catalog. + + Returns: + Callable[[~.ListControlsRequest], + Awaitable[~.ListControlsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_controls' not in self._stubs: + self._stubs['list_controls'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/ListControls', + request_serializer=control_service.ListControlsRequest.serialize, + response_deserializer=control_service.ListControlsResponse.deserialize, + ) + return self._stubs['list_controls'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ControlServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py new file mode 100644 index 00000000..7c079c80 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import PredictionServiceClient +from .async_client import PredictionServiceAsyncClient + +__all__ = ( + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py new file mode 100644 index 00000000..d8a1a148 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport +from .client import PredictionServiceClient + + +class PredictionServiceAsyncClient: + """Service for making recommendation prediction.""" + + _client: PredictionServiceClient + + DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT + + product_path = staticmethod(PredictionServiceClient.product_path) + parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) + common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(PredictionServiceClient.common_project_path) + parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) + common_location_path = staticmethod(PredictionServiceClient.common_location_path) + parse_common_location_path = staticmethod(PredictionServiceClient.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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PredictionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_predict(): + # Create a client + client = retail_v2beta.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + request = prediction_service.PredictRequest(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.predict, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py new file mode 100644 index 00000000..6eb343ca --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py @@ -0,0 +1,480 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionServiceGrpcTransport +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +class PredictionServiceClientMeta(type): + """Metaclass for the PredictionService 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[PredictionServiceTransport]] + _transport_registry["grpc"] = PredictionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PredictionServiceTransport]: + """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): + """Service for making recommendation prediction.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PredictionServiceClient: 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: + PredictionServiceClient: 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) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PredictionServiceTransport): + # transport is a PredictionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_predict(): + # Create a client + client = retail_v2beta.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a prediction_service.PredictRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_service.PredictRequest): + request = prediction_service.PredictRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.predict] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py new file mode 100644 index 00000000..bb65c664 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PredictionServiceTransport +from .grpc import PredictionServiceGrpcTransport +from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] +_transport_registry['grpc'] = PredictionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport + +__all__ = ( + 'PredictionServiceTransport', + 'PredictionServiceGrpcTransport', + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py new file mode 100644 index 00000000..12f65a6c --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PredictionServiceTransport(abc.ABC): + """Abstract transport class for PredictionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.predict: gapic_v1.method.wrap_method( + self.predict, + 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + Union[ + prediction_service.PredictResponse, + Awaitable[prediction_service.PredictResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'PredictionServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py new file mode 100644 index 00000000..98c69839 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py @@ -0,0 +1,264 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO + + +class PredictionServiceGrpcTransport(PredictionServiceTransport): + """gRPC backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + prediction_service.PredictResponse]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + ~.PredictResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'PredictionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..11fce51c --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import PredictionServiceGrpcTransport + + +class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): + """gRPC AsyncIO backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + Awaitable[prediction_service.PredictResponse]]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + Awaitable[~.PredictResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py new file mode 100644 index 00000000..0fa6330a --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ProductServiceClient +from .async_client import ProductServiceAsyncClient + +__all__ = ( + 'ProductServiceClient', + 'ProductServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py new file mode 100644 index 00000000..493936e0 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py @@ -0,0 +1,1692 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.services.product_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.cloud.retail_v2beta.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport +from .client import ProductServiceClient + + +class ProductServiceAsyncClient: + """Service for ingesting [Product][google.cloud.retail.v2beta.Product] + information of the customer's website. + """ + + _client: ProductServiceClient + + DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(ProductServiceClient.branch_path) + parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) + product_path = staticmethod(ProductServiceClient.product_path) + parse_product_path = staticmethod(ProductServiceClient.parse_product_path) + common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProductServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProductServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProductServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProductServiceClient.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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ProductServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ProductServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_create_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`google.cloud.retail_v2beta.types.Product`): + Required. The + [Product][google.cloud.retail.v2beta.Product] to create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + Required. The ID to use for the + [Product][google.cloud.retail.v2beta.Product], which + will become the final component of the + [Product.name][google.cloud.retail.v2beta.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This field must be unique among all + [Product][google.cloud.retail.v2beta.Product]s with the + same + [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Product][google.cloud.retail.v2beta.Product] 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.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Gets a list of [Product][google.cloud.retail.v2beta.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_list_products(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2beta.Product]s under + this branch, regardless of whether or not this branch + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.product_service.pagers.ListProductsAsyncPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (:class:`google.cloud.retail_v2beta.types.Product`): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2beta.Product] to update. + The immutable and output only fields are NOT supported. + If not set, all supported fields (the fields that are + neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_delete_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2beta.Product] to + delete can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product] member nor + a + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] with more + than one + [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2beta.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2beta.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2beta.Product]s to be + successfully updated. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_import_products(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2beta.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2beta.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_set_inventory(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2beta.Product() + inventory.title = "title_value" + + request = retail_v2beta.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (:class:`google.cloud.retail_v2beta.types.Product`): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product] named in + [Product.name][google.cloud.retail.v2beta.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2beta.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2beta.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.SetInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_inventory, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + async def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [AddFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_add_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [AddLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_remove_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py new file mode 100644 index 00000000..fa4ba1f6 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py @@ -0,0 +1,1895 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.services.product_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.cloud.retail_v2beta.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductServiceGrpcTransport +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +class ProductServiceClientMeta(type): + """Metaclass for the ProductService 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[ProductServiceTransport]] + _transport_registry["grpc"] = ProductServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ProductServiceTransport]: + """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 ProductServiceClient(metaclass=ProductServiceClientMeta): + """Service for ingesting [Product][google.cloud.retail.v2beta.Product] + information of the customer's website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProductServiceClient: 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: + ProductServiceClient: 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) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ProductServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProductServiceTransport): + # transport is a ProductServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_create_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (google.cloud.retail_v2beta.types.Product): + Required. The + [Product][google.cloud.retail.v2beta.Product] to create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2beta.Product], which + will become the final component of the + [Product.name][google.cloud.retail.v2beta.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This field must be unique among all + [Product][google.cloud.retail.v2beta.Product]s with the + same + [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.CreateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.CreateProductRequest): + request = product_service.CreateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Product][google.cloud.retail.v2beta.Product] 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.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.GetProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.GetProductRequest): + request = product_service.GetProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Gets a list of [Product][google.cloud.retail.v2beta.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_list_products(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2beta.Product]s under + this branch, regardless of whether or not this branch + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.product_service.pagers.ListProductsPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.ListProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.ListProductsRequest): + request = product_service.ListProductsRequest(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_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (google.cloud.retail_v2beta.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2beta.Product] to update. + The immutable and output only fields are NOT supported. + If not set, all supported fields (the fields that are + neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.UpdateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.UpdateProductRequest): + request = product_service.UpdateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + 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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_delete_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2beta.Product] to + delete can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product] member nor + a + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] with more + than one + [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2beta.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.DeleteProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.DeleteProductRequest): + request = product_service.DeleteProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2beta.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2beta.Product]s to be + successfully updated. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_import_products(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2beta.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportProductsRequest): + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2beta.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_set_inventory(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2beta.Product() + inventory.title = "title_value" + + request = retail_v2beta.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (google.cloud.retail_v2beta.types.Product): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product] named in + [Product.name][google.cloud.retail.v2beta.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2beta.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2beta.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.SetInventoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.SetInventoryRequest): + request = product_service.SetInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_add_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [AddFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddFulfillmentPlacesRequest): + request = product_service.AddFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): + request = product_service.RemoveFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_add_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [AddLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddLocalInventoriesRequest): + request = product_service.AddLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_remove_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveLocalInventoriesRequest): + request = product_service.RemoveLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py new file mode 100644 index 00000000..552c2bfa --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product_service + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListProductsResponse` + 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[..., product_service.ListProductsResponse], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2beta.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[product_service.ListProductsResponse]: + 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[product.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListProductsResponse` + 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[product_service.ListProductsResponse]], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2beta.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: + 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[product.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py new file mode 100644 index 00000000..db824dec --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ProductServiceTransport +from .grpc import ProductServiceGrpcTransport +from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] +_transport_registry['grpc'] = ProductServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport + +__all__ = ( + 'ProductServiceTransport', + 'ProductServiceGrpcTransport', + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py new file mode 100644 index 00000000..325ba99e --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py @@ -0,0 +1,312 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ProductServiceTransport(abc.ABC): + """Abstract transport class for ProductService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_product: gapic_v1.method.wrap_method( + self.create_product, + default_timeout=None, + client_info=client_info, + ), + self.get_product: gapic_v1.method.wrap_method( + self.get_product, + default_timeout=None, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + default_timeout=None, + client_info=client_info, + ), + self.update_product: gapic_v1.method.wrap_method( + self.update_product, + default_timeout=None, + client_info=client_info, + ), + self.delete_product: gapic_v1.method.wrap_method( + self.delete_product, + default_timeout=None, + client_info=client_info, + ), + self.import_products: gapic_v1.method.wrap_method( + self.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.set_inventory: gapic_v1.method.wrap_method( + self.set_inventory, + default_timeout=None, + client_info=client_info, + ), + self.add_fulfillment_places: gapic_v1.method.wrap_method( + self.add_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.remove_fulfillment_places: gapic_v1.method.wrap_method( + self.remove_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.add_local_inventories: gapic_v1.method.wrap_method( + self.add_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.remove_local_inventories: gapic_v1.method.wrap_method( + self.remove_local_inventories, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Union[ + product.Product, + Awaitable[product.Product] + ]]: + raise NotImplementedError() + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Union[ + product_service.ListProductsResponse, + Awaitable[product_service.ListProductsResponse] + ]]: + raise NotImplementedError() + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProductServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py new file mode 100644 index 00000000..8df65e63 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py @@ -0,0 +1,680 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO + + +class ProductServiceGrpcTransport(ProductServiceTransport): + """gRPC backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2beta.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + gcr_product.Product]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.CreateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + product.Product]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + product_service.ListProductsResponse]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2beta.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + gcr_product.Product]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + ~.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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2beta.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2beta.Product]s to be + successfully updated. + + Returns: + Callable[[~.ImportProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + operations_pb2.Operation]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2beta.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProductServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..9ccfc3ee --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py @@ -0,0 +1,679 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductServiceGrpcTransport + + +class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): + """gRPC AsyncIO backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2beta.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.CreateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Awaitable[product.Product]]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Awaitable[product_service.ListProductsResponse]]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2beta.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + 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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2beta.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2beta.Product]s to be + successfully updated. + + Returns: + Callable[[~.ImportProductsRequest], + 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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2beta.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + 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 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + 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 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + 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 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + 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 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py new file mode 100644 index 00000000..2f63fc22 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SearchServiceClient +from .async_client import SearchServiceAsyncClient + +__all__ = ( + 'SearchServiceClient', + 'SearchServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py new file mode 100644 index 00000000..4943cff9 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.search_service import pagers +from google.cloud.retail_v2beta.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .client import SearchServiceClient + + +class SearchServiceAsyncClient: + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: SearchServiceClient + + DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(SearchServiceClient.branch_path) + parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + product_path = staticmethod(SearchServiceClient.product_path) + parse_product_path = staticmethod(SearchServiceClient.parse_product_path) + common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(SearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SearchServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAsyncPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_search(): + # Create a client + client = retail_v2beta.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.search_service.pagers.SearchAsyncPager: + Response message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py new file mode 100644 index 00000000..7c944320 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py @@ -0,0 +1,513 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.search_service import pagers +from google.cloud.retail_v2beta.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SearchServiceGrpcTransport +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +class SearchServiceClientMeta(type): + """Metaclass for the SearchService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] + _transport_registry["grpc"] = SearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SearchServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SearchServiceClient(metaclass=SearchServiceClientMeta): + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SearchServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SearchServiceTransport): + # transport is a SearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_search(): + # Create a client + client = retail_v2beta.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.search_service.pagers.SearchPager: + Response message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a search_service.SearchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py new file mode 100644 index 00000000..6ff03162 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import search_service + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2beta.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2beta.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py new file mode 100644 index 00000000..7917cd1d --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SearchServiceTransport +from .grpc import SearchServiceGrpcTransport +from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] +_transport_registry['grpc'] = SearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport + +__all__ = ( + 'SearchServiceTransport', + 'SearchServiceGrpcTransport', + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py new file mode 100644 index 00000000..c084a7f1 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import search_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SearchServiceTransport(abc.ABC): + """Abstract transport class for SearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search: gapic_v1.method.wrap_method( + self.search, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Union[ + search_service.SearchResponse, + Awaitable[search_service.SearchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SearchServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py new file mode 100644 index 00000000..74a10421 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py @@ -0,0 +1,270 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO + + +class SearchServiceGrpcTransport(SearchServiceTransport): + """gRPC backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..3dfd4aa1 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SearchServiceGrpcTransport + + +class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): + """gRPC AsyncIO backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Awaitable[search_service.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py new file mode 100644 index 00000000..d1a0a023 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ServingConfigServiceClient +from .async_client import ServingConfigServiceAsyncClient + +__all__ = ( + 'ServingConfigServiceClient', + 'ServingConfigServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py new file mode 100644 index 00000000..cfdace1d --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py @@ -0,0 +1,954 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.serving_config_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport +from .client import ServingConfigServiceClient + + +class ServingConfigServiceAsyncClient: + """Service for modifying ServingConfig.""" + + _client: ServingConfigServiceClient + + DEFAULT_ENDPOINT = ServingConfigServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ServingConfigServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(ServingConfigServiceClient.catalog_path) + parse_catalog_path = staticmethod(ServingConfigServiceClient.parse_catalog_path) + serving_config_path = staticmethod(ServingConfigServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(ServingConfigServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(ServingConfigServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ServingConfigServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ServingConfigServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ServingConfigServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ServingConfigServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ServingConfigServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ServingConfigServiceClient.common_project_path) + parse_common_project_path = staticmethod(ServingConfigServiceClient.parse_common_project_path) + common_location_path = staticmethod(ServingConfigServiceClient.common_location_path) + parse_common_location_path = staticmethod(ServingConfigServiceClient.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: + ServingConfigServiceAsyncClient: The constructed client. + """ + return ServingConfigServiceClient.from_service_account_info.__func__(ServingConfigServiceAsyncClient, 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: + ServingConfigServiceAsyncClient: The constructed client. + """ + return ServingConfigServiceClient.from_service_account_file.__func__(ServingConfigServiceAsyncClient, 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 variabel 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 ServingConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ServingConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ServingConfigServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ServingConfigServiceClient).get_transport_class, type(ServingConfigServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ServingConfigServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the serving config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ServingConfigServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ServingConfigServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_serving_config(self, + request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, + *, + parent: str = None, + serving_config: gcr_serving_config.ServingConfig = None, + serving_config_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_create_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = await client.create_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateServingConfigRequest, dict]): + The request object. Request for CreateServingConfig + method. + parent (:class:`str`): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config (:class:`google.cloud.retail_v2beta.types.ServingConfig`): + Required. The ServingConfig to + create. + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config_id (:class:`str`): + Required. The ID to use for the ServingConfig, which + will become the final component of the ServingConfig's + resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``serving_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, serving_config, serving_config_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.CreateServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if serving_config is not None: + request.serving_config = serving_config + if serving_config_id is not None: + request.serving_config_id = serving_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_serving_config(self, + request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_delete_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_serving_config(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteServingConfigRequest, dict]): + The request object. Request for DeleteServingConfig + method. + name (:class:`str`): + Required. The resource name of the ServingConfig to + delete. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.DeleteServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_serving_config(self, + request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, + *, + serving_config: gcr_serving_config.ServingConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Updates a ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = await client.update_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateServingConfigRequest, dict]): + The request object. Request for UpdateServingConfig + method. + serving_config (:class:`google.cloud.retail_v2beta.types.ServingConfig`): + Required. The ServingConfig to + update. + + This corresponds to the ``serving_config`` 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 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.UpdateServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config.name", request.serving_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_serving_config(self, + request: Union[serving_config_service.GetServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> serving_config.ServingConfig: + r"""Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetServingConfigRequest, dict]): + The request object. Request for GetServingConfig method. + name (:class:`str`): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.GetServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_serving_configs(self, + request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServingConfigsAsyncPager: + r"""Lists all ServingConfigs linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_list_serving_configs(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListServingConfigsRequest, dict]): + The request object. Request for ListServingConfigs + method. + parent (:class:`str`): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager: + Response for ListServingConfigs + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.ListServingConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_serving_configs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServingConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_control(self, + request: Union[serving_config_service.AddControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_add_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.add_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddControlRequest, dict]): + The request object. Request for AddControl method. + serving_config (:class:`str`): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.AddControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_control(self, + request: Union[serving_config_service.RemoveControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_remove_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.remove_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveControlRequest, dict]): + The request object. Request for RemoveControl method. + serving_config (:class:`str`): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.RemoveControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServingConfigServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py new file mode 100644 index 00000000..bca31abe --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py @@ -0,0 +1,1163 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.serving_config_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ServingConfigServiceGrpcTransport +from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport + + +class ServingConfigServiceClientMeta(type): + """Metaclass for the ServingConfigService 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[ServingConfigServiceTransport]] + _transport_registry["grpc"] = ServingConfigServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ServingConfigServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ServingConfigServiceTransport]: + """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 ServingConfigServiceClient(metaclass=ServingConfigServiceClientMeta): + """Service for modifying ServingConfig.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServingConfigServiceClient: 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: + ServingConfigServiceClient: 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) -> ServingConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ServingConfigServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,catalog: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ServingConfigServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the serving config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ServingConfigServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ServingConfigServiceTransport): + # transport is a ServingConfigServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_serving_config(self, + request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, + *, + parent: str = None, + serving_config: gcr_serving_config.ServingConfig = None, + serving_config_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_create_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = client.create_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateServingConfigRequest, dict]): + The request object. Request for CreateServingConfig + method. + parent (str): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config (google.cloud.retail_v2beta.types.ServingConfig): + Required. The ServingConfig to + create. + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config_id (str): + Required. The ID to use for the ServingConfig, which + will become the final component of the ServingConfig's + resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``serving_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, serving_config, serving_config_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.CreateServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.CreateServingConfigRequest): + request = serving_config_service.CreateServingConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if serving_config is not None: + request.serving_config = serving_config + if serving_config_id is not None: + request.serving_config_id = serving_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_serving_config(self, + request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_delete_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_serving_config(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteServingConfigRequest, dict]): + The request object. Request for DeleteServingConfig + method. + name (str): + Required. The resource name of the ServingConfig to + delete. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.DeleteServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.DeleteServingConfigRequest): + request = serving_config_service.DeleteServingConfigRequest(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_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_serving_config(self, + request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, + *, + serving_config: gcr_serving_config.ServingConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Updates a ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = client.update_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateServingConfigRequest, dict]): + The request object. Request for UpdateServingConfig + method. + serving_config (google.cloud.retail_v2beta.types.ServingConfig): + Required. The ServingConfig to + update. + + This corresponds to the ``serving_config`` 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 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.UpdateServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.UpdateServingConfigRequest): + request = serving_config_service.UpdateServingConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config.name", request.serving_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_serving_config(self, + request: Union[serving_config_service.GetServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> serving_config.ServingConfig: + r"""Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetServingConfigRequest, dict]): + The request object. Request for GetServingConfig method. + name (str): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.GetServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.GetServingConfigRequest): + request = serving_config_service.GetServingConfigRequest(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_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_serving_configs(self, + request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServingConfigsPager: + r"""Lists all ServingConfigs linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_list_serving_configs(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListServingConfigsRequest, dict]): + The request object. Request for ListServingConfigs + method. + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsPager: + Response for ListServingConfigs + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.ListServingConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.ListServingConfigsRequest): + request = serving_config_service.ListServingConfigsRequest(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_serving_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListServingConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_control(self, + request: Union[serving_config_service.AddControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_add_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.add_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddControlRequest, dict]): + The request object. Request for AddControl method. + serving_config (str): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.AddControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.AddControlRequest): + request = serving_config_service.AddControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_control(self, + request: Union[serving_config_service.RemoveControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_remove_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.remove_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveControlRequest, dict]): + The request object. Request for RemoveControl method. + serving_config (str): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.RemoveControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.RemoveControlRequest): + request = serving_config_service.RemoveControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServingConfigServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py new file mode 100644 index 00000000..a45bf88c --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config_service + + +class ListServingConfigsPager: + """A pager for iterating through ``list_serving_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``serving_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServingConfigs`` requests and continue to iterate + through the ``serving_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` + 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[..., serving_config_service.ListServingConfigsResponse], + request: serving_config_service.ListServingConfigsRequest, + response: serving_config_service.ListServingConfigsResponse, + *, + 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.retail_v2beta.types.ListServingConfigsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListServingConfigsResponse): + 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 = serving_config_service.ListServingConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[serving_config_service.ListServingConfigsResponse]: + 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[serving_config.ServingConfig]: + for page in self.pages: + yield from page.serving_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServingConfigsAsyncPager: + """A pager for iterating through ``list_serving_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``serving_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServingConfigs`` requests and continue to iterate + through the ``serving_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` + 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[serving_config_service.ListServingConfigsResponse]], + request: serving_config_service.ListServingConfigsRequest, + response: serving_config_service.ListServingConfigsResponse, + *, + 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.retail_v2beta.types.ListServingConfigsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListServingConfigsResponse): + 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 = serving_config_service.ListServingConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[serving_config_service.ListServingConfigsResponse]: + 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[serving_config.ServingConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.serving_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py new file mode 100644 index 00000000..3726ac83 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ServingConfigServiceTransport +from .grpc import ServingConfigServiceGrpcTransport +from .grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ServingConfigServiceTransport]] +_transport_registry['grpc'] = ServingConfigServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ServingConfigServiceGrpcAsyncIOTransport + +__all__ = ( + 'ServingConfigServiceTransport', + 'ServingConfigServiceGrpcTransport', + 'ServingConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py new file mode 100644 index 00000000..b8fc6e2b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ServingConfigServiceTransport(abc.ABC): + """Abstract transport class for ServingConfigService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_serving_config: gapic_v1.method.wrap_method( + self.create_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_serving_config: gapic_v1.method.wrap_method( + self.delete_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.update_serving_config: gapic_v1.method.wrap_method( + self.update_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.get_serving_config: gapic_v1.method.wrap_method( + self.get_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.list_serving_configs: gapic_v1.method.wrap_method( + self.list_serving_configs, + default_timeout=None, + client_info=client_info, + ), + self.add_control: gapic_v1.method.wrap_method( + self.add_control, + default_timeout=None, + client_info=client_info, + ), + self.remove_control: gapic_v1.method.wrap_method( + self.remove_control, + 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 create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + Union[ + serving_config.ServingConfig, + Awaitable[serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + Union[ + serving_config_service.ListServingConfigsResponse, + Awaitable[serving_config_service.ListServingConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ServingConfigServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py new file mode 100644 index 00000000..309a486a --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py @@ -0,0 +1,440 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO + + +class ServingConfigServiceGrpcTransport(ServingConfigServiceTransport): + """gRPC backend transport for ServingConfigService. + + Service for modifying ServingConfig. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the create serving config method over gRPC. + + Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + Returns: + Callable[[~.CreateServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/CreateServingConfig', + request_serializer=serving_config_service.CreateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['create_serving_config'] + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete serving config method over gRPC. + + Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.DeleteServingConfigRequest], + ~.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_serving_config' not in self._stubs: + self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/DeleteServingConfig', + request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_serving_config'] + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the update serving config method over gRPC. + + Updates a ServingConfig. + + Returns: + Callable[[~.UpdateServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/UpdateServingConfig', + request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['update_serving_config'] + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + serving_config.ServingConfig]: + r"""Return a callable for the get serving config method over gRPC. + + Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.GetServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/GetServingConfig', + request_serializer=serving_config_service.GetServingConfigRequest.serialize, + response_deserializer=serving_config.ServingConfig.deserialize, + ) + return self._stubs['get_serving_config'] + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + serving_config_service.ListServingConfigsResponse]: + r"""Return a callable for the list serving configs method over gRPC. + + Lists all ServingConfigs linked to this catalog. + + Returns: + Callable[[~.ListServingConfigsRequest], + ~.ListServingConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: + self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/ListServingConfigs', + request_serializer=serving_config_service.ListServingConfigsRequest.serialize, + response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, + ) + return self._stubs['list_serving_configs'] + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the add control method over gRPC. + + Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + Returns: + Callable[[~.AddControlRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_control' not in self._stubs: + self._stubs['add_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/AddControl', + request_serializer=serving_config_service.AddControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['add_control'] + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the remove control method over gRPC. + + Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + Returns: + Callable[[~.RemoveControlRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_control' not in self._stubs: + self._stubs['remove_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/RemoveControl', + request_serializer=serving_config_service.RemoveControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['remove_control'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ServingConfigServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..3cd75655 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py @@ -0,0 +1,439 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ServingConfigServiceGrpcTransport + + +class ServingConfigServiceGrpcAsyncIOTransport(ServingConfigServiceTransport): + """gRPC AsyncIO backend transport for ServingConfigService. + + Service for modifying ServingConfig. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the create serving config method over gRPC. + + Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + Returns: + Callable[[~.CreateServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/CreateServingConfig', + request_serializer=serving_config_service.CreateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['create_serving_config'] + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete serving config method over gRPC. + + Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.DeleteServingConfigRequest], + 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_serving_config' not in self._stubs: + self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/DeleteServingConfig', + request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_serving_config'] + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the update serving config method over gRPC. + + Updates a ServingConfig. + + Returns: + Callable[[~.UpdateServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/UpdateServingConfig', + request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['update_serving_config'] + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + Awaitable[serving_config.ServingConfig]]: + r"""Return a callable for the get serving config method over gRPC. + + Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.GetServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/GetServingConfig', + request_serializer=serving_config_service.GetServingConfigRequest.serialize, + response_deserializer=serving_config.ServingConfig.deserialize, + ) + return self._stubs['get_serving_config'] + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + Awaitable[serving_config_service.ListServingConfigsResponse]]: + r"""Return a callable for the list serving configs method over gRPC. + + Lists all ServingConfigs linked to this catalog. + + Returns: + Callable[[~.ListServingConfigsRequest], + Awaitable[~.ListServingConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: + self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/ListServingConfigs', + request_serializer=serving_config_service.ListServingConfigsRequest.serialize, + response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, + ) + return self._stubs['list_serving_configs'] + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the add control method over gRPC. + + Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + Returns: + Callable[[~.AddControlRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_control' not in self._stubs: + self._stubs['add_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/AddControl', + request_serializer=serving_config_service.AddControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['add_control'] + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the remove control method over gRPC. + + Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + Returns: + Callable[[~.RemoveControlRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_control' not in self._stubs: + self._stubs['remove_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/RemoveControl', + request_serializer=serving_config_service.RemoveControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['remove_control'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ServingConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py new file mode 100644 index 00000000..5f5171c1 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py new file mode 100644 index 00000000..24cdc934 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py @@ -0,0 +1,730 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on the customer + website. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(UserEventServiceClient.catalog_path) + parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) + product_path = staticmethod(UserEventServiceClient.product_path) + parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_write_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_collect_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_purge_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_import_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2beta.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_rejoin_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py new file mode 100644 index 00000000..a57e4e27 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py @@ -0,0 +1,930 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[UserEventServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on the customer + website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_write_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_collect_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_purge_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeUserEventsRequest): + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_import_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2beta.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_rejoin_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.RejoinUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.RejoinUserEventsRequest): + request = user_event_service.RejoinUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py new file mode 100644 index 00000000..f53ee5d7 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py new file mode 100644 index 00000000..bf9e4cfe --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py @@ -0,0 +1,235 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.rejoin_user_events: gapic_v1.method.wrap_method( + self.rejoin_user_events, + 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 write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + user_event.UserEvent, + Awaitable[user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py new file mode 100644 index 00000000..098839e0 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..7fbcb123 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + 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 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py new file mode 100644 index 00000000..62477503 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .catalog import ( + AttributesConfig, + Catalog, + CatalogAttribute, + CompletionConfig, + MerchantCenterLink, + MerchantCenterLinkingConfig, + ProductLevelConfig, +) +from .catalog_service import ( + AddCatalogAttributeRequest, + GetAttributesConfigRequest, + GetCompletionConfigRequest, + GetDefaultBranchRequest, + GetDefaultBranchResponse, + ListCatalogsRequest, + ListCatalogsResponse, + RemoveCatalogAttributeRequest, + ReplaceCatalogAttributeRequest, + SetDefaultBranchRequest, + UpdateAttributesConfigRequest, + UpdateCatalogRequest, + UpdateCompletionConfigRequest, +) +from .common import ( + Audience, + ColorInfo, + Condition, + CustomAttribute, + FulfillmentInfo, + Image, + Interval, + LocalInventory, + PriceInfo, + Rating, + Rule, + UserInfo, + AttributeConfigLevel, + SearchSolutionUseCase, + SolutionType, +) +from .completion_service import ( + CompleteQueryRequest, + CompleteQueryResponse, +) +from .control import ( + Control, +) +from .control_service import ( + CreateControlRequest, + DeleteControlRequest, + GetControlRequest, + ListControlsRequest, + ListControlsResponse, + UpdateControlRequest, +) +from .export_config import ( + ExportErrorsConfig, + ExportMetadata, + ExportProductsResponse, + ExportUserEventsResponse, +) +from .import_config import ( + BigQuerySource, + CompletionDataInputConfig, + GcsSource, + ImportCompletionDataRequest, + ImportCompletionDataResponse, + ImportErrorsConfig, + ImportMetadata, + ImportProductsRequest, + ImportProductsResponse, + ImportUserEventsRequest, + ImportUserEventsResponse, + ProductInlineSource, + ProductInputConfig, + UserEventImportSummary, + UserEventInlineSource, + UserEventInputConfig, +) +from .prediction_service import ( + PredictRequest, + PredictResponse, +) +from .product import ( + Product, +) +from .product_service import ( + AddFulfillmentPlacesMetadata, + AddFulfillmentPlacesRequest, + AddFulfillmentPlacesResponse, + AddLocalInventoriesMetadata, + AddLocalInventoriesRequest, + AddLocalInventoriesResponse, + CreateProductRequest, + DeleteProductRequest, + GetProductRequest, + ListProductsRequest, + ListProductsResponse, + RemoveFulfillmentPlacesMetadata, + RemoveFulfillmentPlacesRequest, + RemoveFulfillmentPlacesResponse, + RemoveLocalInventoriesMetadata, + RemoveLocalInventoriesRequest, + RemoveLocalInventoriesResponse, + SetInventoryMetadata, + SetInventoryRequest, + SetInventoryResponse, + UpdateProductRequest, +) +from .promotion import ( + Promotion, +) +from .purge_config import ( + PurgeMetadata, + PurgeUserEventsRequest, + PurgeUserEventsResponse, +) +from .search_service import ( + SearchRequest, + SearchResponse, +) +from .serving_config import ( + ServingConfig, +) +from .serving_config_service import ( + AddControlRequest, + CreateServingConfigRequest, + DeleteServingConfigRequest, + GetServingConfigRequest, + ListServingConfigsRequest, + ListServingConfigsResponse, + RemoveControlRequest, + UpdateServingConfigRequest, +) +from .user_event import ( + CompletionDetail, + ProductDetail, + PurchaseTransaction, + UserEvent, +) +from .user_event_service import ( + CollectUserEventRequest, + RejoinUserEventsMetadata, + RejoinUserEventsRequest, + RejoinUserEventsResponse, + WriteUserEventRequest, +) + +__all__ = ( + 'AttributesConfig', + 'Catalog', + 'CatalogAttribute', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'ProductLevelConfig', + 'AddCatalogAttributeRequest', + 'GetAttributesConfigRequest', + 'GetCompletionConfigRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + 'SetDefaultBranchRequest', + 'UpdateAttributesConfigRequest', + 'UpdateCatalogRequest', + 'UpdateCompletionConfigRequest', + 'Audience', + 'ColorInfo', + 'Condition', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'Rule', + 'UserInfo', + 'AttributeConfigLevel', + 'SearchSolutionUseCase', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Control', + 'CreateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + 'UpdateControlRequest', + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'ServingConfig', + 'AddControlRequest', + 'CreateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'RemoveControlRequest', + 'UpdateServingConfigRequest', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py new file mode 100644 index 00000000..8398213f --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py @@ -0,0 +1,528 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'ProductLevelConfig', + 'CatalogAttribute', + 'AttributesConfig', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'Catalog', + }, +) + + +class ProductLevelConfig(proto.Message): + r"""Configures what level the product should be uploaded with + regards to how users will be send events and how predictions + will be made. + + Attributes: + ingestion_product_type (str): + The type of [Product][google.cloud.retail.v2beta.Product]s + allowed to be ingested into the catalog. Acceptable values + are: + + - ``primary`` (default): You can ingest + [Product][google.cloud.retail.v2beta.Product]s of all + types. When ingesting a + [Product][google.cloud.retail.v2beta.Product], its type + will default to + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + if unset. + - ``variant``: You can only ingest + [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s. This + means + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] + cannot be empty. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``variant`` and + [merchant_center_product_id_field][google.cloud.retail.v2beta.ProductLevelConfig.merchant_center_product_id_field] + is ``itemGroupId``, an INVALID_ARGUMENT error is returned. + + See `Using product + levels `__ + for more details. + merchant_center_product_id_field (str): + Which field of `Merchant Center + Product `__ + should be imported as + [Product.id][google.cloud.retail.v2beta.Product.id]. + Acceptable values are: + + - ``offerId`` (default): Import ``offerId`` as the product + ID. + - ``itemGroupId``: Import ``itemGroupId`` as the product + ID. Notice that Retail API will choose one item from the + ones with the same ``itemGroupId``, and use it to + represent the item group. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``itemGroupId`` and + [ingestion_product_type][google.cloud.retail.v2beta.ProductLevelConfig.ingestion_product_type] + is ``variant``, an INVALID_ARGUMENT error is returned. + + See `Using product + levels `__ + for more details. + """ + + ingestion_product_type = proto.Field( + proto.STRING, + number=1, + ) + merchant_center_product_id_field = proto.Field( + proto.STRING, + number=2, + ) + + +class CatalogAttribute(proto.Message): + r"""Catalog level attribute config for an attribute. For example, + if customers want to enable/disable facet for a specific + attribute. + + Attributes: + key (str): + Required. Attribute name. For example: ``color``, + ``brands``, ``attributes.custom_attribute``, such as + ``attributes.xyz``. + in_use (bool): + Output only. Indicates whether this attribute has been used + by any products. ``True`` if at least one + [Product][google.cloud.retail.v2beta.Product] is using this + attribute in + [Product.attributes][google.cloud.retail.v2beta.Product.attributes]. + Otherwise, this field is ``False``. + + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + can be pre-loaded by using [AddCatalogAttribute][], + [ImportCatalogAttributes][], or [UpdateAttributesConfig][] + APIs. This field is ``False`` for pre-loaded + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s. + + Only + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s + that are not in use by products can be deleted. + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s + that are in use by products cannot be deleted; however, + their configuration properties will reset to default values + upon removal request. + + After catalog changes, it takes about 10 minutes for this + field to update. + type_ (google.cloud.retail_v2beta.types.CatalogAttribute.AttributeType): + Output only. The type of this attribute. This is derived + from the attribute in + [Product.attributes][google.cloud.retail.v2beta.Product.attributes]. + indexable_option (google.cloud.retail_v2beta.types.CatalogAttribute.IndexableOption): + When + [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] + is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if INDEXABLE_ENABLED + attribute values are indexed so that it can be filtered, + faceted, or boosted in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + dynamic_facetable_option (google.cloud.retail_v2beta.types.CatalogAttribute.DynamicFacetableOption): + If DYNAMIC_FACETABLE_ENABLED, attribute values are available + for dynamic facet. Could only be DYNAMIC_FACETABLE_DISABLED + if + [CatalogAttribute.indexable_option][google.cloud.retail.v2beta.CatalogAttribute.indexable_option] + is INDEXABLE_DISABLED. Otherwise, an INVALID_ARGUMENT error + is returned. + searchable_option (google.cloud.retail_v2beta.types.CatalogAttribute.SearchableOption): + When + [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] + is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if SEARCHABLE_ENABLED, + attribute values are searchable by text queries in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + If SEARCHABLE_ENABLED but attribute type is numerical, + attribute values will not be searchable by text queries in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + as there are no text values associated to numerical + attributes. + """ + class AttributeType(proto.Enum): + r"""The type of an attribute.""" + UNKNOWN = 0 + TEXTUAL = 1 + NUMERICAL = 2 + + class IndexableOption(proto.Enum): + r"""The status of the indexable option of a catalog attribute.""" + INDEXABLE_OPTION_UNSPECIFIED = 0 + INDEXABLE_ENABLED = 1 + INDEXABLE_DISABLED = 2 + + class DynamicFacetableOption(proto.Enum): + r"""The status of the dynamic facetable option of a catalog + attribute. + """ + DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 + DYNAMIC_FACETABLE_ENABLED = 1 + DYNAMIC_FACETABLE_DISABLED = 2 + + class SearchableOption(proto.Enum): + r"""The status of the searchable option of a catalog attribute.""" + SEARCHABLE_OPTION_UNSPECIFIED = 0 + SEARCHABLE_ENABLED = 1 + SEARCHABLE_DISABLED = 2 + + key = proto.Field( + proto.STRING, + number=1, + ) + in_use = proto.Field( + proto.BOOL, + number=9, + ) + type_ = proto.Field( + proto.ENUM, + number=10, + enum=AttributeType, + ) + indexable_option = proto.Field( + proto.ENUM, + number=5, + enum=IndexableOption, + ) + dynamic_facetable_option = proto.Field( + proto.ENUM, + number=6, + enum=DynamicFacetableOption, + ) + searchable_option = proto.Field( + proto.ENUM, + number=7, + enum=SearchableOption, + ) + + +class AttributesConfig(proto.Message): + r"""Catalog level attribute config. + + Attributes: + name (str): + Required. Immutable. The fully qualified resource name of + the attribute config. Format: + ``projects/*/locations/*/catalogs/*/attributesConfig`` + catalog_attributes (Mapping[str, google.cloud.retail_v2beta.types.CatalogAttribute]): + Enable attribute(s) config at catalog level. For example, + indexable, dynamic_facetable, or searchable for each + attribute. + + The key is catalog attribute's name. For example: ``color``, + ``brands``, ``attributes.custom_attribute``, such as + ``attributes.xyz``. + + The maximum number of catalog attributes allowed in a + request is 1000. + attribute_config_level (google.cloud.retail_v2beta.types.AttributeConfigLevel): + Output only. The + [AttributeConfigLevel][google.cloud.retail.v2beta.AttributeConfigLevel] + used for this catalog. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + catalog_attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='CatalogAttribute', + ) + attribute_config_level = proto.Field( + proto.ENUM, + number=3, + enum=common.AttributeConfigLevel, + ) + + +class CompletionConfig(proto.Message): + r"""Catalog level autocomplete config for customers to customize + autocomplete feature's settings. + + Attributes: + name (str): + Required. Immutable. Fully qualified name + ``projects/*/locations/*/catalogs/*/completionConfig`` + matching_order (str): + Specifies the matching order for autocomplete suggestions, + e.g., a query consisting of 'sh' with 'out-of-order' + specified would suggest "women's shoes", whereas a query of + 'red s' with 'exact-prefix' specified would suggest "red + shoes". Currently supported values: + + - 'out-of-order' + - 'exact-prefix' + + Default value: 'exact-prefix'. + max_suggestions (int): + The maximum number of autocomplete + suggestions returned per term. The maximum + allowed max suggestions is 20. Default value is + 20. If left unset or set to 0, then will + fallback to default value. + min_prefix_length (int): + The minimum number of characters needed to be + typed in order to get suggestions. Default value + is 2. If left unset or set to 0, then will + fallback to default value. + auto_learning (bool): + If set to true, the auto learning function is enabled. Auto + learning uses user data to generate suggestions using ML + techniques. Default value is false. Only after enabling auto + learning can users use ``cloud-retail`` data in + [CompleteQueryRequest][google.cloud.retail.v2beta.CompleteQueryRequest]. + suggestions_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the + autocomplete phrases uploaded by the customer. + last_suggestions_import_operation (str): + Output only. Name of the LRO corresponding to the latest + suggestion terms list import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + denylist_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the / + autocomplete denylist phrases uploaded by the + customer. + last_denylist_import_operation (str): + Output only. LRO corresponding to the latest denylist + import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + allowlist_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the + autocomplete allowlist phrases uploaded by the + customer. + last_allowlist_import_operation (str): + Output only. LRO corresponding to the latest allowlist + import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + matching_order = proto.Field( + proto.STRING, + number=2, + ) + max_suggestions = proto.Field( + proto.INT32, + number=3, + ) + min_prefix_length = proto.Field( + proto.INT32, + number=4, + ) + auto_learning = proto.Field( + proto.BOOL, + number=11, + ) + suggestions_input_config = proto.Field( + proto.MESSAGE, + number=5, + message=import_config.CompletionDataInputConfig, + ) + last_suggestions_import_operation = proto.Field( + proto.STRING, + number=6, + ) + denylist_input_config = proto.Field( + proto.MESSAGE, + number=7, + message=import_config.CompletionDataInputConfig, + ) + last_denylist_import_operation = proto.Field( + proto.STRING, + number=8, + ) + allowlist_input_config = proto.Field( + proto.MESSAGE, + number=9, + message=import_config.CompletionDataInputConfig, + ) + last_allowlist_import_operation = proto.Field( + proto.STRING, + number=10, + ) + + +class MerchantCenterLink(proto.Message): + r"""Represents a link between a Merchant Center account and a + branch. Once a link is established, products from the linked + merchant center account will be streamed to the linked branch. + + Attributes: + merchant_center_account_id (int): + Required. The linked `Merchant center account + id `__. + The account must be a standalone account or a sub-account of + a MCA. + branch_id (str): + The branch id (e.g. 0/1/2) within this catalog that products + from merchant_center_account_id are streamed to. When + updating this field, an empty value will use the currently + configured default branch. However, changing the default + branch later on won't change the linked branch here. + + A single branch id can only have one linked merchant center + account id. + destinations (Sequence[str]): + String representing the destination to import for, all if + left empty. List of possible values can be found here. + [https://support.google.com/merchants/answer/7501026] List + of allowed string values: "Shopping_ads", + "Buy_on_google_listings", "Display_ads", "Local_inventory + \_ads", "Free_listings", "Free_local_listings" NOTE: The + string values are case sensitive. + region_code (str): + Region code of offers to accept. 2-letter Uppercase ISO + 3166-1 alpha-2 code. List of values can be found + `here `__ + under the ``region`` tag. If left blank no region filtering + will be performed. + + Example value: ``US``. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. ISO + 639-1. + + This specifies the language of offers in Merchant Center + that will be accepted. If empty no language filtering will + be performed. + + Example value: ``en``. + """ + + merchant_center_account_id = proto.Field( + proto.INT64, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + destinations = proto.RepeatedField( + proto.STRING, + number=3, + ) + region_code = proto.Field( + proto.STRING, + number=4, + ) + language_code = proto.Field( + proto.STRING, + number=5, + ) + + +class MerchantCenterLinkingConfig(proto.Message): + r"""Configures Merchant Center linking. + Links contained in the config will be used to sync data from a + Merchant Center account to a Cloud Retail branch. + + Attributes: + links (Sequence[google.cloud.retail_v2beta.types.MerchantCenterLink]): + Links between Merchant Center accounts and + branches. + """ + + links = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MerchantCenterLink', + ) + + +class Catalog(proto.Message): + r"""The catalog configuration. + + Attributes: + name (str): + Required. Immutable. The fully qualified + resource name of the catalog. + display_name (str): + Required. Immutable. The catalog display name. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + product_level_config (google.cloud.retail_v2beta.types.ProductLevelConfig): + Required. The product level configuration. + merchant_center_linking_config (google.cloud.retail_v2beta.types.MerchantCenterLinkingConfig): + The Merchant Center linking configuration. + Once a link is added, the data stream from + Merchant Center to Cloud Retail will be enabled + automatically. The requester must have access to + the merchant center account in order to make + changes to this field. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + product_level_config = proto.Field( + proto.MESSAGE, + number=4, + message='ProductLevelConfig', + ) + merchant_center_linking_config = proto.Field( + proto.MESSAGE, + number=6, + message='MerchantCenterLinkingConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py new file mode 100644 index 00000000..c49ba005 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py @@ -0,0 +1,453 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'UpdateCatalogRequest', + 'SetDefaultBranchRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'GetCompletionConfigRequest', + 'UpdateCompletionConfigRequest', + 'GetAttributesConfigRequest', + 'UpdateAttributesConfigRequest', + 'AddCatalogAttributeRequest', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + }, +) + + +class ListCatalogsRequest(proto.Message): + r"""Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + + Attributes: + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2beta.Catalog]s under this + location, regardless of whether or not this location exists, + a PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [Catalog][google.cloud.retail.v2beta.Catalog]s to return. If + unspecified, defaults to 50. The maximum allowed value is + 1000. Values above 1000 will be coerced to 1000. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [ListCatalogsResponse.next_page_token][google.cloud.retail.v2beta.ListCatalogsResponse.next_page_token], + received from a previous + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCatalogsResponse(proto.Message): + r"""Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + + Attributes: + catalogs (Sequence[google.cloud.retail_v2beta.types.Catalog]): + All the customer's + [Catalog][google.cloud.retail.v2beta.Catalog]s. + next_page_token (str): + A token that can be sent as + [ListCatalogsRequest.page_token][google.cloud.retail.v2beta.ListCatalogsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + catalogs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateCatalogRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] + method. + + Attributes: + catalog (google.cloud.retail_v2beta.types.Catalog): + Required. The [Catalog][google.cloud.retail.v2beta.Catalog] + to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2beta.Catalog], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2beta.Catalog] 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 + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + catalog = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class SetDefaultBranchRequest(proto.Message): + r"""Request message to set a specified branch as new default_branch. + + Attributes: + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + branch_id (str): + The final component of the resource name of a branch. + + This field must be one of "0", "1" or "2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If there are no sufficient active products in the targeted + branch and + [force][google.cloud.retail.v2beta.SetDefaultBranchRequest.force] + is not set, a FAILED_PRECONDITION error is returned. + note (str): + Some note on this request, this can be retrieved by + [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch] + before next valid default branch set occurs. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + force (bool): + If set to true, it permits switching to a branch with + [branch_id][google.cloud.retail.v2beta.SetDefaultBranchRequest.branch_id] + even if it has no sufficient active products. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + force = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetDefaultBranchRequest(proto.Message): + r"""Request message to show which branch is currently the default + branch. + + Attributes: + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDefaultBranchResponse(proto.Message): + r"""Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. + + Attributes: + branch (str): + Full resource name of the branch id currently + set as default branch. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when this branch is set to default. + note (str): + This corresponds to + [SetDefaultBranchRequest.note][google.cloud.retail.v2beta.SetDefaultBranchRequest.note] + field, when this branch was set as default. + """ + + branch = proto.Field( + proto.STRING, + number=1, + ) + set_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + + +class GetCompletionConfigRequest(proto.Message): + r"""Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] + method. + + Attributes: + name (str): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateCompletionConfigRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] + method. + + Attributes: + completion_config (google.cloud.retail_v2beta.types.CompletionConfig): + Required. The + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + 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 + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + """ + + completion_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.CompletionConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetAttributesConfigRequest(proto.Message): + r"""Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] + method. + + Attributes: + name (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAttributesConfigRequest(proto.Message): + r"""Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] + method. + + Attributes: + attributes_config (google.cloud.retail_v2beta.types.AttributesConfig): + Required. The + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + """ + + attributes_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.AttributesConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class AddCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + catalog_attribute (google.cloud.retail_v2beta.types.CatalogAttribute): + Required. The + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + catalog_attribute = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_catalog.CatalogAttribute, + ) + + +class RemoveCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + key (str): + Required. The attribute name key of the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + key = proto.Field( + proto.STRING, + number=2, + ) + + +class ReplaceCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + catalog_attribute (google.cloud.retail_v2beta.types.CatalogAttribute): + Required. The updated + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to update. The following are NOT supported: + + - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key] + + If not set, all supported fields are updated. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + catalog_attribute = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_catalog.CatalogAttribute, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py new file mode 100644 index 00000000..c40843c0 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py @@ -0,0 +1,1178 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'AttributeConfigLevel', + 'SolutionType', + 'SearchSolutionUseCase', + 'Condition', + 'Rule', + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'LocalInventory', + }, +) + + +class AttributeConfigLevel(proto.Enum): + r"""At which level we offer configuration for attributes.""" + ATTRIBUTE_CONFIG_LEVEL_UNSPECIFIED = 0 + PRODUCT_LEVEL_ATTRIBUTE_CONFIG = 1 + CATALOG_LEVEL_ATTRIBUTE_CONFIG = 2 + + +class SolutionType(proto.Enum): + r"""The type of solution.""" + SOLUTION_TYPE_UNSPECIFIED = 0 + SOLUTION_TYPE_RECOMMENDATION = 1 + SOLUTION_TYPE_SEARCH = 2 + + +class SearchSolutionUseCase(proto.Enum): + r"""The use case of Cloud Retail Search.""" + SEARCH_SOLUTION_USE_CASE_UNSPECIFIED = 0 + SEARCH_SOLUTION_USE_CASE_SEARCH = 1 + SEARCH_SOLUTION_USE_CASE_BROWSE = 2 + + +class Condition(proto.Message): + r"""Metadata that is used to define a condition that triggers an action. + A valid condition must specify at least one of 'query_terms' or + 'products_filter'. If multiple fields are specified, the condition + is met if all the fields are satisfied e.g. if a set of query terms + and product_filter are set, then only items matching the + product_filter for requests with a query matching the query terms + wil get boosted. + + Attributes: + query_terms (Sequence[google.cloud.retail_v2beta.types.Condition.QueryTerm]): + A list (up to 10 entries) of terms to match + the query on. If not specified, match all + queries. If many query terms are specified, the + condition is matched if any of the terms is a + match (i.e. using the OR operator). + active_time_range (Sequence[google.cloud.retail_v2beta.types.Condition.TimeRange]): + Range of time(s) specifying when Condition is + active. Condition true if any time range + matches. + """ + + class QueryTerm(proto.Message): + r"""Query terms that we want to match on. + + Attributes: + value (str): + The value of the term to match on. + Value cannot be empty. + Value can have at most 3 terms if specified as a + partial match. Each space separated string is + considered as one term. Example) "a b c" is 3 + terms and allowed, " a b c d" is 4 terms and not + allowed for partial match. + full_match (bool): + Whether this is supposed to be a full or + partial match. + """ + + value = proto.Field( + proto.STRING, + number=1, + ) + full_match = proto.Field( + proto.BOOL, + number=2, + ) + + class TimeRange(proto.Message): + r"""Used for time-dependent conditions. + Example: Want to have rule applied for week long sale. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start of time range. Range is inclusive. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End of time range. Range is inclusive. + """ + + start_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + query_terms = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=QueryTerm, + ) + active_time_range = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TimeRange, + ) + + +class Rule(proto.Message): + r"""A rule is a condition-action pair + + - A condition defines when a rule is to be triggered. + - An action specifies what occurs on that trigger. Currently only + boost rules are supported. Currently only supported by the search + endpoint. + + 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: + boost_action (google.cloud.retail_v2beta.types.Rule.BoostAction): + A boost action. + + This field is a member of `oneof`_ ``action``. + redirect_action (google.cloud.retail_v2beta.types.Rule.RedirectAction): + Redirects a shopper to a specific page. + + This field is a member of `oneof`_ ``action``. + oneway_synonyms_action (google.cloud.retail_v2beta.types.Rule.OnewaySynonymsAction): + Treats specific term as a synonym with a + group of terms. Group of terms will not be + treated as synonyms with the specific term. + + This field is a member of `oneof`_ ``action``. + do_not_associate_action (google.cloud.retail_v2beta.types.Rule.DoNotAssociateAction): + Prevents term from being associated with + other terms. + + This field is a member of `oneof`_ ``action``. + replacement_action (google.cloud.retail_v2beta.types.Rule.ReplacementAction): + Replaces specific terms in the query. + + This field is a member of `oneof`_ ``action``. + ignore_action (google.cloud.retail_v2beta.types.Rule.IgnoreAction): + Ignores specific terms from query during + search. + + This field is a member of `oneof`_ ``action``. + filter_action (google.cloud.retail_v2beta.types.Rule.FilterAction): + Filters results. + + This field is a member of `oneof`_ ``action``. + twoway_synonyms_action (google.cloud.retail_v2beta.types.Rule.TwowaySynonymsAction): + Treats a set of terms as synonyms of one + another. + + This field is a member of `oneof`_ ``action``. + condition (google.cloud.retail_v2beta.types.Condition): + Required. The condition that triggers the + rule. If the condition is empty, the rule will + always apply. + """ + + class BoostAction(proto.Message): + r"""A boost action to apply to results matching condition + specified above. + + Attributes: + boost (float): + Strength of the condition boost, which must be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + products_filter (str): + The filter can have a max size of 5000 characters. An + expression which specifies which products to apply an action + to. The syntax and supported fields are the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": *(id: + ANY("product_1", "product_2"))* *AND* *(colorFamilies: + ANY("Red", "Blue"))* + """ + + boost = proto.Field( + proto.FLOAT, + number=1, + ) + products_filter = proto.Field( + proto.STRING, + number=2, + ) + + class FilterAction(proto.Message): + r"""- Rule Condition: + + - No [Condition][query_terms] provided is a global match. + - 1 or more [Condition][query_terms] provided is combined with + OR operator. + + - Action Input: The request query and filter that will be applied + to the retrieved products, in addition to any filters already + provided with the SearchRequest. The AND operator is used to + combine the query's existing filters with the filter rule(s). + NOTE: May result in 0 results when filters conflict. + - Action Result: Filters the returned objects to be ONLY those that + passed the filter. + + Attributes: + filter (str): + A filter to apply on the matching condition results. + Supported features: + + - [filter][google.cloud.retail.v2beta.Rule.FilterAction.filter] + must be set. + - Filter syntax is identical to + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter]. + See more details at the Retail Search `user + guide `__. + - To filter products with product ID "product_1" or + "product_2", and color "Red" or "Blue": *(id: + ANY("product_1", "product_2"))* *AND* *(colorFamilies: + ANY("Red", "Blue"))* + """ + + filter = proto.Field( + proto.STRING, + number=1, + ) + + class RedirectAction(proto.Message): + r"""Redirects a shopper to a specific page. + + - Rule Condition: + + - Must specify [Condition][query_terms]. + + - Action Input: Request Query + - Action Result: Redirects shopper to provided uri. + + Attributes: + redirect_uri (str): + URL must have length equal or less than 2000 + characters. + """ + + redirect_uri = proto.Field( + proto.STRING, + number=1, + ) + + class TwowaySynonymsAction(proto.Message): + r"""Creates a set of terms that will be treated as synonyms of each + other. Example: synonyms of "sneakers" and "shoes". + + - "sneakers" will use a synonym of "shoes". + - "shoes" will use a synonym of "sneakers". + + Attributes: + synonyms (Sequence[str]): + Defines a set of synonyms. + Can specify up to 100 synonyms. + Must specify at least 2 synonyms. + """ + + synonyms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class OnewaySynonymsAction(proto.Message): + r"""Maps a set of terms to a set of synonyms. Set of synonyms will be + treated as synonyms of each query term only. ``query_terms`` will + not be treated as synonyms of each other. Example: "sneakers" will + use a synonym of "shoes". "shoes" will not use a synonym of + "sneakers". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. + Will treat synonyms as their synonyms. + Not themselves synonyms of the synonyms. + Can specify up to 100 terms. + synonyms (Sequence[str]): + Defines a set of synonyms. + Cannot contain duplicates. + Can specify up to 100 synonyms. + oneway_terms (Sequence[str]): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=3, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=4, + ) + oneway_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class DoNotAssociateAction(proto.Message): + r"""Prevents ``query_term`` from being associated with specified terms + during search. Example: Don't associate "gShoe" and "cheap". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. Will not consider + do_not_associate_terms for search if in search query. Can + specify up to 100 terms. + do_not_associate_terms (Sequence[str]): + Cannot contain duplicates or the query term. + Can specify up to 100 terms. + terms (Sequence[str]): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + do_not_associate_terms = proto.RepeatedField( + proto.STRING, + number=3, + ) + terms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class ReplacementAction(proto.Message): + r"""Replaces a term in the query. Multiple replacement candidates can be + specified. All ``query_terms`` will be replaced with the replacement + term. Example: Replace "gShoe" with "google shoe". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. + Will be replaced by replacement term. + Can specify up to 100 terms. + replacement_term (str): + Term that will be used for replacement. + term (str): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + replacement_term = proto.Field( + proto.STRING, + number=3, + ) + term = proto.Field( + proto.STRING, + number=1, + ) + + class IgnoreAction(proto.Message): + r"""Prevents a term in the query from being used in search. + Example: Don't search for "shoddy". + + Attributes: + ignore_terms (Sequence[str]): + Terms to ignore in the search query. + """ + + ignore_terms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + boost_action = proto.Field( + proto.MESSAGE, + number=2, + oneof='action', + message=BoostAction, + ) + redirect_action = proto.Field( + proto.MESSAGE, + number=3, + oneof='action', + message=RedirectAction, + ) + oneway_synonyms_action = proto.Field( + proto.MESSAGE, + number=6, + oneof='action', + message=OnewaySynonymsAction, + ) + do_not_associate_action = proto.Field( + proto.MESSAGE, + number=7, + oneof='action', + message=DoNotAssociateAction, + ) + replacement_action = proto.Field( + proto.MESSAGE, + number=8, + oneof='action', + message=ReplacementAction, + ) + ignore_action = proto.Field( + proto.MESSAGE, + number=9, + oneof='action', + message=IgnoreAction, + ) + filter_action = proto.Field( + proto.MESSAGE, + number=10, + oneof='action', + message=FilterAction, + ) + twoway_synonyms_action = proto.Field( + proto.MESSAGE, + number=11, + oneof='action', + message=TwowaySynonymsAction, + ) + condition = proto.Field( + proto.MESSAGE, + number=1, + message='Condition', + ) + + +class Audience(proto.Message): + r"""An intended audience of the + [Product][google.cloud.retail.v2beta.Product] for whom it's sold. + + Attributes: + genders (Sequence[str]): + The genders of the audience. Strongly encouraged to use the + standard values: "male", "female", "unisex". + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `gender `__. + Schema.org property + `Product.audience.suggestedGender `__. + age_groups (Sequence[str]): + The age groups of the audience. Strongly encouraged to use + the standard values: "newborn" (up to 3 months old), + "infant" (3–12 months old), "toddler" (1–5 years old), + "kids" (5–13 years old), "adult" (typically teens or older). + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `age_group `__. + Schema.org property + `Product.audience.suggestedMinAge `__ + and + `Product.audience.suggestedMaxAge `__. + """ + + genders = proto.RepeatedField( + proto.STRING, + number=1, + ) + age_groups = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class ColorInfo(proto.Message): + r"""The color information of a + [Product][google.cloud.retail.v2beta.Product]. + + Attributes: + color_families (Sequence[str]): + The standard color families. Strongly recommended to use the + following standard color groups: "Red", "Pink", "Orange", + "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", + "White", "Gray", "Black" and "Mixed". Normally it is + expected to have only 1 color family. May consider using + single "Mixed" instead of multiple values. + + A maximum of 5 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + colors (Sequence[str]): + The color display names, which may be different from + standard color family names, such as the color aliases used + in the website frontend. Normally it is expected to have + only 1 color. May consider using single "Mixed" instead of + multiple values. + + A maximum of 25 colors are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + """ + + color_families = proto.RepeatedField( + proto.STRING, + number=1, + ) + colors = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in + [Product][google.cloud.retail.v2beta.Product]. + + Attributes: + text (Sequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an INVALID_ARGUMENT + error is returned. + + Exactly one of + [text][google.cloud.retail.v2beta.CustomAttribute.text] or + [numbers][google.cloud.retail.v2beta.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + numbers (Sequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [text][google.cloud.retail.v2beta.CustomAttribute.text] or + [numbers][google.cloud.retail.v2beta.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + searchable (bool): + This field will only be used when + [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] + of the [Catalog][google.cloud.retail.v2beta.Catalog] is + 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute + values are searchable by text queries in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2beta.UserEvent]. + + Only set if type + [text][google.cloud.retail.v2beta.CustomAttribute.text] is + set. Otherwise, a INVALID_ARGUMENT error is returned. + + This field is a member of `oneof`_ ``_searchable``. + indexable (bool): + This field will only be used when + [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] + of the [Catalog][google.cloud.retail.v2beta.Catalog] is + 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute + values are indexed, so that it can be filtered, faceted or + boosted in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2beta.UserEvent]. + + See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter], + [SearchRequest.facet_specs][google.cloud.retail.v2beta.SearchRequest.facet_specs] + and + [SearchRequest.boost_spec][google.cloud.retail.v2beta.SearchRequest.boost_spec] + for more details. + + This field is a member of `oneof`_ ``_indexable``. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + searchable = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + indexable = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + +class FulfillmentInfo(proto.Message): + r"""Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + Attributes: + type_ (str): + The fulfillment type, including commonly used types (such as + pickup in store and same day delivery), and custom types. + Customers have to map custom types to their display names + before rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + place_ids (Sequence[str]): + The IDs for this + [type][google.cloud.retail.v2beta.FulfillmentInfo.type], + such as the store IDs for + [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2beta.FulfillmentInfo.type] + or the region IDs for + [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2beta.FulfillmentInfo.type]. + + A maximum of 3000 values are allowed. Each value must be a + string with a length limit of 30 characters, matching the + pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". + Otherwise, an INVALID_ARGUMENT error is returned. + """ + + type_ = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class Image(proto.Message): + r"""[Product][google.cloud.retail.v2beta.Product] image. Recommendations + AI and Retail Search do not use product images to improve prediction + and search results. However, product images can be returned in + results, and are shown in prediction or search previews in the + console. + + Attributes: + uri (str): + Required. URI of the image. + + This field must be a valid UTF-8 encoded URI with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + height (int): + Height of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + width (int): + Width of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + height = proto.Field( + proto.INT32, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + + +class Interval(proto.Message): + r"""A floating point interval. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum = proto.Field( + proto.DOUBLE, + number=1, + oneof='min', + ) + exclusive_minimum = proto.Field( + proto.DOUBLE, + number=2, + oneof='min', + ) + maximum = proto.Field( + proto.DOUBLE, + number=3, + oneof='max', + ) + exclusive_maximum = proto.Field( + proto.DOUBLE, + number=4, + oneof='max', + ) + + +class PriceInfo(proto.Message): + r"""The price information of a + [Product][google.cloud.retail.v2beta.Product]. + + Attributes: + currency_code (str): + The 3-letter currency code defined in `ISO + 4217 `__. + + If this field is an unrecognizable currency code, an + INVALID_ARGUMENT error is returned. + + The + [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s with the same + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] + must share the same + [currency_code][google.cloud.retail.v2beta.PriceInfo.currency_code]. + Otherwise, a FAILED_PRECONDITION error is returned. + price (float): + Price of the product. + + Google Merchant Center property + `price `__. + Schema.org property + `Offer.price `__. + original_price (float): + Price of the product without any discount. If zero, by + default set to be the + [price][google.cloud.retail.v2beta.PriceInfo.price]. + cost (float): + The costs associated with the sale of a particular product. + Used for gross profit reporting. + + - Profit = + [price][google.cloud.retail.v2beta.PriceInfo.price] - + [cost][google.cloud.retail.v2beta.PriceInfo.cost] + + Google Merchant Center property + `cost_of_goods_sold `__. + price_effective_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2beta.PriceInfo.price] starts + to be effective. This can be set as a future timestamp, and + the [price][google.cloud.retail.v2beta.PriceInfo.price] is + only used for search after + [price_effective_time][google.cloud.retail.v2beta.PriceInfo.price_effective_time]. + If so, the + [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + is used before + [price_effective_time][google.cloud.retail.v2beta.PriceInfo.price_effective_time]. + + Do not set if + [price][google.cloud.retail.v2beta.PriceInfo.price] is + always effective because it will cause additional latency + during search. + price_expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2beta.PriceInfo.price] stops to + be effective. The + [price][google.cloud.retail.v2beta.PriceInfo.price] is used + for search before + [price_expire_time][google.cloud.retail.v2beta.PriceInfo.price_expire_time]. + If this field is set, the + [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + is used after + [price_expire_time][google.cloud.retail.v2beta.PriceInfo.price_expire_time]. + + Do not set if + [price][google.cloud.retail.v2beta.PriceInfo.price] is + always effective because it will cause additional latency + during search. + price_range (google.cloud.retail_v2beta.types.PriceInfo.PriceRange): + Output only. The price range of all the child + [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s grouped + together on the + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]. Only + populated for + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct]. + Do not set this field in API requests. + """ + + class PriceRange(proto.Message): + r"""The price range of all + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. + + Attributes: + price (google.cloud.retail_v2beta.types.Interval): + The inclusive + [Product.pricing_info.price][google.cloud.retail.v2beta.PriceInfo.price] + interval of all + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] having the + same + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. + original_price (google.cloud.retail_v2beta.types.Interval): + The inclusive + [Product.pricing_info.original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + internal of all + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] having the + same + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. + """ + + price = proto.Field( + proto.MESSAGE, + number=1, + message='Interval', + ) + original_price = proto.Field( + proto.MESSAGE, + number=2, + message='Interval', + ) + + currency_code = proto.Field( + proto.STRING, + number=1, + ) + price = proto.Field( + proto.FLOAT, + number=2, + ) + original_price = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + price_effective_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + price_expire_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + price_range = proto.Field( + proto.MESSAGE, + number=7, + message=PriceRange, + ) + + +class Rating(proto.Message): + r"""The rating of a [Product][google.cloud.retail.v2beta.Product]. + + Attributes: + rating_count (int): + The total number of ratings. This value is independent of + the value of + [rating_histogram][google.cloud.retail.v2beta.Rating.rating_histogram]. + + This value must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + average_rating (float): + The average rating of the + [Product][google.cloud.retail.v2beta.Product]. + + The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT + error is returned. + rating_histogram (Sequence[int]): + List of rating counts per rating value (index = rating - 1). + The list is empty if there is no rating. If the list is + non-empty, its size is always 5. Otherwise, an + INVALID_ARGUMENT error is returned. + + For example, [41, 14, 13, 47, 303]. It means that the + [Product][google.cloud.retail.v2beta.Product] got 41 ratings + with 1 star, 14 ratings with 2 star, and so on. + """ + + rating_count = proto.Field( + proto.INT32, + number=1, + ) + average_rating = proto.Field( + proto.FLOAT, + number=2, + ) + rating_histogram = proto.RepeatedField( + proto.INT32, + number=3, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. + + Always use a hashed value for this ID. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + ip_address (str): + The end user's IP address. This field is used to extract + location information for personalization. + + This field must be either an IPv4 address (e.g. + "104.133.9.80") or an IPv6 address (e.g. + "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an + INVALID_ARGUMENT error is returned. + + This should not be set when: + + - setting + [SearchRequest.user_info][google.cloud.retail.v2beta.SearchRequest.user_info]. + - using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2beta.UserInfo.direct_user_request] + is set. + user_agent (str): + User agent as included in the HTTP header. Required for + getting + [SearchResponse.sponsored_results][google.cloud.retail.v2beta.SearchResponse.sponsored_results]. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2beta.UserInfo.direct_user_request] + is set. + direct_user_request (bool): + True if the request is made directly from the end user, in + which case the + [ip_address][google.cloud.retail.v2beta.UserInfo.ip_address] + and + [user_agent][google.cloud.retail.v2beta.UserInfo.user_agent] + can be populated from the HTTP request. This flag should be + set only if the API request is made directly from the end + user such as a mobile app (and not if a gateway or a server + is processing and pushing the user events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent]. + """ + + user_id = proto.Field( + proto.STRING, + number=1, + ) + ip_address = proto.Field( + proto.STRING, + number=2, + ) + user_agent = proto.Field( + proto.STRING, + number=3, + ) + direct_user_request = proto.Field( + proto.BOOL, + number=4, + ) + + +class LocalInventory(proto.Message): + r"""The inventory information at a place (e.g. a store) + identified by a place ID. + + Attributes: + place_id (str): + The place ID for the current set of inventory + information. + price_info (google.cloud.retail_v2beta.types.PriceInfo): + Product price and cost information. + + Google Merchant Center property + `price `__. + attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): + Additional local inventory attributes, for example, store + name, promotion tags, etc. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - At most 30 attributes are allowed. + - The key must be a UTF-8 encoded string with a length + limit of 32 characters. + - The key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis + or KEY_1_LIKE_THIS. + - The attribute values must be of the same type (text or + number). + - Only 1 value is allowed for each attribute. + - For text values, the length limit is 256 UTF-8 + characters. + - The attribute does not support search. The ``searchable`` + field should be unset or set to false. + - The max summed total bytes of custom attribute keys and + values per product is 5MiB. + fulfillment_types (Sequence[str]): + Input only. Supported fulfillment types. Valid fulfillment + type values include commonly used types (such as pickup in + store and same day delivery), and custom types. Customers + have to map custom types to their display names before + rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + All the elements must be distinct. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + place_id = proto.Field( + proto.STRING, + number=1, + ) + price_info = proto.Field( + proto.MESSAGE, + number=2, + message='PriceInfo', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='CustomAttribute', + ) + fulfillment_types = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py new file mode 100644 index 00000000..47e39772 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'CompleteQueryRequest', + 'CompleteQueryResponse', + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Auto-complete parameters. + + Attributes: + catalog (str): + Required. Catalog for which the completion is performed. + + Full resource name of catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + query (str): + Required. The query used to generate + suggestions. + The maximum number of allowed characters is 255. + visitor_id (str): + Required field. A unique identifier for tracking visitors. + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + language_codes (Sequence[str]): + The language filters applied to the output suggestions. If + set, it should contain the language of the query. If not + set, suggestions are returned without considering language + restrictions. This is the BCP-47 language code, such as + "en-US" or "sr-Latn". For more information, see `Tags for + Identifying + Languages `__. The + maximum number of language codes is 3. + device_type (str): + The device type context for completion suggestions. It is + useful to apply different suggestions on different device + types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the + suggestions are across all device types. + + Supported formats: + + - ``UNKNOWN_DEVICE_TYPE`` + + - ``DESKTOP`` + + - ``MOBILE`` + + - A customized string starts with ``OTHER_``, e.g. + ``OTHER_IPHONE``. + dataset (str): + Determines which dataset to use for fetching completion. + "user-data" will use the imported dataset through + [CompletionService.ImportCompletionData][google.cloud.retail.v2beta.CompletionService.ImportCompletionData]. + "cloud-retail" will use the dataset generated by cloud + retail based on user events. If leave empty, it will use the + "user-data". + + Current supported values: + + - user-data + + - cloud-retail This option requires additional + allowlisting. Before using cloud-retail, contact Cloud + Retail support team first. + max_suggestions (int): + Completion max suggestions. If left unset or set to 0, then + will fallback to the configured value + [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions]. + + The maximum allowed max suggestions is 20. If it is set + higher, it will be capped by 20. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + visitor_id = proto.Field( + proto.STRING, + number=7, + ) + language_codes = proto.RepeatedField( + proto.STRING, + number=3, + ) + device_type = proto.Field( + proto.STRING, + number=4, + ) + dataset = proto.Field( + proto.STRING, + number=6, + ) + max_suggestions = proto.Field( + proto.INT32, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response of the auto-complete query. + + Attributes: + completion_results (Sequence[google.cloud.retail_v2beta.types.CompleteQueryResponse.CompletionResult]): + Results of the matching suggestions. The + result list is ordered and the first result is + top suggestion. + attribution_token (str): + A unique complete token. This should be included in the + [UserEvent.completion_detail][google.cloud.retail.v2beta.UserEvent.completion_detail] + for search events resulting from this completion, which + enables accurate attribution of complete model performance. + recent_search_results (Sequence[google.cloud.retail_v2beta.types.CompleteQueryResponse.RecentSearchResult]): + Matched recent searches of this user. The maximum number of + recent searches is 10. This field is a restricted feature. + Contact Retail Search support team if you are interested in + enabling it. + + This feature is only available when + [CompleteQueryRequest.visitor_id][google.cloud.retail.v2beta.CompleteQueryRequest.visitor_id] + field is set and + [UserEvent][google.cloud.retail.v2beta.UserEvent] is + imported. The recent searches satisfy the follow rules: + + - They are ordered from latest to oldest. + - They are matched with + [CompleteQueryRequest.query][google.cloud.retail.v2beta.CompleteQueryRequest.query] + case insensitively. + - They are transformed to lower cases. + - They are UTF-8 safe. + + Recent searches are deduplicated. More recent searches will + be reserved when duplication happens. + """ + + class CompletionResult(proto.Message): + r"""Resource that represents completion results. + + Attributes: + suggestion (str): + The suggestion for the query. + attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): + Custom attributes for the suggestion term. + + - For "user-data", the attributes are additional custom + attributes ingested through BigQuery. + - For "cloud-retail", the attributes are product attributes + generated by Cloud Retail. + """ + + suggestion = proto.Field( + proto.STRING, + number=1, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=common.CustomAttribute, + ) + + class RecentSearchResult(proto.Message): + r"""Recent search of this user. + + Attributes: + recent_search (str): + The recent search query. + """ + + recent_search = proto.Field( + proto.STRING, + number=1, + ) + + completion_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=CompletionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + recent_search_results = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=RecentSearchResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py new file mode 100644 index 00000000..0c7cdc3d --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'Control', + }, +) + + +class Control(proto.Message): + r"""Configures dynamic serving time metadata that is used to pre + and post process search/recommendation model results. + + 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: + facet_spec (google.cloud.retail_v2beta.types.SearchRequest.FacetSpec): + A facet specification to perform faceted + search. + + This field is a member of `oneof`_ ``control``. + rule (google.cloud.retail_v2beta.types.Rule): + A rule control - a condition-action pair. + Enacts a set action when the condition is + triggered. For example: Boost "gShoe" when query + full matches "Running Shoes". + + This field is a member of `oneof`_ ``control``. + name (str): + Immutable. Fully qualified name + projects/\ */locations/global/catalogs/*/controls/\* + display_name (str): + Required. The human readable control display name. Used in + Retail UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is thrown. + associated_serving_config_ids (Sequence[str]): + Output only. List of serving configuration + ids that that are associated with this control. + Note the association is managed via the + ServingConfig, this is an output only + denormalizeed view. Assumed to be in the same + catalog. + solution_types (Sequence[google.cloud.retail_v2beta.types.SolutionType]): + Required. Immutable. The solution types that the serving + config is used for. Currently we support setting only one + type of solution at creation time. + + Only ``SOLUTION_TYPE_SEARCH`` value is supported at the + moment. If no solution type is provided at creation time, + will default to SOLUTION_TYPE_SEARCH. + """ + + facet_spec = proto.Field( + proto.MESSAGE, + number=3, + oneof='control', + message=search_service.SearchRequest.FacetSpec, + ) + rule = proto.Field( + proto.MESSAGE, + number=4, + oneof='control', + message=common.Rule, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + associated_serving_config_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + solution_types = proto.RepeatedField( + proto.ENUM, + number=6, + enum=common.SolutionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py new file mode 100644 index 00000000..17120bb5 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import control as gcr_control +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'CreateControlRequest', + 'UpdateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + }, +) + + +class CreateControlRequest(proto.Message): + r"""Request for CreateControl method. + + Attributes: + parent (str): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + control (google.cloud.retail_v2beta.types.Control): + Required. The Control to create. + control_id (str): + Required. The ID to use for the Control, which will become + the final component of the Control's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-_/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + control = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_control.Control, + ) + control_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateControlRequest(proto.Message): + r"""Request for UpdateControl method. + + Attributes: + control (google.cloud.retail_v2beta.types.Control): + Required. The Control to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Control][google.cloud.retail.v2beta.Control] to update. The + following are NOT supported: + + - [Control.name][google.cloud.retail.v2beta.Control.name] + + If not set or empty, all supported fields are updated. + """ + + control = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_control.Control, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteControlRequest(proto.Message): + r"""Request for DeleteControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetControlRequest(proto.Message): + r"""Request for GetControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListControlsRequest(proto.Message): + r"""Request for ListControls method. + + Attributes: + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 50. Max + allowed value is 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListControls`` call. Provide this to retrieve the + subsequent page. + filter (str): + Optional. A filter to apply on the list results. Supported + features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2beta.ListControlsRequest.filter] + is unset. + - List controls that are used in a single ServingConfig: + 'serving_config = "boosted_home_page_cvr"' + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListControlsResponse(proto.Message): + r"""Response for ListControls method. + + Attributes: + controls (Sequence[google.cloud.retail_v2beta.types.Control]): + All the Controls for a given catalog. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + controls = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_control.Control, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py new file mode 100644 index 00000000..b020964a --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + }, +) + + +class ExportErrorsConfig(proto.Message): + r"""Configuration of destination for Export related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage path for import errors. This must be an + empty, existing Cloud Storage bucket. Export errors will be + written to a file in this bucket, one per line, as a + JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ExportMetadata(proto.Message): + r"""Metadata related to the progress of the Export operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ExportProductsResponse(proto.Message): + r"""Response of the ExportProductsRequest. If the long running + operation is done, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2beta.types.ExportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExportErrorsConfig', + ) + + +class ExportUserEventsResponse(proto.Message): + r"""Response of the ExportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2beta.types.ExportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExportErrorsConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py new file mode 100644 index 00000000..a32de943 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py @@ -0,0 +1,691 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import user_event +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'GcsSource', + 'BigQuerySource', + 'ProductInlineSource', + 'UserEventInlineSource', + 'ImportErrorsConfig', + 'ImportProductsRequest', + 'ImportUserEventsRequest', + 'ImportCompletionDataRequest', + 'ProductInputConfig', + 'UserEventInputConfig', + 'CompletionDataInputConfig', + 'ImportMetadata', + 'ImportProductsResponse', + 'ImportUserEventsResponse', + 'UserEventImportSummary', + 'ImportCompletionDataResponse', + }, +) + + +class GcsSource(proto.Message): + r"""Google Cloud Storage location for input content. + format. + + Attributes: + input_uris (Sequence[str]): + Required. Google Cloud Storage URIs to input files. URI can + be up to 2000 characters long. URIs can match the full + object path (for example, + ``gs://bucket/directory/object.json``) or a pattern matching + one or more files, such as ``gs://bucket/directory/*.json``. + A request can contain at most 100 files, and each file can + be up to 2 GB. See `Importing product + information `__ + for the expected file format and setup instructions. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2beta.Product] per line. + Each product must have a valid + [Product.id][google.cloud.retail.v2beta.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2beta.UserEvent] per + line. + - ``user_event_ga360``: Using + https://support.google.com/analytics/answer/3437719. + + Supported values for control imports: + + - 'control' (default): One JSON + [Control][google.cloud.retail.v2beta.Control] per line. + + Supported values for catalog attribute imports: + + - 'catalog_attribute' (default): One CSV + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + per line. + """ + + input_uris = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2beta.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID (can be project # or ID) that + the BigQuery source is in with a length limit of + 128 characters. If not specified, inherits the + project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2beta.Product] per line. + Each product must have a valid + [Product.id][google.cloud.retail.v2beta.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2beta.UserEvent] per + line. + - ``user_event_ga360``: The schema is available here: + https://support.google.com/analytics/answer/3437719. + - ``user_event_ga4``: This feature is in private preview. + Please contact the support team for importing Google + Analytics 4 events. The schema is available here: + https://support.google.com/analytics/answer/7029846. + + Supported values for auto-completion imports: + + - ``suggestions`` (default): One JSON completion suggestion + per line. + - ``denylist``: One JSON deny suggestion per line. + - ``allowlist``: One JSON allow suggestion per line. + """ + + partition_date = proto.Field( + proto.MESSAGE, + number=6, + oneof='partition', + message=date_pb2.Date, + ) + project_id = proto.Field( + proto.STRING, + number=5, + ) + dataset_id = proto.Field( + proto.STRING, + number=1, + ) + table_id = proto.Field( + proto.STRING, + number=2, + ) + gcs_staging_dir = proto.Field( + proto.STRING, + number=3, + ) + data_schema = proto.Field( + proto.STRING, + number=4, + ) + + +class ProductInlineSource(proto.Message): + r"""The inline source for the input config for ImportProducts + method. + + Attributes: + products (Sequence[google.cloud.retail_v2beta.types.Product]): + Required. A list of products to update/create. Each product + must have a valid + [Product.id][google.cloud.retail.v2beta.Product.id]. + Recommended max of 100 items. + """ + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=product.Product, + ) + + +class UserEventInlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (Sequence[google.cloud.retail_v2beta.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + +class ImportErrorsConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage prefix for import errors. This must be + an empty, existing Cloud Storage directory. Import errors + will be written to sharded files in this directory, one per + line, as a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportProductsRequest(proto.Message): + r"""Request message for Import methods. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` + + If no updateMask is specified, requires products.create + permission. If updateMask is specified, requires + products.update permission. + request_id (str): + Deprecated. This field has no effect. + input_config (google.cloud.retail_v2beta.types.ProductInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported 'products' to update. If not set, will + by default update all fields. + reconciliation_mode (google.cloud.retail_v2beta.types.ImportProductsRequest.ReconciliationMode): + The mode of reconciliation between existing products and the + products to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2beta.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2beta.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + """ + class ReconciliationMode(proto.Enum): + r"""Indicates how imported products are reconciled with the + existing products created or imported before. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + request_id = proto.Field( + proto.STRING, + number=6, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='ProductInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + reconciliation_mode = proto.Field( + proto.ENUM, + number=5, + enum=ReconciliationMode, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=7, + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + input_config (google.cloud.retail_v2beta.types.UserEventInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='UserEventInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + + +class ImportCompletionDataRequest(proto.Message): + r"""Request message for ImportCompletionData methods. + + Attributes: + parent (str): + Required. The catalog which the suggestions dataset belongs + to. + + Format: + ``projects/1234/locations/global/catalogs/default_catalog``. + input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): + Required. The desired input location of the + data. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='CompletionDataInputConfig', + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=3, + ) + + +class ProductInputConfig(proto.Message): + r"""The input config source for products. + + 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: + product_inline_source (google.cloud.retail_v2beta.types.ProductInlineSource): + The Inline source for the input content for + products. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2beta.types.GcsSource): + Google Cloud Storage location for the input + content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + product_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='ProductInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class UserEventInputConfig(proto.Message): + r"""The input config source for user events. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user_event_inline_source (google.cloud.retail_v2beta.types.UserEventInlineSource): + Required. The Inline source for the input + content for UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2beta.types.GcsSource): + Required. Google Cloud Storage location for + the input content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): + Required. BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + user_event_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='UserEventInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class CompletionDataInputConfig(proto.Message): + r"""The input config source for completion data. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): + Required. BigQuery input source. + Add the IAM permission "BigQuery Data Viewer" + for + cloud-retail-customer-data-access@system.gserviceaccount.com + before using this feature otherwise an error is + thrown. + + This field is a member of `oneof`_ ``source``. + """ + + big_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='BigQuerySource', + ) + + +class ImportMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + request_id (str): + Deprecated. This field is never set. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=3, + ) + failure_count = proto.Field( + proto.INT64, + number=4, + ) + request_id = proto.Field( + proto.STRING, + number=5, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=6, + ) + + +class ImportProductsResponse(proto.Message): + r"""Response of the + [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + import_summary (google.cloud.retail_v2beta.types.UserEventImportSummary): + Aggregated statistics of user event import + status. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + import_summary = proto.Field( + proto.MESSAGE, + number=3, + message='UserEventImportSummary', + ) + + +class UserEventImportSummary(proto.Message): + r"""A summary of import result. The UserEventImportSummary + summarizes the import status for user events. + + Attributes: + joined_events_count (int): + Count of user events imported with complete + existing catalog information. + unjoined_events_count (int): + Count of user events imported, but with + catalog information not found in the imported + catalog. + """ + + joined_events_count = proto.Field( + proto.INT64, + number=1, + ) + unjoined_events_count = proto.Field( + proto.INT64, + number=2, + ) + + +class ImportCompletionDataResponse(proto.Message): + r"""Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. + 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 (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py new file mode 100644 index 00000000..f31ba819 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import user_event as gcr_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'PredictRequest', + 'PredictResponse', + }, +) + + +class PredictRequest(proto.Message): + r"""Request message for Predict method. + + Attributes: + placement (str): + Required. Full resource name of the format: + {name=projects/*/locations/global/catalogs/default_catalog/placements/*} + The ID of the Recommendations AI placement. Before you can + request predictions from your model, you must create at + least one placement for it. For more information, see + `Managing + placements `__. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements + user_event (google.cloud.retail_v2beta.types.UserEvent): + Required. Context about the user, what they + are looking at and what action they took to + trigger the predict request. Note that this user + event detail won't be ingested to userEvent + logs. Thus, a separate userEvent write request + is required for event logging. + page_size (int): + Maximum number of results to return per page. + Set this property to the number of prediction + results needed. If zero, the service will choose + a reasonable default. The maximum allowed value + is 100. Values above 100 will be coerced to 100. + page_token (str): + The previous PredictResponse.next_page_token. + filter (str): + Filter for restricting prediction results with a length + limit of 5,000 characters. Accepts values for tags and the + ``filterOutOfStockItems`` flag. + + - Tag expressions. Restricts predictions to products that + match all of the specified tags. Boolean operators ``OR`` + and ``NOT`` are supported if the expression is enclosed + in parentheses, and must be separated from the tag values + by a space. ``-"tagA"`` is also supported and is + equivalent to ``NOT "tagA"``. Tag values must be double + quoted UTF-8 encoded strings with a size limit of 1,000 + characters. + + Note: "Recently viewed" models don't support tag + filtering at the moment. + + - filterOutOfStockItems. Restricts predictions to products + that do not have a stockState value of OUT_OF_STOCK. + + Examples: + + - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT + "promotional") + - filterOutOfStockItems tag=(-"promotional") + - filterOutOfStockItems + + If your filter blocks all prediction results, the API will + return generic (unfiltered) popular products. If you only + want results strictly matching the filters, set + ``strictFiltering`` to True in ``PredictRequest.params`` to + receive empty results instead. Note that the API will never + return items with storageStatus of "EXPIRED" or "DELETED" + regardless of filter choices. + validate_only (bool): + Use validate only mode for this prediction + query. If set to true, a dummy model will be + used that returns arbitrary products. Note that + the validate only mode should only be used for + testing the API, or if the model is not ready. + params (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific parameters for the predictions. + + Allowed values: + + - ``returnProduct``: Boolean. If set to true, the + associated product object will be returned in the + ``results.metadata`` field in the prediction response. + - ``returnScore``: Boolean. If set to true, the prediction + 'score' corresponding to each returned product will be + set in the ``results.metadata`` field in the prediction + response. The given 'score' indicates the probability of + an product being clicked/purchased given the user's + context and history. + - ``strictFiltering``: Boolean. True by default. If set to + false, the service will return generic (unfiltered) + popular products instead of empty if your filter blocks + all prediction results. + - ``priceRerankLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of + {'no-price-reranking', 'low-price-reranking', + 'medium-price-reranking', 'high-price-reranking'}. This + gives request-level control and adjusts prediction + results based on product price. + - ``diversityLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of {'no-diversity', + 'low-diversity', 'medium-diversity', 'high-diversity', + 'auto-diversity'}. This gives request-level control and + adjusts prediction results based on product category. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters, and cannot be empty. Values can + be empty, and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + placement = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + filter = proto.Field( + proto.STRING, + number=5, + ) + validate_only = proto.Field( + proto.BOOL, + number=6, + ) + params = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class PredictResponse(proto.Message): + r"""Response message for predict method. + + Attributes: + results (Sequence[google.cloud.retail_v2beta.types.PredictResponse.PredictionResult]): + A list of recommended products. The order + represents the ranking (from the most relevant + product to the least). + attribution_token (str): + A unique attribution token. This should be included in the + [UserEvent][google.cloud.retail.v2beta.UserEvent] logs + resulting from this recommendation, which enables accurate + attribution of recommendation model performance. + missing_ids (Sequence[str]): + IDs of products in the request that were + missing from the inventory. + validate_only (bool): + True if the validateOnly property was set in + the request. + """ + + class PredictionResult(proto.Message): + r"""PredictionResult represents the recommendation prediction + results. + + Attributes: + id (str): + ID of the recommended product + metadata (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional product metadata / annotations. + + Possible values: + + - ``product``: JSON representation of the product. Will be + set if ``returnProduct`` is set to true in + ``PredictRequest.params``. + - ``score``: Prediction score in double value. Will be set + if ``returnScore`` is set to true in + ``PredictRequest.params``. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + metadata = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=PredictionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + missing_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py new file mode 100644 index 00000000..bd0de773 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py @@ -0,0 +1,705 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'Product', + }, +) + + +class Product(proto.Message): + r"""Product captures all metadata information of items to be + recommended or searched. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this product becomes unavailable for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + If it is set, the + [Product][google.cloud.retail.v2beta.Product] is not + available for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + after + [expire_time][google.cloud.retail.v2beta.Product.expire_time]. + However, the product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + [expire_time][google.cloud.retail.v2beta.Product.expire_time] + must be later than + [available_time][google.cloud.retail.v2beta.Product.available_time] + and + [publish_time][google.cloud.retail.v2beta.Product.publish_time], + otherwise an INVALID_ARGUMENT error is thrown. + + Corresponding properties: Google Merchant Center property + `expiration_date `__. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Input only. The TTL (time to live) of the product. + + If it is set, it must be a non-negative value, and + [expire_time][google.cloud.retail.v2beta.Product.expire_time] + is set as current timestamp plus + [ttl][google.cloud.retail.v2beta.Product.ttl]. The derived + [expire_time][google.cloud.retail.v2beta.Product.expire_time] + is returned in the output and + [ttl][google.cloud.retail.v2beta.Product.ttl] is left blank + when retrieving the + [Product][google.cloud.retail.v2beta.Product]. + + If it is set, the product is not available for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + after current timestamp plus + [ttl][google.cloud.retail.v2beta.Product.ttl]. However, the + product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This field is a member of `oneof`_ ``expiration``. + name (str): + Immutable. Full resource name of the product, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. + id (str): + Immutable. [Product][google.cloud.retail.v2beta.Product] + identifier, which is the final component of + [name][google.cloud.retail.v2beta.Product.name]. For + example, this field is "id_1", if + [name][google.cloud.retail.v2beta.Product.name] is + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `id `__. + Schema.org property + `Product.sku `__. + type_ (google.cloud.retail_v2beta.types.Product.Type): + Immutable. The type of the product. Default to + [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2beta.ProductLevelConfig.ingestion_product_type] + if unset. + primary_product_id (str): + Variant group identifier. Must be an + [id][google.cloud.retail.v2beta.Product.id], with the same + parent branch with this product. Otherwise, an error is + thrown. + + For + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]s, this field + can only be empty or set to the same value as + [id][google.cloud.retail.v2beta.Product.id]. + + For VARIANT [Product][google.cloud.retail.v2beta.Product]s, + this field cannot be empty. A maximum of 2,000 products are + allowed to share the same + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `item_group_id `__. + Schema.org property + `Product.inProductGroupWithID `__. + collection_member_ids (Sequence[str]): + The [id][google.cloud.retail.v2beta.Product.id] of the + collection members when + [type][google.cloud.retail.v2beta.Product.type] is + [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION]. + + Non-existent product ids are allowed. The + [type][google.cloud.retail.v2beta.Product.type] of the + members must be either + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + or + [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + otherwise and INVALID_ARGUMENT error is thrown. Should not + set it for other types. A maximum of 1000 values are + allowed. Otherwise, an INVALID_ARGUMENT error is return. + gtin (str): + The Global Trade Item Number (GTIN) of the product. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This field must be a Unigram. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `gtin `__. + Schema.org property + `Product.isbn `__, + `Product.gtin8 `__, + `Product.gtin12 `__, + `Product.gtin13 `__, or + `Product.gtin14 `__. + + If the value is not a valid GTIN, an INVALID_ARGUMENT error + is returned. + categories (Sequence[str]): + Product categories. This field is repeated for supporting + one product belonging to several parallel categories. + Strongly recommended using the full path for better search / + recommendation quality. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + For example, if a shoes product belongs to both ["Shoes & + Accessories" -> "Shoes"] and ["Sports & Fitness" -> + "Athletic Clothing" -> "Shoes"], it could be represented as: + + :: + + "categories": [ + "Shoes & Accessories > Shoes", + "Sports & Fitness > Athletic Clothing > Shoes" + ] + + Must be set for + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] otherwise an + INVALID_ARGUMENT error is returned. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2beta.Product]. Empty values + are not allowed. Each value must be a UTF-8 encoded string + with a length limit of 5,000 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `google_product_category `__. + Schema.org property [Product.category] + (https://schema.org/category). + title (str): + Required. Product title. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `title `__. + Schema.org property + `Product.name `__. + brands (Sequence[str]): + The brands of the product. + + A maximum of 30 brands are allowed. Each brand must be a + UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `brand `__. + Schema.org property + `Product.brand `__. + description (str): + Product description. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `description `__. + Schema.org property + `Product.description `__. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. + + For product prediction, this field is ignored and the model + automatically detects the text language. The + [Product][google.cloud.retail.v2beta.Product] can include + text in different languages, but duplicating + [Product][google.cloud.retail.v2beta.Product]s to provide + text in multiple languages can result in degraded model + performance. + + For product search this field is in use. It defaults to + "en-US" if unset. + attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): + Highly encouraged. Extra product attributes to be included. + For example, for products, this could include the store + name, vendor, style, color, etc. These are very strong + signals for recommendation model, thus we highly recommend + providing the attributes here. + + Features that can take on one of a limited number of + possible values. Two types of features can be set are: + + Textual features. some examples would be the brand/maker of + a product, or country of a customer. Numerical features. + Some examples would be the height/weight of a product, or + age of a customer. + + For example: + ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - Max entries count: 200. + - The key must be a UTF-8 encoded string with a length + limit of 128 characters. + - For indexable attribute, the key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, + ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a + non-empty UTF-8 encoded string with a length limit of 256 + characters. + - For number attributes, at most 400 values are allowed. + tags (Sequence[str]): + Custom tags associated with the product. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2beta.Product]. This value + must be a UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This tag can be used for filtering recommendation results by + passing the tag as part of the + [PredictRequest.filter][google.cloud.retail.v2beta.PredictRequest.filter]. + + Corresponding properties: Google Merchant Center property + `custom_label_0–4 `__. + price_info (google.cloud.retail_v2beta.types.PriceInfo): + Product price and cost information. + + Corresponding properties: Google Merchant Center property + `price `__. + rating (google.cloud.retail_v2beta.types.Rating): + The rating of this product. + available_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this + [Product][google.cloud.retail.v2beta.Product] becomes + available for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + availability (google.cloud.retail_v2beta.types.Product.Availability): + The online availability of the + [Product][google.cloud.retail.v2beta.Product]. Default to + [Availability.IN_STOCK][google.cloud.retail.v2beta.Product.Availability.IN_STOCK]. + + Corresponding properties: Google Merchant Center property + `availability `__. + Schema.org property + `Offer.availability `__. + available_quantity (google.protobuf.wrappers_pb2.Int32Value): + The available quantity of the item. + fulfillment_info (Sequence[google.cloud.retail_v2beta.types.FulfillmentInfo]): + Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + All the elements must have distinct + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type]. + Otherwise, an INVALID_ARGUMENT error is returned. + uri (str): + Canonical URL directly linking to the product detail page. + + It is strongly recommended to provide a valid uri for the + product, otherwise the service performance could be + significantly degraded. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `link `__. + Schema.org property `Offer.url `__. + images (Sequence[google.cloud.retail_v2beta.types.Image]): + Product images for the product. We highly recommend putting + the main image first. + + A maximum of 300 images are allowed. + + Corresponding properties: Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + audience (google.cloud.retail_v2beta.types.Audience): + The target group associated with a given + audience (e.g. male, veterans, car owners, + musicians, etc.) of the product. + color_info (google.cloud.retail_v2beta.types.ColorInfo): + The color of the product. + + Corresponding properties: Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + sizes (Sequence[str]): + The size of the product. To represent different size systems + or size types, consider using this format: + [[[size_system:]size_type:]size_value]. + + For example, in "US:MENS:M", "US" represents size system; + "MENS" represents size type; "M" represents size value. In + "GIRLS:27", size system is empty; "GIRLS" represents size + type; "27" represents size value. In "32 inches", both size + system and size type are empty, while size value is "32 + inches". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2beta.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `size `__, + `size_type `__, + and + `size_system `__. + Schema.org property + `Product.size `__. + materials (Sequence[str]): + The material of the product. For example, "leather", + "wooden". + + A maximum of 20 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 200 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `material `__. + Schema.org property + `Product.material `__. + patterns (Sequence[str]): + The pattern or graphic print of the product. For example, + "striped", "polka dot", "paisley". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2beta.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `pattern `__. + Schema.org property + `Product.pattern `__. + conditions (Sequence[str]): + The condition of the product. Strongly encouraged to use the + standard values: "new", "refurbished", "used". + + A maximum of 1 value is allowed per + [Product][google.cloud.retail.v2beta.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `condition `__. + Schema.org property + `Offer.itemCondition `__. + promotions (Sequence[google.cloud.retail_v2beta.types.Promotion]): + The promotions applied to the product. A maximum of 10 + values are allowed per + [Product][google.cloud.retail.v2beta.Product]. Only + [Promotion.promotion_id][google.cloud.retail.v2beta.Promotion.promotion_id] + will be used, other fields will be ignored if set. + publish_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the product is published by the retailer + for the first time, which indicates the freshness of the + products. Note that this field is different from + [available_time][google.cloud.retail.v2beta.Product.available_time], + given it purely describes product freshness regardless of + when it is available on search and recommendation. + retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the + [Product][google.cloud.retail.v2beta.Product]s are returned + in + [SearchResponse][google.cloud.retail.v2beta.SearchResponse]. + + Supported fields for all + [type][google.cloud.retail.v2beta.Product.type]s: + + - [audience][google.cloud.retail.v2beta.Product.audience] + - [availability][google.cloud.retail.v2beta.Product.availability] + - [brands][google.cloud.retail.v2beta.Product.brands] + - [color_info][google.cloud.retail.v2beta.Product.color_info] + - [conditions][google.cloud.retail.v2beta.Product.conditions] + - [gtin][google.cloud.retail.v2beta.Product.gtin] + - [materials][google.cloud.retail.v2beta.Product.materials] + - [name][google.cloud.retail.v2beta.Product.name] + - [patterns][google.cloud.retail.v2beta.Product.patterns] + - [price_info][google.cloud.retail.v2beta.Product.price_info] + - [rating][google.cloud.retail.v2beta.Product.rating] + - [sizes][google.cloud.retail.v2beta.Product.sizes] + - [title][google.cloud.retail.v2beta.Product.title] + - [uri][google.cloud.retail.v2beta.Product.uri] + + Supported fields only for + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION]: + + - [categories][google.cloud.retail.v2beta.Product.categories] + - [description][google.cloud.retail.v2beta.Product.description] + - [images][google.cloud.retail.v2beta.Product.images] + + Supported fields only for + [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT]: + + - Only the first image in + [images][google.cloud.retail.v2beta.Product.images] + + To mark + [attributes][google.cloud.retail.v2beta.Product.attributes] + as retrievable, include paths of the form "attributes.key" + where "key" is the key of a custom attribute, as specified + in + [attributes][google.cloud.retail.v2beta.Product.attributes]. + + For + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION], + the following fields are always returned in + [SearchResponse][google.cloud.retail.v2beta.SearchResponse] + by default: + + - [name][google.cloud.retail.v2beta.Product.name] + + For + [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT], + the following fields are always returned in by default: + + - [name][google.cloud.retail.v2beta.Product.name] + - [color_info][google.cloud.retail.v2beta.Product.color_info] + + Maximum number of paths is 30. Otherwise, an + INVALID_ARGUMENT error is returned. + + Note: Returning more fields in + [SearchResponse][google.cloud.retail.v2beta.SearchResponse] + may increase response payload size and serving latency. + variants (Sequence[google.cloud.retail_v2beta.types.Product]): + Output only. Product variants grouped together on primary + product which share similar product attributes. It's + automatically grouped by + [primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] + for all the product variants. Only populated for + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct]. + Do not set this field in API requests. + """ + class Type(proto.Enum): + r"""The type of this product.""" + TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + VARIANT = 2 + COLLECTION = 3 + + class Availability(proto.Enum): + r"""Product availability. If this field is unspecified, the + product is assumed to be in stock. + """ + AVAILABILITY_UNSPECIFIED = 0 + IN_STOCK = 1 + OUT_OF_STOCK = 2 + PREORDER = 3 + BACKORDER = 4 + + expire_time = proto.Field( + proto.MESSAGE, + number=16, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl = proto.Field( + proto.MESSAGE, + number=17, + oneof='expiration', + message=duration_pb2.Duration, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + type_ = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + primary_product_id = proto.Field( + proto.STRING, + number=4, + ) + collection_member_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + gtin = proto.Field( + proto.STRING, + number=6, + ) + categories = proto.RepeatedField( + proto.STRING, + number=7, + ) + title = proto.Field( + proto.STRING, + number=8, + ) + brands = proto.RepeatedField( + proto.STRING, + number=9, + ) + description = proto.Field( + proto.STRING, + number=10, + ) + language_code = proto.Field( + proto.STRING, + number=11, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message=common.CustomAttribute, + ) + tags = proto.RepeatedField( + proto.STRING, + number=13, + ) + price_info = proto.Field( + proto.MESSAGE, + number=14, + message=common.PriceInfo, + ) + rating = proto.Field( + proto.MESSAGE, + number=15, + message=common.Rating, + ) + available_time = proto.Field( + proto.MESSAGE, + number=18, + message=timestamp_pb2.Timestamp, + ) + availability = proto.Field( + proto.ENUM, + number=19, + enum=Availability, + ) + available_quantity = proto.Field( + proto.MESSAGE, + number=20, + message=wrappers_pb2.Int32Value, + ) + fulfillment_info = proto.RepeatedField( + proto.MESSAGE, + number=21, + message=common.FulfillmentInfo, + ) + uri = proto.Field( + proto.STRING, + number=22, + ) + images = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=common.Image, + ) + audience = proto.Field( + proto.MESSAGE, + number=24, + message=common.Audience, + ) + color_info = proto.Field( + proto.MESSAGE, + number=25, + message=common.ColorInfo, + ) + sizes = proto.RepeatedField( + proto.STRING, + number=26, + ) + materials = proto.RepeatedField( + proto.STRING, + number=27, + ) + patterns = proto.RepeatedField( + proto.STRING, + number=28, + ) + conditions = proto.RepeatedField( + proto.STRING, + number=29, + ) + promotions = proto.RepeatedField( + proto.MESSAGE, + number=34, + message=promotion.Promotion, + ) + publish_time = proto.Field( + proto.MESSAGE, + number=33, + message=timestamp_pb2.Timestamp, + ) + retrievable_fields = proto.Field( + proto.MESSAGE, + number=30, + message=field_mask_pb2.FieldMask, + ) + variants = proto.RepeatedField( + proto.MESSAGE, + number=31, + message='Product', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py new file mode 100644 index 00000000..06a23d13 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py @@ -0,0 +1,844 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'CreateProductRequest', + 'GetProductRequest', + 'UpdateProductRequest', + 'DeleteProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'SetInventoryRequest', + 'SetInventoryMetadata', + 'SetInventoryResponse', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesResponse', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesResponse', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesResponse', + }, +) + + +class CreateProductRequest(proto.Message): + r"""Request message for [CreateProduct][] method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + product (google.cloud.retail_v2beta.types.Product): + Required. The [Product][google.cloud.retail.v2beta.Product] + to create. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2beta.Product], which will + become the final component of the + [Product.name][google.cloud.retail.v2beta.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2beta.Product]s with the same + [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + product_id = proto.Field( + proto.STRING, + number=3, + ) + + +class GetProductRequest(proto.Message): + r"""Request message for [GetProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested + [Product][google.cloud.retail.v2beta.Product] does not + exist, a NOT_FOUND error is returned. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateProductRequest(proto.Message): + r"""Request message for [UpdateProduct][] method. + + Attributes: + product (google.cloud.retail_v2beta.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Product][google.cloud.retail.v2beta.Product] to update. The + immutable and output only fields are NOT supported. If not + set, all supported fields (the fields that are neither + immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + a new [Product][google.cloud.retail.v2beta.Product] will be + created. In this situation, ``update_mask`` is ignored. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteProductRequest(proto.Message): + r"""Request message for [DeleteProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2beta.Product] to delete + can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] with more than + one + [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2beta.Product] will be + deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProductsRequest(proto.Message): + r"""Request message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list products + under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2beta.Product]s under this + branch, regardless of whether or not this branch exists, a + PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [Product][google.cloud.retail.v2beta.Product]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 + [ListProductsResponse.next_page_token][google.cloud.retail.v2beta.ListProductsResponse.next_page_token], + received from a previous + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + filter (str): + A filter to apply on the list results. Supported features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2beta.ListProductsRequest.filter] + is unset. + - List + [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s sharing + the same + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]. For + example: ``primary_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2beta.Product]s + bundled in a + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product]. For + example: ``collection_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2beta.Product]s with + a partibular type. For example: ``type = "PRIMARY"`` + ``type = "VARIANT"`` ``type = "COLLECTION"`` + + If the field is unrecognizable, an INVALID_ARGUMENT error is + returned. + + If the specified + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] or + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product] does not + exist, a NOT_FOUND error is returned. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields of [Product][google.cloud.retail.v2beta.Product] + to return in the responses. If not set or empty, the + following fields are returned: + + - [Product.name][google.cloud.retail.v2beta.Product.name] + - [Product.id][google.cloud.retail.v2beta.Product.id] + - [Product.title][google.cloud.retail.v2beta.Product.title] + - [Product.uri][google.cloud.retail.v2beta.Product.uri] + - [Product.images][google.cloud.retail.v2beta.Product.images] + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.brands][google.cloud.retail.v2beta.Product.brands] + + If "*" is provided, all fields are returned. + [Product.name][google.cloud.retail.v2beta.Product.name] is + always returned no matter what mask is set. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class ListProductsResponse(proto.Message): + r"""Response message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + + Attributes: + products (Sequence[google.cloud.retail_v2beta.types.Product]): + The [Product][google.cloud.retail.v2beta.Product]s. + next_page_token (str): + A token that can be sent as + [ListProductsRequest.page_token][google.cloud.retail.v2beta.ListProductsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class SetInventoryRequest(proto.Message): + r"""Request message for [SetInventory][] method. + + Attributes: + inventory (google.cloud.retail_v2beta.types.Product): + Required. The inventory information to update. The allowable + fields to update are: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product] named in + [Product.name][google.cloud.retail.v2beta.Product.name], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2beta.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting the + last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of fulfillment + types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear in + [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types have + empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following inventory + fields: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + + If a full overwrite of inventory information while ignoring + timestamps is needed, [UpdateProduct][] should be invoked + instead. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2beta.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the request is issued, used to + prevent out-of-order updates on inventory fields + with the last update time recorded. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] with name + [Product.name][google.cloud.retail.v2beta.Product.name] is + not found, the inventory update will still be processed and + retained for at most 1 day until the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + inventory = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + set_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + set_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=4, + ) + + +class SetInventoryMetadata(proto.Message): + r"""Metadata related to the progress of the SetInventory operation. + Currently empty because there is no meaningful metadata populated + from the [SetInventory][] method. + + """ + + +class SetInventoryResponse(proto.Message): + r"""Response of the SetInventoryRequest. Currently empty because there + is no meaningful response populated from the [SetInventory][] + method. + + """ + + +class AddFulfillmentPlacesRequest(proto.Message): + r"""Request message for [AddFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery" to be added for this + [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type]. + Duplicate IDs will be automatically ignored. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If the total number of place IDs exceeds 2000 for this + [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type] + after adding, then the update will be rejected. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + the fulfillment information will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + add_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class AddFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the AddFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [AddFulfillmentPlaces][] method. + + """ + + +class AddFulfillmentPlacesResponse(proto.Message): + r"""Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + + +class AddLocalInventoriesRequest(proto.Message): + r"""Request message for [AddLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + local_inventories (Sequence[google.cloud.retail_v2beta.types.LocalInventory]): + Required. A list of inventory information at + difference places. Each place is identified by + its place ID. At most 3000 inventories are + allowed per request. + add_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided list of + [LocalInventory][google.cloud.retail.v2beta.LocalInventory] + to update. The field is updated to the provided value. + + If a field is set while the place does not have a previous + local inventory, the local inventory at that store is + created. + + If a field is set while the value of that field is not + provided, the original field value, if it exists, is + deleted. + + If the mask is not set or set with empty paths, all + inventory fields will be updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory updates are + issued. Used to prevent out-of-order updates on + local inventory fields. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + the local inventory will still be processed and retained for + at most 1 day and processed once the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + local_inventories = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.LocalInventory, + ) + add_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + add_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=6, + ) + + +class AddLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the AddLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [AddLocalInventories][] method. + + """ + + +class AddLocalInventoriesResponse(proto.Message): + r"""Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesRequest(proto.Message): + r"""Request message for [RemoveLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + place_ids (Sequence[str]): + Required. A list of place IDs to have their + inventory deleted. At most 3000 place IDs are + allowed per request. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory deletions are + issued. Used to prevent out-of-order updates and + deletions on local inventory fields. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + the local inventory removal request will still be processed + and retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class RemoveLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesResponse(proto.Message): + r"""Response of the [RemoveLocalInventories][] API. Currently empty + because there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + + +class RemoveFulfillmentPlacesRequest(proto.Message): + r"""Request message for [RemoveFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2beta.RemoveFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery", to be removed for this + [type][google.cloud.retail.v2beta.RemoveFulfillmentPlacesRequest.type]. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + the fulfillment information will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class RemoveFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveFulfillmentPlaces][] method. + + """ + + +class RemoveFulfillmentPlacesResponse(proto.Message): + r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty + because there is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py new file mode 100644 index 00000000..be192a70 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'Promotion', + }, +) + + +class Promotion(proto.Message): + r"""Promotion information. + + Attributes: + promotion_id (str): + ID of the promotion. For example, "free gift". + + The value must be a UTF-8 encoded string with a length limit + of 128 characters, and match the pattern: + ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or + ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is + returned. + + Google Merchant Center property + `promotion `__. + """ + + promotion_id = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py new file mode 100644 index 00000000..95c99126 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + }, +) + + +class PurgeMetadata(proto.Message): + r"""Metadata related to the progress of the Purge operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + """ + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + + Attributes: + parent (str): + Required. The resource name of the catalog under which the + events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}`` + filter (str): + Required. The filter string to specify the events to be + deleted with a length limit of 5,000 characters. Empty + string filter is not allowed. The eligible fields for + filtering are: + + - ``eventType``: Double quoted + [UserEvent.event_type][google.cloud.retail.v2beta.UserEvent.event_type] + string. + - ``eventTime``: in ISO 8601 "zulu" format. + - ``visitorId``: Double quoted string. Specifying this will + delete all events associated with a visitor. + - ``userId``: Double quoted string. Specifying this will + delete all events associated with a user. + + Examples: + + - Deleting all events in a time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + - Deleting specific eventType in time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + - Deleting all events for a specific visitor: + ``visitorId = "visitor1024"`` + + The filtering fields are assumed to have an implicit AND. + force (bool): + Actually perform the purge. If ``force`` is set to false, + the method will return the expected purge count without + deleting any user events. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsResponse(proto.Message): + r"""Response of the PurgeUserEventsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purged_events_count (int): + The total count of events purged as a result + of the operation. + """ + + purged_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py new file mode 100644 index 00000000..21447a27 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py @@ -0,0 +1,1074 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'SearchRequest', + 'SearchResponse', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + + Attributes: + placement (str): + Required. The resource name of the search engine placement, + such as + ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` + This field is used to identify the serving configuration + name and the set of models that will be used to make the + search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + + Use "default_branch" as the branch ID or leave this field + empty, to search products under the default branch. + query (str): + Raw search query. + visitor_id (str): + Required. A unique identifier for tracking visitors. For + example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + This should be the same identifier as + [UserEvent.visitor_id][google.cloud.retail.v2beta.UserEvent.visitor_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2beta.types.UserInfo): + User information. + page_size (int): + Maximum number of + [Product][google.cloud.retail.v2beta.Product]s to return. If + unspecified, defaults to a reasonable value. The maximum + allowed value is 120. Values above 120 will be coerced to + 120. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [SearchResponse.next_page_token][google.cloud.retail.v2beta.SearchResponse.next_page_token], + received from a previous + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Product][google.cloud.retail.v2beta.Product]s deemed by the + API as relevant) in search results. This field is only + considered if + [page_token][google.cloud.retail.v2beta.SearchRequest.page_token] + is unset. + + If this field is negative, an INVALID_ARGUMENT is returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. Filter expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + canonical_filter (str): + The default filter that is applied when a user performs a + search without checking any filters on the search page. + + The filter applied to every search request when quality + improvement such as query expansion is needed. For example, + if a query does not have enough results, an expanded query + with + [SearchRequest.canonical_filter][google.cloud.retail.v2beta.SearchRequest.canonical_filter] + will be returned as a supplement of the original query. This + field is strongly recommended to achieve high search + quality. + + See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for more details about filter syntax. + order_by (str): + The order in which products are returned. Products can be + ordered by a field in an + [Product][google.cloud.retail.v2beta.Product] object. Leave + it unset if ordered by relevance. OrderBy expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + facet_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + dynamic_facet_spec (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec): + Deprecated. Refer to + https://cloud.google.com/retail/docs/configs#dynamic + to enable dynamic facets. Do not set this field. + The specification for dynamically generated + facets. Notice that only textual facets can be + dynamically generated. + boost_spec (google.cloud.retail_v2beta.types.SearchRequest.BoostSpec): + Boost specification to boost certain products. See more + details at this `user + guide `__. + + Notice that if both + [ServingConfig.boost_control_ids][google.cloud.retail.v2beta.ServingConfig.boost_control_ids] + and [SearchRequest.boost_spec] are set, the boost conditions + from both places are evaluated. If a search request matches + multiple boost conditions, the final boost score is equal to + the sum of the boost scores from all matched boost + conditions. + query_expansion_spec (google.cloud.retail_v2beta.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that specifies the + conditions under which query expansion will occur. See more + details at this `user + guide `__. + variant_rollup_keys (Sequence[str]): + The keys to fetch and rollup the matching + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s attributes, + [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo] + or + [LocalInventory][google.cloud.retail.v2beta.LocalInventory]s + attributes. The attributes from all the matching + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s or + [LocalInventory][google.cloud.retail.v2beta.LocalInventory]s + are merged and de-duplicated. Notice that rollup attributes + will lead to extra query latency. Maximum number of keys is + 30. + + For + [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], + a fulfillment type and a fulfillment ID must be provided in + the format of "fulfillmentType.fulfillmentId". E.g., in + "pickupInStore.store123", "pickupInStore" is fulfillment + type and "store123" is the store ID. + + Supported keys are: + + - colorFamilies + - price + - originalPrice + - discount + - variantId + - inventory(place_id,price) + - inventory(place_id,original_price) + - inventory(place_id,attributes.key), where key is any key + in the [Product.inventories.attributes][] map. + - attributes.key, where key is any key in the + [Product.attributes][google.cloud.retail.v2beta.Product.attributes] + map. + - pickupInStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "pickup-in-store". + - shipToStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "ship-to-store". + - sameDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "same-day-delivery". + - nextDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "next-day-delivery". + - customFulfillment1.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-1". + - customFulfillment2.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-2". + - customFulfillment3.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-3". + - customFulfillment4.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-4". + - customFulfillment5.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-5". + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. Required for + category navigation queries to achieve good search quality. + The format should be the same as + [UserEvent.page_categories][google.cloud.retail.v2beta.UserEvent.page_categories]; + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + search_mode (google.cloud.retail_v2beta.types.SearchRequest.SearchMode): + The search mode of the search request. If not + specified, a single search request triggers both + product search and faceted search. + personalization_spec (google.cloud.retail_v2beta.types.SearchRequest.PersonalizationSpec): + The specification for personalization. + """ + class SearchMode(proto.Enum): + r"""The search mode of each search request.""" + SEARCH_MODE_UNSPECIFIED = 0 + PRODUCT_SEARCH_ONLY = 1 + FACETED_SEARCH_ONLY = 2 + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.retail_v2beta.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum of facet values that should be returned for this + facet. If unspecified, defaults to 20. The maximum allowed + value is 300. Values above 300 will be coerced to 300. + + If this field is negative, an INVALID_ARGUMENT is returned. + excluded_filter_keys (Sequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + For example, suppose there are 100 products with color facet + "Red" and 200 products with color facet "Blue". A query + containing the filter "colorFamilies:ANY("Red")" and have + "colorFamilies" as + [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] + will by default return the "Red" with count 100. + + If this field contains "colorFamilies", then the query + returns both the "Red" with count 100 and "Blue" with count + 200, because the "colorFamilies" key is now excluded from + the filter. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined by Google Retail Search. It will be ordered + together with dynamic facets if dynamic facets is enabled. + If set to false, the position of this facet in the response + will be the same as in the request, and it will be ranked + before the facets with dynamic position enable and all + dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response will be determined by Google Retail + Search. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enable, which will + generate a facet 'gender'. Then the final order of the + facets in the response can be ("price", "brands", "rating", + "gender") or ("price", "brands", "gender", "rating") depends + on how Google Retail Search orders "gender" and "rating" + facets. However, notice that "price" and "brands" will + always be ranked at 1st and 2nd position since their + enable_dynamic_position are false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Product][google.cloud.retail.v2beta.Product] object, over + which the facet values are computed. Facet key is + case-sensitive. + + Allowed facet keys when + [FacetKey.query][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.query] + is not specified: + + - textual_field = + + - "brands" + - "categories" + - "genders" + - "ageGroups" + - "availability" + - "colorFamilies" + - "colors" + - "sizes" + - "materials" + - "patterns" + - "conditions" + - "attributes.key" + - "pickupInStore" + - "shipToStore" + - "sameDayDelivery" + - "nextDayDelivery" + - "customFulfillment1" + - "customFulfillment2" + - "customFulfillment3" + - "customFulfillment4" + - "customFulfillment5" + - "inventory(place_id,attributes.key)" + + - numerical_field = + + - "price" + - "discount" + - "rating" + - "ratingCount" + - "attributes.key" + - "inventory(place_id,price)" + - "inventory(place_id,original_price)" + - "inventory(place_id,attributes.key)". + intervals (Sequence[google.cloud.retail_v2beta.types.Interval]): + Set only if values should be bucketized into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (Sequence[str]): + Only get facet for the given restricted values. For example, + when using "pickupInStore" as key and set restricted values + to ["store123", "store456"], only facets for "store123" and + "store456" are returned. Only supported on textual fields + and fulfillments. Maximum is 20. + + Must be set for the fulfillment facet keys: + + - pickupInStore + + - shipToStore + + - sameDayDelivery + + - nextDayDelivery + + - customFulfillment1 + + - customFulfillment2 + + - customFulfillment3 + + - customFulfillment4 + + - customFulfillment5 + prefixes (Sequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "categories" has three values "Women > Shoe", + "Women > Dress" and "Men > Shoe". If set + "prefixes" to "Women", the "categories" facet + will give only "Women > Shoe" and "Women > + Dress". Only supported on textual fields. + Maximum is 10. + contains (Sequence[str]): + Only get facet values that contains the given + strings. For example, suppose "categories" has + three values "Women > Shoe", "Women > Dress" and + "Men > Shoe". If set "contains" to "Shoe", the + "categories" facet will give only "Women > Shoe" + and "Men > Shoe". Only supported on textual + fields. Maximum is 10. + order_by (str): + The order in which [Facet.values][] are returned. + + Allowed values are: + + - "count desc", which means order by + [Facet.FacetValue.count][] descending. + + - "value desc", which means order by + [Facet.FacetValue.value][] descending. Only applies to + textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.intervals]; + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + are sorted in the order given by + [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.restricted_values]. + query (str): + The query that is used to compute facet for the given facet + key. When provided, it will override the default behavior of + facet computation. The query syntax is the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for detail syntax and limitations. Notice that there is no + limitation on + [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] + when query is specified. + + In the response, [FacetValue.value][] will be always "1" and + [FacetValue.count][] will be the number of results that + matches the query. + + For example, you can set a customized facet for + "shipToStore", where + [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] + is "customizedShipToStore", and + [FacetKey.query][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.query] + is "availability: ANY("IN_STOCK") AND shipToStore: + ANY("123")". Then the facet will count the products that are + both in stock and ship to store "123". + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + intervals = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes = proto.RepeatedField( + proto.STRING, + number=8, + ) + contains = proto.RepeatedField( + proto.STRING, + number=9, + ) + order_by = proto.Field( + proto.STRING, + number=4, + ) + query = proto.Field( + proto.STRING, + number=5, + ) + + facet_key = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.FacetSpec.FacetKey', + ) + limit = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position = proto.Field( + proto.BOOL, + number=4, + ) + + class DynamicFacetSpec(proto.Message): + r"""The specifications of dynamically generated facets. + + Attributes: + mode (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec.Mode): + Mode of the DynamicFacet feature. Defaults to + [Mode.DISABLED][google.cloud.retail.v2beta.SearchRequest.DynamicFacetSpec.Mode.DISABLED] + if it's unset. + """ + class Mode(proto.Enum): + r"""Enum to control DynamicFacet mode""" + MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.DynamicFacetSpec.Mode', + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain items. + + Attributes: + condition_boost_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a product + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 10. + skip_boost_spec_validation (bool): + Whether to skip boostspec validation. If this field is set + to true, invalid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] + will be ignored and valid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] + will still be applied. + + This field is a member of `oneof`_ ``_skip_boost_spec_validation``. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to products which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": + + - (id: ANY("product_1", "product_2")) AND + (colorFamilies: ANY("Red","Blue")) + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition = proto.Field( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + skip_boost_spec_validation = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.retail_v2beta.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.retail.v2beta.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 3 + + condition = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.QueryExpansionSpec.Condition', + ) + pin_unexpanded_results = proto.Field( + proto.BOOL, + number=2, + ) + + class PersonalizationSpec(proto.Message): + r"""The specification for personalization. + + Attributes: + mode (google.cloud.retail_v2beta.types.SearchRequest.PersonalizationSpec.Mode): + Defaults to + [Mode.AUTO][google.cloud.retail.v2beta.SearchRequest.PersonalizationSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""The personalization mode of each search request.""" + MODE_UNSPECIFIED = 0 + AUTO = 1 + DISABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.PersonalizationSpec.Mode', + ) + + placement = proto.Field( + proto.STRING, + number=1, + ) + branch = proto.Field( + proto.STRING, + number=2, + ) + query = proto.Field( + proto.STRING, + number=3, + ) + visitor_id = proto.Field( + proto.STRING, + number=4, + ) + user_info = proto.Field( + proto.MESSAGE, + number=5, + message=common.UserInfo, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + offset = proto.Field( + proto.INT32, + number=9, + ) + filter = proto.Field( + proto.STRING, + number=10, + ) + canonical_filter = proto.Field( + proto.STRING, + number=28, + ) + order_by = proto.Field( + proto.STRING, + number=11, + ) + facet_specs = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=FacetSpec, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=21, + message=DynamicFacetSpec, + ) + boost_spec = proto.Field( + proto.MESSAGE, + number=13, + message=BoostSpec, + ) + query_expansion_spec = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionSpec, + ) + variant_rollup_keys = proto.RepeatedField( + proto.STRING, + number=17, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=23, + ) + search_mode = proto.Field( + proto.ENUM, + number=31, + enum=SearchMode, + ) + personalization_spec = proto.Field( + proto.MESSAGE, + number=32, + message=PersonalizationSpec, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + + Attributes: + results (Sequence[google.cloud.retail_v2beta.types.SearchResponse.SearchResult]): + A list of matched items. The order represents + the ranking. + facets (Sequence[google.cloud.retail_v2beta.types.SearchResponse.Facet]): + Results of facets requested by user. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.retail.v2beta.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.retail.v2beta.SearchResponse.total_size] + that matches. + corrected_query (str): + If spell correction applies, the corrected + query. Otherwise, empty. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.retail.v2beta.UserEvent] logs + resulting from this search, which enables accurate + attribution of search model performance. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.retail.v2beta.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + query_expansion_info (google.cloud.retail_v2beta.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search will be performed, and only + [redirect_uri][google.cloud.retail.v2beta.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.retail.v2beta.SearchResponse.attribution_token] + will be set in the response. + applied_controls (Sequence[str]): + The fully qualified resource name of applied + `controls `__. + invalid_condition_boost_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + The invalid + [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] + that are not applied during serving. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Product.id][google.cloud.retail.v2beta.Product.id] of the + searched [Product][google.cloud.retail.v2beta.Product]. + product (google.cloud.retail_v2beta.types.Product): + The product data snippet in the search response. Only + [Product.name][google.cloud.retail.v2beta.Product.name] is + guaranteed to be populated. + + [Product.variants][google.cloud.retail.v2beta.Product.variants] + contains the product variants that match the search query. + If there are multiple product variants matching the query, + top 5 most relevant product variants are returned and + ordered by relevancy. + + If relevancy can be deternmined, use + [matching_variant_fields][google.cloud.retail.v2beta.SearchResponse.SearchResult.matching_variant_fields] + to look up matched product variants fields. If relevancy + cannot be determined, e.g. when searching "shoe" all + products in a shoe product can be a match, 5 product + variants are returned but order is meaningless. + matching_variant_count (int): + The count of matched + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s. + matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): + If a + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] matches the + search query, this map indicates which + [Product][google.cloud.retail.v2beta.Product] fields are + matched. The key is the + [Product.name][google.cloud.retail.v2beta.Product.name], the + value is a field mask of the matched + [Product][google.cloud.retail.v2beta.Product] fields. If + matched attributes cannot be determined, this map will be + empty. + + For example, a key "sku1" with field mask + "products.color_info" indicates there is a match between + "sku1" [ColorInfo][google.cloud.retail.v2beta.ColorInfo] and + the query. + variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): + The rollup matching + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] attributes. + The key is one of the + [SearchRequest.variant_rollup_keys][google.cloud.retail.v2beta.SearchRequest.variant_rollup_keys]. + The values are the merged and de-duplicated + [Product][google.cloud.retail.v2beta.Product] attributes. + Notice that the rollup values are respect filter. For + example, when filtering by "colorFamilies:ANY("red")" and + rollup "colorFamilies", only "red" is returned. + + For textual and numerical attributes, the rollup values is a + list of string or double values with type + [google.protobuf.ListValue][google.protobuf.ListValue]. For + example, if there are two variants with colors "red" and + "blue", the rollup values are + + :: + + { key: "colorFamilies" + value { + list_value { + values { string_value: "red" } + values { string_value: "blue" } + } + } + } + + For + [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], + the rollup values is a double value with type + [google.protobuf.Value][google.protobuf.Value]. For example, + ``{key: "pickupInStore.store1" value { number_value: 10 }}`` + means a there are 10 variants in this product are available + in the store "store1". + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + matching_variant_count = proto.Field( + proto.INT32, + number=3, + ) + matching_variant_fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + variant_rollup_values = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. E.g., "colorFamilies" + or "price" or "attributes.attr1". + values (Sequence[google.cloud.retail_v2beta.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Text value of a facet, such as "Black" for + facet "colorFamilies". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.retail_v2beta.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value = proto.Field( + proto.STRING, + number=1, + oneof='facet_value', + ) + interval = proto.Field( + proto.MESSAGE, + number=2, + oneof='facet_value', + message=common.Interval, + ) + count = proto.Field( + proto.INT64, + number=3, + ) + + key = proto.Field( + proto.STRING, + number=1, + ) + values = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SearchResponse.Facet.FacetValue', + ) + dynamic_facet = proto.Field( + proto.BOOL, + number=3, + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2beta.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count = proto.Field( + proto.INT64, + number=2, + ) + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + corrected_query = proto.Field( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + next_page_token = proto.Field( + proto.STRING, + number=6, + ) + query_expansion_info = proto.Field( + proto.MESSAGE, + number=7, + message=QueryExpansionInfo, + ) + redirect_uri = proto.Field( + proto.STRING, + number=10, + ) + applied_controls = proto.RepeatedField( + proto.STRING, + number=12, + ) + invalid_condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py new file mode 100644 index 00000000..f8b78591 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py @@ -0,0 +1,309 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'ServingConfig', + }, +) + + +class ServingConfig(proto.Message): + r"""Configures metadata that is used to generate serving time results + (e.g. search results or recommendation predictions). The + ServingConfig is passed in the search and predict request and + together with the Catalog.default_branch, generates results. + + Attributes: + name (str): + Immutable. Fully qualified name + projects/\ */locations/global/catalogs/*/servingConfig/\* + display_name (str): + Required. The human readable serving config display name. + Used in Retail UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + model_id (str): + The id of the model to use at serving time. Currently only + RecommendationModels are supported: + https://cloud.google.com/retail/recommendations-ai/docs/create-models + Can be changed but only to a compatible model (e.g. + others-you-may-like CTR to others-you-may-like CVR). + + Required when + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + price_reranking_level (str): + How much price ranking we want in serving results. Price + reranking causes product items with a similar recommendation + probability to be ordered by price, with the highest-priced + items first. This setting could result in a decrease in + click-through and conversion rates. Allowed values are: + + - 'no-price-reranking' + - 'low-price-raranking' + - 'medium-price-reranking' + - 'high-price-reranking' + + If not specified, we choose default based on model type. + Default value: 'no-price-reranking'. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + facet_control_ids (Sequence[str]): + Facet specifications for faceted search. If empty, no facets + are returned. The ids refer to the ids of + [Control][google.cloud.retail.v2beta.Control] resources with + only the Facet control set. These controls are assumed to be + in the same [Catalog][google.cloud.retail.v2beta.Catalog] as + the + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]. A + maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + dynamic_facet_spec (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec): + The specification for dynamically generated facets. Notice + that only textual facets can be dynamically generated. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + boost_control_ids (Sequence[str]): + Condition boost specifications. If a product matches + multiple conditions in the specifications, boost scores from + these specifications are all applied and combined in a + non-linear way. Maximum number of specifications is 100. + + Notice that if both + [ServingConfig.boost_control_ids][google.cloud.retail.v2beta.ServingConfig.boost_control_ids] + and [SearchRequest.boost_spec] are set, the boost conditions + from both places are evaluated. If a search request matches + multiple boost conditions, the final boost score is equal to + the sum of the boost scores from all matched boost + conditions. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + filter_control_ids (Sequence[str]): + Condition filter specifications. If a product matches + multiple conditions in the specifications, filters from + these specifications are all applied and combined via the + AND operator. Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + redirect_control_ids (Sequence[str]): + Condition redirect specifications. Only the first triggered + redirect action is applied, even if multiple apply. Maximum + number of specifications is 1000. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + twoway_synonyms_control_ids (Sequence[str]): + Condition synonyms specifications. If multiple syonyms + conditions match, all matching synonyms control in the list + will execute. Order of controls in the list will not matter. + Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + oneway_synonyms_control_ids (Sequence[str]): + Condition oneway synonyms specifications. If multiple oneway + synonyms conditions match, all matching oneway synonyms + controls in the list will execute. Order of controls in the + list will not matter. Maximum number of specifications is + 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + do_not_associate_control_ids (Sequence[str]): + Condition do not associate specifications. If multiple do + not associate conditions match, all matching do not + associate controls in the list will execute. + + - Order does not matter. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + replacement_control_ids (Sequence[str]): + Condition replacement specifications. + + - Applied according to the order in the list. + - A previously replaced term can not be re-replaced. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + ignore_control_ids (Sequence[str]): + Condition ignore specifications. If multiple ignore + conditions match, all matching ignore controls in the list + will execute. + + - Order does not matter. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + diversity_level (str): + How much diversity to use in recommendation model results + e.g. 'medium-diversity' or 'high-diversity'. Currently + supported values: + + - 'no-diversity' + - 'low-diversity' + - 'medium-diversity' + - 'high-diversity' + - 'auto-diversity' + + If not specified, we choose default based on recommendation + model type. Default value: 'no-diversity'. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + enable_category_filter_level (str): + Whether to add additional category filters on the + 'similar-items' model. If not specified, we enable it by + default. Allowed values are: + + - 'no-category-match': No additional filtering of original + results from the model and the customer's filters. + - 'relaxed-category-match': Only keep results with + categories that match at least one item categories in the + PredictRequests's context item. + + - If customer also sends filters in the PredictRequest, + then the results will satisfy both conditions (user + given and category match). + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + solution_types (Sequence[google.cloud.retail_v2beta.types.SolutionType]): + Required. Immutable. Specifies the solution + types that a serving config can be associated + with. Currently we support setting only one type + of solution. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + model_id = proto.Field( + proto.STRING, + number=3, + ) + price_reranking_level = proto.Field( + proto.STRING, + number=4, + ) + facet_control_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=6, + message=search_service.SearchRequest.DynamicFacetSpec, + ) + boost_control_ids = proto.RepeatedField( + proto.STRING, + number=7, + ) + filter_control_ids = proto.RepeatedField( + proto.STRING, + number=9, + ) + redirect_control_ids = proto.RepeatedField( + proto.STRING, + number=10, + ) + twoway_synonyms_control_ids = proto.RepeatedField( + proto.STRING, + number=18, + ) + oneway_synonyms_control_ids = proto.RepeatedField( + proto.STRING, + number=12, + ) + do_not_associate_control_ids = proto.RepeatedField( + proto.STRING, + number=13, + ) + replacement_control_ids = proto.RepeatedField( + proto.STRING, + number=14, + ) + ignore_control_ids = proto.RepeatedField( + proto.STRING, + number=15, + ) + diversity_level = proto.Field( + proto.STRING, + number=8, + ) + enable_category_filter_level = proto.Field( + proto.STRING, + number=16, + ) + solution_types = proto.RepeatedField( + proto.ENUM, + number=19, + enum=common.SolutionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py new file mode 100644 index 00000000..20edced0 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py @@ -0,0 +1,234 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'CreateServingConfigRequest', + 'UpdateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'AddControlRequest', + 'RemoveControlRequest', + }, +) + + +class CreateServingConfigRequest(proto.Message): + r"""Request for CreateServingConfig method. + + Attributes: + parent (str): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + serving_config (google.cloud.retail_v2beta.types.ServingConfig): + Required. The ServingConfig to create. + serving_config_id (str): + Required. The ID to use for the ServingConfig, which will + become the final component of the ServingConfig's resource + name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-_/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + serving_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_serving_config.ServingConfig, + ) + serving_config_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateServingConfigRequest(proto.Message): + r"""Request for UpdateServingConfig method. + + Attributes: + serving_config (google.cloud.retail_v2beta.types.ServingConfig): + Required. The ServingConfig to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [ServingConfig][google.cloud.retail.v2beta.ServingConfig] to + update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] + + If not set, all supported fields are updated. + """ + + serving_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_serving_config.ServingConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteServingConfigRequest(proto.Message): + r"""Request for DeleteServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetServingConfigRequest(proto.Message): + r"""Request for GetServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListServingConfigsRequest(proto.Message): + r"""Request for ListServingConfigs method. + + Attributes: + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 100. If a + value greater than 100 is provided, at most 100 + results are returned. + page_token (str): + Optional. A page token, received from a previous + ``ListServingConfigs`` call. Provide this to retrieve the + subsequent page. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServingConfigsResponse(proto.Message): + r"""Response for ListServingConfigs method. + + Attributes: + serving_configs (Sequence[google.cloud.retail_v2beta.types.ServingConfig]): + All the ServingConfigs for a given catalog. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + serving_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_serving_config.ServingConfig, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class AddControlRequest(proto.Message): + r"""Request for AddControl method. + + Attributes: + serving_config (str): + Required. The source ServingConfig resource name . Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + control_id (str): + Required. The id of the control to apply. Assumed to be in + the same catalog as the serving config - if id is not found + a NOT_FOUND error is returned. + """ + + serving_config = proto.Field( + proto.STRING, + number=1, + ) + control_id = proto.Field( + proto.STRING, + number=2, + ) + + +class RemoveControlRequest(proto.Message): + r"""Request for RemoveControl method. + + Attributes: + serving_config (str): + Required. The source ServingConfig resource name . Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + control_id (str): + Required. The id of the control to apply. + Assumed to be in the same catalog as the serving + config. + """ + + serving_config = proto.Field( + proto.STRING, + number=1, + ) + control_id = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py new file mode 100644 index 00000000..bf1b1aee --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py @@ -0,0 +1,507 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import product as gcr_product +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'UserEvent', + 'ProductDetail', + 'CompletionDetail', + 'PurchaseTransaction', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Retail API needs + to know about how end users interact with customers' website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + - ``add-to-cart``: Products being added to cart. + - ``category-page-view``: Special pages such as sale or + promotion pages viewed. + - ``detail-page-view``: Products detail page viewed. + - ``home-page-view``: Homepage viewed. + - ``promotion-offered``: Promotion is offered to a user. + - ``promotion-not-offered``: Promotion is not offered to a + user. + - ``purchase-complete``: User finishing a purchase. + - ``search``: Product search. + - ``shopping-cart-page-view``: User viewing a shopping + cart. + visitor_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + The field should not contain PII or user-data. We recommend + to use Google Analystics `Client + ID `__ + for this field. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the sesion_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add visitor_id as prefix. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.retail.v2beta.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + experiment_ids (Sequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups + (e.g. using Retail API, using different + recommendation models). + attribution_token (str): + Highly recommended for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2beta.PredictionService.Predict]. + This field enables accurate attribution of recommendation + model performance. + + The value must be a valid + [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] + for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2beta.PredictionService.Predict]. + The value must be a valid + [SearchResponse.attribution_token][google.cloud.retail.v2beta.SearchResponse.attribution_token] + for user events that are the result of + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + This token enables us to accurately attribute page view or + purchase back to the event and the particular predict + response containing this clicked/purchased product. If user + clicks on product K in the recommendation results, pass + [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] + as a URL parameter to product K's page. When recording + events on product K's page, log the + [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] + to this field. + product_details (Sequence[google.cloud.retail_v2beta.types.ProductDetail]): + The main product details related to the event. + + This field is required for the following event types: + + - ``add-to-cart`` + - ``detail-page-view`` + - ``purchase-complete`` + - ``search`` + + In a ``search`` event, this field represents the products + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [product_details][google.cloud.retail.v2beta.UserEvent.product_details] + is desired. The end user may have not finished browsing the + whole page yet. + completion_detail (google.cloud.retail_v2beta.types.CompletionDetail): + The main auto-completion details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Retail API use those + custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - The key must be a UTF-8 encoded string with a length + limit of 5,000 characters. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a UTF-8 + encoded string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is traffic_channel, which is how a user arrives + at the site. Users can arrive at the site by coming to the + site directly, coming through Google search, or in other + ways. + cart_id (str): + The ID or name of the associated shopping cart. This ID is + used to associate multiple items added or present in the + cart before purchase. + + This can only be set for ``add-to-cart``, + ``purchase-complete``, or ``shopping-cart-page-view`` + events. + purchase_transaction (google.cloud.retail_v2beta.types.PurchaseTransaction): + A transaction represents the entire purchase transaction. + + Required for ``purchase-complete`` events. Other event types + should not set this field. Otherwise, an INVALID_ARGUMENT + error is returned. + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.retail.v2beta.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + At least one of + [search_query][google.cloud.retail.v2beta.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2beta.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. + + See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + order_by (str): + The order in which products are returned. + + See + [SearchRequest.order_by][google.cloud.retail.v2beta.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.retail.v2beta.SearchRequest.offset] + for definition. + + If this field is negative, an INVALID_ARGUMENT is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + + Required for ``category-page-view`` events. At least one of + [search_query][google.cloud.retail.v2beta.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2beta.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2beta.types.UserInfo): + User information. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. + page_view_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageViewId`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + """ + + event_type = proto.Field( + proto.STRING, + number=1, + ) + visitor_id = proto.Field( + proto.STRING, + number=2, + ) + session_id = proto.Field( + proto.STRING, + number=21, + ) + event_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + experiment_ids = proto.RepeatedField( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + product_details = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ProductDetail', + ) + completion_detail = proto.Field( + proto.MESSAGE, + number=22, + message='CompletionDetail', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=common.CustomAttribute, + ) + cart_id = proto.Field( + proto.STRING, + number=8, + ) + purchase_transaction = proto.Field( + proto.MESSAGE, + number=9, + message='PurchaseTransaction', + ) + search_query = proto.Field( + proto.STRING, + number=10, + ) + filter = proto.Field( + proto.STRING, + number=16, + ) + order_by = proto.Field( + proto.STRING, + number=17, + ) + offset = proto.Field( + proto.INT32, + number=18, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=11, + ) + user_info = proto.Field( + proto.MESSAGE, + number=12, + message=common.UserInfo, + ) + uri = proto.Field( + proto.STRING, + number=13, + ) + referrer_uri = proto.Field( + proto.STRING, + number=14, + ) + page_view_id = proto.Field( + proto.STRING, + number=15, + ) + + +class ProductDetail(proto.Message): + r"""Detailed product information associated with a user event. + + Attributes: + product (google.cloud.retail_v2beta.types.Product): + Required. [Product][google.cloud.retail.v2beta.Product] + information. + + Required field(s): + + - [Product.id][google.cloud.retail.v2beta.Product.id] + + Optional override field(s): + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + + If any supported optional fields are provided, we will treat + them as a full override when looking up product information + from the catalog. Thus, it is important to ensure that the + overriding fields are accurate and complete. + + All other product fields are ignored and instead populated + via catalog lookup after event ingestion. + quantity (google.protobuf.wrappers_pb2.Int32Value): + Quantity of the product associated with the user event. + + For example, this field will be 2 if two products are added + to the shopping cart for ``purchase-complete`` event. + Required for ``add-to-cart`` and ``purchase-complete`` event + types. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + quantity = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +class CompletionDetail(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + completion_attribution_token (str): + Completion attribution token in + [CompleteQueryResponse.attribution_token][google.cloud.retail.v2beta.CompleteQueryResponse.attribution_token]. + selected_suggestion (str): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2beta.CompleteQueryResponse.CompletionResult.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2beta.CompleteQueryResponse.CompletionResult.suggestion] + position, starting from 0. + """ + + completion_attribution_token = proto.Field( + proto.STRING, + number=1, + ) + selected_suggestion = proto.Field( + proto.STRING, + number=2, + ) + selected_position = proto.Field( + proto.INT32, + number=3, + ) + + +class PurchaseTransaction(proto.Message): + r"""A transaction represents the entire purchase transaction. + + Attributes: + id (str): + The transaction ID with a length limit of 128 + characters. + revenue (float): + Required. Total non-zero revenue or grand + total associated with the transaction. This + value include shipping, tax, or other + adjustments to total revenue that you want to + include as part of your revenue calculations. + tax (float): + All the taxes associated with the + transaction. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [revenue][google.cloud.retail.v2beta.PurchaseTransaction.revenue] + - + [tax][google.cloud.retail.v2beta.PurchaseTransaction.tax] + - + [cost][google.cloud.retail.v2beta.PurchaseTransaction.cost] + currency_code (str): + Required. Currency code. Use three-character + ISO-4217 code. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + revenue = proto.Field( + proto.FLOAT, + number=2, + ) + tax = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + currency_code = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py new file mode 100644 index 00000000..990180c4 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import user_event as gcr_user_event + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'WriteUserEventRequest', + 'CollectUserEventRequest', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'RejoinUserEventsMetadata', + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (google.cloud.retail_v2beta.types.UserEvent): + Required. User event to write. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for 3rd party requests. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.STRING, + number=2, + ) + uri = proto.Field( + proto.STRING, + number=3, + ) + ets = proto.Field( + proto.INT64, + number=4, + ) + + +class RejoinUserEventsRequest(proto.Message): + r"""Request message for RejoinUserEvents method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event_rejoin_scope (google.cloud.retail_v2beta.types.RejoinUserEventsRequest.UserEventRejoinScope): + The type of the user event rejoin to define the scope and + range of the user events to be rejoined with the latest + product catalog. Defaults to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not + set, or set to an invalid integer value. + """ + class UserEventRejoinScope(proto.Enum): + r"""The scope of user events to be rejoined with the latest product + catalog. If the rejoining aims at reducing number of unjoined + events, set UserEventRejoinScope to UNJOINED_EVENTS. If the + rejoining aims at correcting product catalog information in joined + events, set UserEventRejoinScope to JOINED_EVENTS. If all events + needs to be rejoined, set UserEventRejoinScope to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. + """ + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 + JOINED_EVENTS = 1 + UNJOINED_EVENTS = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event_rejoin_scope = proto.Field( + proto.ENUM, + number=2, + enum=UserEventRejoinScope, + ) + + +class RejoinUserEventsResponse(proto.Message): + r"""Response message for RejoinUserEvents method. + + Attributes: + rejoined_user_events_count (int): + Number of user events that were joined with + latest product catalog. + """ + + rejoined_user_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +class RejoinUserEventsMetadata(proto.Message): + r"""Metadata for RejoinUserEvents method. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/mypy.ini b/owl-bot-staging/v2beta/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v2beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2beta/noxfile.py b/owl-bot-staging/v2beta/noxfile.py new file mode 100644 index 00000000..5abd48a4 --- /dev/null +++ b/owl-bot-staging/v2beta/noxfile.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.6", + "3.7", + "3.8", + "3.9", + "3.10", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==19.10b0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.9" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/retail_v2beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py new file mode 100644 index 00000000..09847366 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_AddCatalogAttribute_async] +from google.cloud import retail_v2beta + + +async def sample_add_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_AddCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py new file mode 100644 index 00000000..4f05ae26 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync] +from google.cloud import retail_v2beta + + +def sample_add_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py new file mode 100644 index 00000000..637bfe3a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetAttributesConfig_async] +from google.cloud import retail_v2beta + + +async def sample_get_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetAttributesConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py new file mode 100644 index 00000000..c347bee2 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetAttributesConfig_sync] +from google.cloud import retail_v2beta + + +def sample_get_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetAttributesConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py new file mode 100644 index 00000000..2133e940 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetCompletionConfig_async] +from google.cloud import retail_v2beta + + +async def sample_get_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetCompletionConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py new file mode 100644 index 00000000..bb9bf00d --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetCompletionConfig_sync] +from google.cloud import retail_v2beta + + +def sample_get_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetCompletionConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py new file mode 100644 index 00000000..e598ec09 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetDefaultBranch_async] +from google.cloud import retail_v2beta + + +async def sample_get_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py new file mode 100644 index 00000000..6adcb072 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetDefaultBranch_sync] +from google.cloud import retail_v2beta + + +def sample_get_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py new file mode 100644 index 00000000..b4e3df0e --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_ListCatalogs_async] +from google.cloud import retail_v2beta + + +async def sample_list_catalogs(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py new file mode 100644 index 00000000..d938f3ae --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_ListCatalogs_sync] +from google.cloud import retail_v2beta + + +def sample_list_catalogs(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py new file mode 100644 index 00000000..032fb3c6 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async] +from google.cloud import retail_v2beta + + +async def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = await client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py new file mode 100644 index 00000000..f1ecc22b --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync] +from google.cloud import retail_v2beta + + +def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py new file mode 100644 index 00000000..8a87262f --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReplaceCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async] +from google.cloud import retail_v2beta + + +async def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py new file mode 100644 index 00000000..24b38d05 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReplaceCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync] +from google.cloud import retail_v2beta + + +def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py new file mode 100644 index 00000000..6eec0779 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_SetDefaultBranch_async] +from google.cloud import retail_v2beta + + +async def sample_set_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + +# [END retail_v2beta_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py new file mode 100644 index 00000000..a3deb8fd --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_SetDefaultBranch_sync] +from google.cloud import retail_v2beta + + +def sample_set_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + +# [END retail_v2beta_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py new file mode 100644 index 00000000..b4a235ec --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async] +from google.cloud import retail_v2beta + + +async def sample_update_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + attributes_config = retail_v2beta.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2beta.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = await client.update_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py new file mode 100644 index 00000000..8f82ee5d --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync] +from google.cloud import retail_v2beta + + +def sample_update_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + attributes_config = retail_v2beta.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2beta.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = client.update_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py new file mode 100644 index 00000000..772504ff --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateCatalog_async] +from google.cloud import retail_v2beta + + +async def sample_update_catalog(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2beta.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2beta.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py new file mode 100644 index 00000000..ed59d356 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateCatalog_sync] +from google.cloud import retail_v2beta + + +def sample_update_catalog(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2beta.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2beta.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py new file mode 100644 index 00000000..377166a7 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async] +from google.cloud import retail_v2beta + + +async def sample_update_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + completion_config = retail_v2beta.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2beta.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = await client.update_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py new file mode 100644 index 00000000..f641f121 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync] +from google.cloud import retail_v2beta + + +def sample_update_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + completion_config = retail_v2beta.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2beta.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = client.update_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py new file mode 100644 index 00000000..96fdc6a6 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CompletionService_CompleteQuery_async] +from google.cloud import retail_v2beta + + +async def sample_complete_query(): + # Create a client + client = retail_v2beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py new file mode 100644 index 00000000..afb0ba7d --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CompletionService_CompleteQuery_sync] +from google.cloud import retail_v2beta + + +def sample_complete_query(): + # Create a client + client = retail_v2beta.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py new file mode 100644 index 00000000..912753e9 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CompletionService_ImportCompletionData_async] +from google.cloud import retail_v2beta + + +async def sample_import_completion_data(): + # Create a client + client = retail_v2beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2beta.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py new file mode 100644 index 00000000..2cbd277d --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CompletionService_ImportCompletionData_sync] +from google.cloud import retail_v2beta + + +def sample_import_completion_data(): + # Create a client + client = retail_v2beta.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2beta.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py new file mode 100644 index 00000000..51e0cb4f --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_CreateControl_async] +from google.cloud import retail_v2beta + + +async def sample_create_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = await client.create_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_CreateControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py new file mode 100644 index 00000000..8d16b152 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_CreateControl_sync] +from google.cloud import retail_v2beta + + +def sample_create_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = client.create_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_CreateControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py new file mode 100644 index 00000000..cb18f6ba --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_DeleteControl_async] +from google.cloud import retail_v2beta + + +async def sample_delete_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteControlRequest( + name="name_value", + ) + + # Make the request + await client.delete_control(request=request) + + +# [END retail_v2beta_generated_ControlService_DeleteControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py new file mode 100644 index 00000000..8a0d4f56 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_DeleteControl_sync] +from google.cloud import retail_v2beta + + +def sample_delete_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteControlRequest( + name="name_value", + ) + + # Make the request + client.delete_control(request=request) + + +# [END retail_v2beta_generated_ControlService_DeleteControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py new file mode 100644 index 00000000..f9eeb9fd --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_GetControl_async] +from google.cloud import retail_v2beta + + +async def sample_get_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetControlRequest( + name="name_value", + ) + + # Make the request + response = await client.get_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_GetControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py new file mode 100644 index 00000000..ee0de08a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_GetControl_sync] +from google.cloud import retail_v2beta + + +def sample_get_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetControlRequest( + name="name_value", + ) + + # Make the request + response = client.get_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_GetControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py new file mode 100644 index 00000000..9a645706 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListControls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_ListControls_async] +from google.cloud import retail_v2beta + + +async def sample_list_controls(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_ControlService_ListControls_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py new file mode 100644 index 00000000..97c8ba62 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListControls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_ListControls_sync] +from google.cloud import retail_v2beta + + +def sample_list_controls(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_ControlService_ListControls_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py new file mode 100644 index 00000000..9a42018c --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_UpdateControl_async] +from google.cloud import retail_v2beta + + +async def sample_update_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateControlRequest( + control=control, + ) + + # Make the request + response = await client.update_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_UpdateControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py new file mode 100644 index 00000000..2a306202 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_UpdateControl_sync] +from google.cloud import retail_v2beta + + +def sample_update_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateControlRequest( + control=control, + ) + + # Make the request + response = client.update_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_UpdateControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py new file mode 100644 index 00000000..fd37548f --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_PredictionService_Predict_async] +from google.cloud import retail_v2beta + + +async def sample_predict(): + # Create a client + client = retail_v2beta.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py new file mode 100644 index 00000000..6975056e --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_PredictionService_Predict_sync] +from google.cloud import retail_v2beta + + +def sample_predict(): + # Create a client + client = retail_v2beta.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py new file mode 100644 index 00000000..92a7a7e1 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async] +from google.cloud import retail_v2beta + + +async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py new file mode 100644 index 00000000..d828edde --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync] +from google.cloud import retail_v2beta + + +def sample_add_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py new file mode 100644 index 00000000..ebcf5c80 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_AddLocalInventories_async] +from google.cloud import retail_v2beta + + +async def sample_add_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py new file mode 100644 index 00000000..9d3d9ab0 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_AddLocalInventories_sync] +from google.cloud import retail_v2beta + + +def sample_add_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py new file mode 100644 index 00000000..2bba20c0 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_CreateProduct_async] +from google.cloud import retail_v2beta + + +async def sample_create_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py new file mode 100644 index 00000000..32bd03e2 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_CreateProduct_sync] +from google.cloud import retail_v2beta + + +def sample_create_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py new file mode 100644 index 00000000..8f9591fa --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_DeleteProduct_async] +from google.cloud import retail_v2beta + + +async def sample_delete_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + +# [END retail_v2beta_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py new file mode 100644 index 00000000..56630734 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_DeleteProduct_sync] +from google.cloud import retail_v2beta + + +def sample_delete_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + +# [END retail_v2beta_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py new file mode 100644 index 00000000..f8dcfc01 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_GetProduct_async] +from google.cloud import retail_v2beta + + +async def sample_get_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py new file mode 100644 index 00000000..ab5cd918 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_GetProduct_sync] +from google.cloud import retail_v2beta + + +def sample_get_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py new file mode 100644 index 00000000..aa4256cc --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_ImportProducts_async] +from google.cloud import retail_v2beta + + +async def sample_import_products(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2beta.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py new file mode 100644 index 00000000..b4bc8314 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_ImportProducts_sync] +from google.cloud import retail_v2beta + + +def sample_import_products(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2beta.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py new file mode 100644 index 00000000..e259ecd6 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_ListProducts_async] +from google.cloud import retail_v2beta + + +async def sample_list_products(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py new file mode 100644 index 00000000..5cb40315 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_ListProducts_sync] +from google.cloud import retail_v2beta + + +def sample_list_products(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py new file mode 100644 index 00000000..1b18eb50 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async] +from google.cloud import retail_v2beta + + +async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py new file mode 100644 index 00000000..f430e360 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync] +from google.cloud import retail_v2beta + + +def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py new file mode 100644 index 00000000..55fba819 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_RemoveLocalInventories_async] +from google.cloud import retail_v2beta + + +async def sample_remove_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py new file mode 100644 index 00000000..31d1e58e --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_RemoveLocalInventories_sync] +from google.cloud import retail_v2beta + + +def sample_remove_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py new file mode 100644 index 00000000..9b467025 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_SetInventory_async] +from google.cloud import retail_v2beta + + +async def sample_set_inventory(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2beta.Product() + inventory.title = "title_value" + + request = retail_v2beta.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py new file mode 100644 index 00000000..d1061827 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_SetInventory_sync] +from google.cloud import retail_v2beta + + +def sample_set_inventory(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2beta.Product() + inventory.title = "title_value" + + request = retail_v2beta.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py new file mode 100644 index 00000000..8d9590cd --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_UpdateProduct_async] +from google.cloud import retail_v2beta + + +async def sample_update_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py new file mode 100644 index 00000000..fc614e58 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_UpdateProduct_sync] +from google.cloud import retail_v2beta + + +def sample_update_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py new file mode 100644 index 00000000..967c9102 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_SearchService_Search_async] +from google.cloud import retail_v2beta + + +async def sample_search(): + # Create a client + client = retail_v2beta.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py new file mode 100644 index 00000000..1e6a5045 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_SearchService_Search_sync] +from google.cloud import retail_v2beta + + +def sample_search(): + # Create a client + client = retail_v2beta.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py new file mode 100644 index 00000000..d6554386 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_AddControl_async] +from google.cloud import retail_v2beta + + +async def sample_add_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.add_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_AddControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py new file mode 100644 index 00000000..e61e4e2a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_AddControl_sync] +from google.cloud import retail_v2beta + + +def sample_add_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.add_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_AddControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py new file mode 100644 index 00000000..b09fadf2 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_CreateServingConfig_async] +from google.cloud import retail_v2beta + + +async def sample_create_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = await client.create_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_CreateServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py new file mode 100644 index 00000000..5d4c0993 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync] +from google.cloud import retail_v2beta + + +def sample_create_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = client.create_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py new file mode 100644 index 00000000..c0b03659 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async] +from google.cloud import retail_v2beta + + +async def sample_delete_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_serving_config(request=request) + + +# [END retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py new file mode 100644 index 00000000..1db19c0a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync] +from google.cloud import retail_v2beta + + +def sample_delete_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_serving_config(request=request) + + +# [END retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py new file mode 100644 index 00000000..64f6aeef --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_GetServingConfig_async] +from google.cloud import retail_v2beta + + +async def sample_get_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_GetServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py new file mode 100644 index 00000000..1cfab934 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_GetServingConfig_sync] +from google.cloud import retail_v2beta + + +def sample_get_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_GetServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py new file mode 100644 index 00000000..7ad0a3aa --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServingConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_ListServingConfigs_async] +from google.cloud import retail_v2beta + + +async def sample_list_serving_configs(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_ServingConfigService_ListServingConfigs_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py new file mode 100644 index 00000000..6a3e7e2a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServingConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync] +from google.cloud import retail_v2beta + + +def sample_list_serving_configs(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py new file mode 100644 index 00000000..c9994a00 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_RemoveControl_async] +from google.cloud import retail_v2beta + + +async def sample_remove_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.remove_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_RemoveControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py new file mode 100644 index 00000000..db6dfa93 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_RemoveControl_sync] +from google.cloud import retail_v2beta + + +def sample_remove_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.remove_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_RemoveControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py new file mode 100644 index 00000000..2a6bd3a0 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async] +from google.cloud import retail_v2beta + + +async def sample_update_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = await client.update_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py new file mode 100644 index 00000000..f6441e46 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync] +from google.cloud import retail_v2beta + + +def sample_update_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = client.update_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 00000000..ce80fabf --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_CollectUserEvent_async] +from google.cloud import retail_v2beta + + +async def sample_collect_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 00000000..ff7df192 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_CollectUserEvent_sync] +from google.cloud import retail_v2beta + + +def sample_collect_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py new file mode 100644 index 00000000..259c3424 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_ImportUserEvents_async] +from google.cloud import retail_v2beta + + +async def sample_import_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2beta.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 00000000..89e0ec02 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_ImportUserEvents_sync] +from google.cloud import retail_v2beta + + +def sample_import_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2beta.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py new file mode 100644 index 00000000..6f97cab1 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_PurgeUserEvents_async] +from google.cloud import retail_v2beta + + +async def sample_purge_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py new file mode 100644 index 00000000..212d2693 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_PurgeUserEvents_sync] +from google.cloud import retail_v2beta + + +def sample_purge_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py new file mode 100644 index 00000000..8a95e668 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_RejoinUserEvents_async] +from google.cloud import retail_v2beta + + +async def sample_rejoin_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py new file mode 100644 index 00000000..ebd635b8 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_RejoinUserEvents_sync] +from google.cloud import retail_v2beta + + +def sample_rejoin_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py new file mode 100644 index 00000000..71317cac --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_WriteUserEvent_async] +from google.cloud import retail_v2beta + + +async def sample_write_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 00000000..e93e4df4 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_WriteUserEvent_sync] +from google.cloud import retail_v2beta + + +def sample_write_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json b/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json new file mode 100644 index 00000000..591f20ca --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json @@ -0,0 +1,6913 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.retail.v2beta", + "version": "v2beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-retail" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.add_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "AddCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "add_catalog_attribute" + }, + "description": "Sample for AddCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_AddCatalogAttribute_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.add_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "AddCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "add_catalog_attribute" + }, + "description": "Sample for AddCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetAttributesConfigRequest" + }, + { + "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.retail_v2beta.types.AttributesConfig", + "shortName": "get_attributes_config" + }, + "description": "Sample for GetAttributesConfig", + "file": "retail_v2beta_generated_catalog_service_get_attributes_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetAttributesConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_attributes_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetAttributesConfigRequest" + }, + { + "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.retail_v2beta.types.AttributesConfig", + "shortName": "get_attributes_config" + }, + "description": "Sample for GetAttributesConfig", + "file": "retail_v2beta_generated_catalog_service_get_attributes_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetAttributesConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_attributes_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_completion_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetCompletionConfigRequest" + }, + { + "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.retail_v2beta.types.CompletionConfig", + "shortName": "get_completion_config" + }, + "description": "Sample for GetCompletionConfig", + "file": "retail_v2beta_generated_catalog_service_get_completion_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetCompletionConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_completion_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_completion_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetCompletionConfigRequest" + }, + { + "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.retail_v2beta.types.CompletionConfig", + "shortName": "get_completion_config" + }, + "description": "Sample for GetCompletionConfig", + "file": "retail_v2beta_generated_catalog_service_get_completion_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetCompletionConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_completion_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2beta_generated_catalog_service_get_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetDefaultBranch_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2beta_generated_catalog_service_get_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetDefaultBranch_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListCatalogsRequest" + }, + { + "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.retail_v2beta.services.catalog_service.pagers.ListCatalogsAsyncPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2beta_generated_catalog_service_list_catalogs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_ListCatalogs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_list_catalogs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListCatalogsRequest" + }, + { + "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.retail_v2beta.services.catalog_service.pagers.ListCatalogsPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2beta_generated_catalog_service_list_catalogs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_ListCatalogs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_list_catalogs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.remove_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "RemoveCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "remove_catalog_attribute" + }, + "description": "Sample for RemoveCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.remove_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "RemoveCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "remove_catalog_attribute" + }, + "description": "Sample for RemoveCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.replace_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ReplaceCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "replace_catalog_attribute" + }, + "description": "Sample for ReplaceCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.replace_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ReplaceCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "replace_catalog_attribute" + }, + "description": "Sample for ReplaceCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2beta_generated_catalog_service_set_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_SetDefaultBranch_async", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_set_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2beta_generated_catalog_service_set_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_SetDefaultBranch_sync", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_set_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest" + }, + { + "name": "attributes_config", + "type": "google.cloud.retail_v2beta.types.AttributesConfig" + }, + { + "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.retail_v2beta.types.AttributesConfig", + "shortName": "update_attributes_config" + }, + "description": "Sample for UpdateAttributesConfig", + "file": "retail_v2beta_generated_catalog_service_update_attributes_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_attributes_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest" + }, + { + "name": "attributes_config", + "type": "google.cloud.retail_v2beta.types.AttributesConfig" + }, + { + "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.retail_v2beta.types.AttributesConfig", + "shortName": "update_attributes_config" + }, + "description": "Sample for UpdateAttributesConfig", + "file": "retail_v2beta_generated_catalog_service_update_attributes_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_attributes_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2beta.types.Catalog" + }, + { + "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.retail_v2beta.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2beta_generated_catalog_service_update_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateCatalog_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2beta.types.Catalog" + }, + { + "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.retail_v2beta.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2beta_generated_catalog_service_update_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateCatalog_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_completion_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest" + }, + { + "name": "completion_config", + "type": "google.cloud.retail_v2beta.types.CompletionConfig" + }, + { + "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.retail_v2beta.types.CompletionConfig", + "shortName": "update_completion_config" + }, + "description": "Sample for UpdateCompletionConfig", + "file": "retail_v2beta_generated_catalog_service_update_completion_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_completion_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_completion_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest" + }, + { + "name": "completion_config", + "type": "google.cloud.retail_v2beta.types.CompletionConfig" + }, + { + "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.retail_v2beta.types.CompletionConfig", + "shortName": "update_completion_config" + }, + "description": "Sample for UpdateCompletionConfig", + "file": "retail_v2beta_generated_catalog_service_update_completion_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_completion_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2beta.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2beta_generated_completion_service_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CompletionService_CompleteQuery_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_completion_service_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CompletionServiceClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2beta.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2beta_generated_completion_service_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CompletionService_CompleteQuery_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_completion_service_complete_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2beta.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2beta_generated_completion_service_import_completion_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CompletionService_ImportCompletionData_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_completion_service_import_completion_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CompletionServiceClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2beta.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2beta_generated_completion_service_import_completion_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CompletionService_ImportCompletionData_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_completion_service_import_completion_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.create_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.CreateControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "CreateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateControlRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "control", + "type": "google.cloud.retail_v2beta.types.Control" + }, + { + "name": "control_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.retail_v2beta.types.Control", + "shortName": "create_control" + }, + "description": "Sample for CreateControl", + "file": "retail_v2beta_generated_control_service_create_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_CreateControl_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_create_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.create_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.CreateControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "CreateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateControlRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "control", + "type": "google.cloud.retail_v2beta.types.Control" + }, + { + "name": "control_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.retail_v2beta.types.Control", + "shortName": "create_control" + }, + "description": "Sample for CreateControl", + "file": "retail_v2beta_generated_control_service_create_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_CreateControl_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_create_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.delete_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.DeleteControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "DeleteControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteControlRequest" + }, + { + "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_control" + }, + "description": "Sample for DeleteControl", + "file": "retail_v2beta_generated_control_service_delete_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_DeleteControl_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_delete_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.delete_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.DeleteControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "DeleteControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteControlRequest" + }, + { + "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_control" + }, + "description": "Sample for DeleteControl", + "file": "retail_v2beta_generated_control_service_delete_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_DeleteControl_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_delete_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.get_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.GetControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "GetControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetControlRequest" + }, + { + "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.retail_v2beta.types.Control", + "shortName": "get_control" + }, + "description": "Sample for GetControl", + "file": "retail_v2beta_generated_control_service_get_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_GetControl_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_get_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.get_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.GetControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "GetControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetControlRequest" + }, + { + "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.retail_v2beta.types.Control", + "shortName": "get_control" + }, + "description": "Sample for GetControl", + "file": "retail_v2beta_generated_control_service_get_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_GetControl_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_get_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.list_controls", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.ListControls", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListControlsRequest" + }, + { + "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.retail_v2beta.services.control_service.pagers.ListControlsAsyncPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "retail_v2beta_generated_control_service_list_controls_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_ListControls_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_list_controls_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.list_controls", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.ListControls", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListControlsRequest" + }, + { + "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.retail_v2beta.services.control_service.pagers.ListControlsPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "retail_v2beta_generated_control_service_list_controls_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_ListControls_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_list_controls_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.update_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.UpdateControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "UpdateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateControlRequest" + }, + { + "name": "control", + "type": "google.cloud.retail_v2beta.types.Control" + }, + { + "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.retail_v2beta.types.Control", + "shortName": "update_control" + }, + "description": "Sample for UpdateControl", + "file": "retail_v2beta_generated_control_service_update_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_UpdateControl_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_update_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.update_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.UpdateControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "UpdateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateControlRequest" + }, + { + "name": "control", + "type": "google.cloud.retail_v2beta.types.Control" + }, + { + "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.retail_v2beta.types.Control", + "shortName": "update_control" + }, + "description": "Sample for UpdateControl", + "file": "retail_v2beta_generated_control_service_update_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_UpdateControl_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_update_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.PredictionServiceAsyncClient", + "shortName": "PredictionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.PredictionServiceAsyncClient.predict", + "method": { + "fullName": "google.cloud.retail.v2beta.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2beta.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2beta_generated_prediction_service_predict_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_PredictionService_Predict_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_prediction_service_predict_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.PredictionServiceClient", + "shortName": "PredictionServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.PredictionServiceClient.predict", + "method": { + "fullName": "google.cloud.retail.v2beta.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2beta.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2beta_generated_prediction_service_predict_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_PredictionService_Predict_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_prediction_service_predict_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2beta_generated_product_service_add_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_add_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2beta_generated_product_service_add_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_add_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2beta_generated_product_service_add_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_AddLocalInventories_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_add_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2beta_generated_product_service_add_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_AddLocalInventories_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_add_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "name": "product_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.retail_v2beta.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2beta_generated_product_service_create_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_CreateProduct_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_create_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "name": "product_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.retail_v2beta.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2beta_generated_product_service_create_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_CreateProduct_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_create_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2beta_generated_product_service_delete_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_DeleteProduct_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_delete_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2beta_generated_product_service_delete_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_DeleteProduct_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_delete_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetProductRequest" + }, + { + "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.retail_v2beta.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2beta_generated_product_service_get_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_GetProduct_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_get_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetProductRequest" + }, + { + "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.retail_v2beta.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2beta_generated_product_service_get_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_GetProduct_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_get_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2beta_generated_product_service_import_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_ImportProducts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_import_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2beta_generated_product_service_import_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_ImportProducts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_import_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListProductsRequest" + }, + { + "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.retail_v2beta.services.product_service.pagers.ListProductsAsyncPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2beta_generated_product_service_list_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_ListProducts_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_list_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListProductsRequest" + }, + { + "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.retail_v2beta.services.product_service.pagers.ListProductsPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2beta_generated_product_service_list_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_ListProducts_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_list_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2beta_generated_product_service_remove_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_remove_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2beta_generated_product_service_remove_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_RemoveLocalInventories_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_remove_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2beta_generated_product_service_remove_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_RemoveLocalInventories_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_remove_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2beta_generated_product_service_set_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_SetInventory_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_set_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2beta_generated_product_service_set_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_SetInventory_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_set_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "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.retail_v2beta.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2beta_generated_product_service_update_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_UpdateProduct_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_update_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "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.retail_v2beta.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2beta_generated_product_service_update_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_UpdateProduct_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_update_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.SearchServiceAsyncClient.search", + "method": { + "fullName": "google.cloud.retail.v2beta.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2beta.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2beta_generated_search_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_SearchService_Search_async", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_search_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.SearchServiceClient", + "shortName": "SearchServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.SearchServiceClient.search", + "method": { + "fullName": "google.cloud.retail.v2beta.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2beta.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.services.search_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2beta_generated_search_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_SearchService_Search_sync", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_search_service_search_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.add_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.AddControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "AddControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "add_control" + }, + "description": "Sample for AddControl", + "file": "retail_v2beta_generated_serving_config_service_add_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_AddControl_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_add_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.add_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.AddControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "AddControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "add_control" + }, + "description": "Sample for AddControl", + "file": "retail_v2beta_generated_serving_config_service_add_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_AddControl_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_add_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.create_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.CreateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "CreateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateServingConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2beta.types.ServingConfig" + }, + { + "name": "serving_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "create_serving_config" + }, + "description": "Sample for CreateServingConfig", + "file": "retail_v2beta_generated_serving_config_service_create_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_CreateServingConfig_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_create_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.create_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.CreateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "CreateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateServingConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2beta.types.ServingConfig" + }, + { + "name": "serving_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "create_serving_config" + }, + "description": "Sample for CreateServingConfig", + "file": "retail_v2beta_generated_serving_config_service_create_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_create_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.delete_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.DeleteServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "DeleteServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteServingConfigRequest" + }, + { + "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_serving_config" + }, + "description": "Sample for DeleteServingConfig", + "file": "retail_v2beta_generated_serving_config_service_delete_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_delete_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.delete_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.DeleteServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "DeleteServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteServingConfigRequest" + }, + { + "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_serving_config" + }, + "description": "Sample for DeleteServingConfig", + "file": "retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.get_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.GetServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "GetServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetServingConfigRequest" + }, + { + "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.retail_v2beta.types.ServingConfig", + "shortName": "get_serving_config" + }, + "description": "Sample for GetServingConfig", + "file": "retail_v2beta_generated_serving_config_service_get_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_GetServingConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_get_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.get_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.GetServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "GetServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetServingConfigRequest" + }, + { + "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.retail_v2beta.types.ServingConfig", + "shortName": "get_serving_config" + }, + "description": "Sample for GetServingConfig", + "file": "retail_v2beta_generated_serving_config_service_get_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_GetServingConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_get_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.list_serving_configs", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.ListServingConfigs", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "ListServingConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListServingConfigsRequest" + }, + { + "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.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager", + "shortName": "list_serving_configs" + }, + "description": "Sample for ListServingConfigs", + "file": "retail_v2beta_generated_serving_config_service_list_serving_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_ListServingConfigs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_list_serving_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.list_serving_configs", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.ListServingConfigs", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "ListServingConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListServingConfigsRequest" + }, + { + "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.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsPager", + "shortName": "list_serving_configs" + }, + "description": "Sample for ListServingConfigs", + "file": "retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.remove_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.RemoveControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "RemoveControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "remove_control" + }, + "description": "Sample for RemoveControl", + "file": "retail_v2beta_generated_serving_config_service_remove_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_RemoveControl_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_remove_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.remove_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.RemoveControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "RemoveControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "remove_control" + }, + "description": "Sample for RemoveControl", + "file": "retail_v2beta_generated_serving_config_service_remove_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_RemoveControl_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_remove_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.update_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.UpdateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "UpdateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateServingConfigRequest" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2beta.types.ServingConfig" + }, + { + "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.retail_v2beta.types.ServingConfig", + "shortName": "update_serving_config" + }, + "description": "Sample for UpdateServingConfig", + "file": "retail_v2beta_generated_serving_config_service_update_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_update_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.update_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.UpdateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "UpdateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateServingConfigRequest" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2beta.types.ServingConfig" + }, + { + "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.retail_v2beta.types.ServingConfig", + "shortName": "update_serving_config" + }, + "description": "Sample for UpdateServingConfig", + "file": "retail_v2beta_generated_serving_config_service_update_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_update_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2beta_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_CollectUserEvent_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2beta_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_CollectUserEvent_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2beta_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_ImportUserEvents_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2beta_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_ImportUserEvents_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2beta_generated_user_event_service_purge_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_PurgeUserEvents_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_purge_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2beta_generated_user_event_service_purge_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_PurgeUserEvents_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_purge_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2beta_generated_user_event_service_rejoin_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_RejoinUserEvents_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_rejoin_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_RejoinUserEvents_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2beta_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_WriteUserEvent_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2beta_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_WriteUserEvent_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py b/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py new file mode 100644 index 00000000..dbd16de7 --- /dev/null +++ b/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py @@ -0,0 +1,218 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class retailCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_catalog_attribute': ('attributes_config', 'catalog_attribute', ), + 'add_control': ('serving_config', 'control_id', ), + 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), + 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), + 'create_control': ('parent', 'control', 'control_id', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'create_serving_config': ('parent', 'serving_config', 'serving_config_id', ), + 'delete_control': ('name', ), + 'delete_product': ('name', ), + 'delete_serving_config': ('name', ), + 'get_attributes_config': ('name', ), + 'get_completion_config': ('name', ), + 'get_control': ('name', ), + 'get_default_branch': ('catalog', ), + 'get_product': ('name', ), + 'get_serving_config': ('name', ), + 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), + 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), + 'import_user_events': ('parent', 'input_config', 'errors_config', ), + 'list_catalogs': ('parent', 'page_size', 'page_token', ), + 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', ), + 'list_serving_configs': ('parent', 'page_size', 'page_token', ), + 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), + 'purge_user_events': ('parent', 'filter', 'force', ), + 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), + 'remove_catalog_attribute': ('attributes_config', 'key', ), + 'remove_control': ('serving_config', 'control_id', ), + 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), + 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), + 'replace_catalog_attribute': ('attributes_config', 'catalog_attribute', 'update_mask', ), + 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), + 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), + 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), + 'update_attributes_config': ('attributes_config', 'update_mask', ), + 'update_catalog': ('catalog', 'update_mask', ), + 'update_completion_config': ('completion_config', 'update_mask', ), + 'update_control': ('control', 'update_mask', ), + 'update_product': ('product', 'update_mask', 'allow_missing', ), + 'update_serving_config': ('serving_config', 'update_mask', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=retailCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the retail client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2beta/setup.py b/owl-bot-staging/v2beta/setup.py new file mode 100644 index 00000000..1103510b --- /dev/null +++ b/owl-bot-staging/v2beta/setup.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-retail', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-retail", + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 2.8.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'googleapis-common-protos >= 1.55.0, <2.0.0dev', + 'proto-plus >= 1.19.7', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2beta/tests/__init__.py b/owl-bot-staging/v2beta/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/tests/unit/__init__.py b/owl-bot-staging/v2beta/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py b/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py new file mode 100644 index 00000000..a933c6e0 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py @@ -0,0 +1,3844 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.catalog_service import CatalogServiceAsyncClient +from google.cloud.retail_v2beta.services.catalog_service import CatalogServiceClient +from google.cloud.retail_v2beta.services.catalog_service import pagers +from google.cloud.retail_v2beta.services.catalog_service import transports +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CatalogServiceClient._get_default_mtls_endpoint(None) is None + assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CatalogServiceGrpcTransport, "grpc"), + (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_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", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_catalog_service_client_get_transport_class(): + transport = CatalogServiceClient.get_transport_class() + available_transports = [ + transports.CatalogServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CatalogServiceClient.get_transport_class("grpc") + assert transport == transports.CatalogServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CatalogServiceClient, CatalogServiceAsyncClient +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_catalog_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ListCatalogsRequest, + dict, +]) +def test_list_catalogs(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_catalogs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalogs), + '__call__') as call: + client.list_catalogs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + +@pytest.mark.asyncio +async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_catalogs_async_from_dict(): + await test_list_catalogs_async(request_type=dict) + + +def test_list_catalogs_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = catalog_service.ListCatalogsResponse() + client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_catalogs( + 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_catalogs_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_catalogs_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_catalogs( + 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_catalogs_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + + +def test_list_catalogs_pager(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_catalogs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, catalog.Catalog) + for i in results) +def test_list_catalogs_pages(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = list(client.list_catalogs(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_catalogs_async_pager(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_catalogs(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, catalog.Catalog) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_catalogs_async_pages(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCatalogRequest, + dict, +]) +def test_update_catalog(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + ) + response = client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_catalog_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalog), + '__call__') as call: + client.update_catalog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + +@pytest.mark.asyncio +async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_catalog_async_from_dict(): + await test_update_catalog_async(request_type=dict) + + +def test_update_catalog_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = gcr_catalog.Catalog() + client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_catalog_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +def test_update_catalog_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_catalog_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.SetDefaultBranchRequest, + dict, +]) +def test_set_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_set_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + client.set_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_set_default_branch_async_from_dict(): + await test_set_default_branch_async(request_type=dict) + + +def test_set_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = None + client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_set_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_set_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetDefaultBranchRequest, + dict, +]) +def test_get_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + ) + response = client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +def test_get_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_default_branch), + '__call__') as call: + client.get_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + )) + response = await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +@pytest.mark.asyncio +async def test_get_default_branch_async_from_dict(): + await test_get_default_branch_async(request_type=dict) + + +def test_get_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = catalog_service.GetDefaultBranchResponse() + client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_get_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_get_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetCompletionConfigRequest, + dict, +]) +def test_get_completion_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + ) + response = client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +def test_get_completion_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_completion_config), + '__call__') as call: + client.get_completion_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + +@pytest.mark.asyncio +async def test_get_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCompletionConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + )) + response = await client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +@pytest.mark.asyncio +async def test_get_completion_config_async_from_dict(): + await test_get_completion_config_async(request_type=dict) + + +def test_get_completion_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCompletionConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + call.return_value = catalog.CompletionConfig() + client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_completion_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCompletionConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + await client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_completion_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_completion_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_completion_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_completion_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_completion_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_completion_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCompletionConfigRequest, + dict, +]) +def test_update_completion_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + ) + response = client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +def test_update_completion_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_completion_config), + '__call__') as call: + client.update_completion_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + +@pytest.mark.asyncio +async def test_update_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCompletionConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + )) + response = await client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +@pytest.mark.asyncio +async def test_update_completion_config_async_from_dict(): + await test_update_completion_config_async(request_type=dict) + + +def test_update_completion_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCompletionConfigRequest() + + request.completion_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + call.return_value = catalog.CompletionConfig() + client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'completion_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_completion_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCompletionConfigRequest() + + request.completion_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + await client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'completion_config.name=name_value', + ) in kw['metadata'] + + +def test_update_completion_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_completion_config( + completion_config=catalog.CompletionConfig(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].completion_config + mock_val = catalog.CompletionConfig(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_completion_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_completion_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_completion_config( + completion_config=catalog.CompletionConfig(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].completion_config + mock_val = catalog.CompletionConfig(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_completion_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetAttributesConfigRequest, + dict, +]) +def test_get_attributes_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_get_attributes_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_attributes_config), + '__call__') as call: + client.get_attributes_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + +@pytest.mark.asyncio +async def test_get_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetAttributesConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_get_attributes_config_async_from_dict(): + await test_get_attributes_config_async(request_type=dict) + + +def test_get_attributes_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetAttributesConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_attributes_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetAttributesConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_attributes_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_attributes_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_attributes_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_attributes_config( + catalog_service.GetAttributesConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_attributes_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_attributes_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_attributes_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_attributes_config( + catalog_service.GetAttributesConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateAttributesConfigRequest, + dict, +]) +def test_update_attributes_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_update_attributes_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_attributes_config), + '__call__') as call: + client.update_attributes_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + +@pytest.mark.asyncio +async def test_update_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateAttributesConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_update_attributes_config_async_from_dict(): + await test_update_attributes_config_async(request_type=dict) + + +def test_update_attributes_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateAttributesConfigRequest() + + request.attributes_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_attributes_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateAttributesConfigRequest() + + request.attributes_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config.name=name_value', + ) in kw['metadata'] + + +def test_update_attributes_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_attributes_config( + attributes_config=catalog.AttributesConfig(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].attributes_config + mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_attributes_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_attributes_config( + attributes_config=catalog.AttributesConfig(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].attributes_config + mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.AddCatalogAttributeRequest, + dict, +]) +def test_add_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_add_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + client.add_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_add_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.AddCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_add_catalog_attribute_async_from_dict(): + await test_add_catalog_attribute_async(request_type=dict) + + +def test_add_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.AddCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.AddCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + catalog_service.RemoveCatalogAttributeRequest, + dict, +]) +def test_remove_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_remove_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + client.remove_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.RemoveCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_async_from_dict(): + await test_remove_catalog_attribute_async(request_type=dict) + + +def test_remove_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.RemoveCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.RemoveCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ReplaceCatalogAttributeRequest, + dict, +]) +def test_replace_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_replace_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + client.replace_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ReplaceCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_async_from_dict(): + await test_replace_catalog_attribute_async(request_type=dict) + + +def test_replace_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ReplaceCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ReplaceCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CatalogServiceClient.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 = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CatalogServiceGrpcTransport, + ) + +def test_catalog_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_catalog_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_catalogs', + 'update_catalog', + 'set_default_branch', + 'get_default_branch', + 'get_completion_config', + 'update_completion_config', + 'get_attributes_config', + 'update_attributes_config', + 'add_catalog_attribute', + 'remove_catalog_attribute', + 'replace_catalog_attribute', + ) + 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_catalog_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.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport( + 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_catalog_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.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport() + adc.assert_called_once() + + +def test_catalog_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) + CatalogServiceClient() + 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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +def test_catalog_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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + transports.CatalogServiceRestTransport, + ], +) +def test_catalog_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.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_catalog_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_no_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_with_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_catalog_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcTransport( + 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_catalog_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcAsyncIOTransport( + 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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_attributes_config_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.attributes_config_path(project, location, catalog) + assert expected == actual + + +def test_parse_attributes_config_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CatalogServiceClient.attributes_config_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_attributes_config_path(path) + assert expected == actual + +def test_branch_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = CatalogServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "branch": "clam", + } + path = CatalogServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_branch_path(path) + assert expected == actual + +def test_catalog_path(): + project = "whelk" + location = "octopus" + catalog = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + } + path = CatalogServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_completion_config_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.completion_config_path(project, location, catalog) + assert expected == actual + + +def test_parse_completion_config_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + } + path = CatalogServiceClient.completion_config_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_completion_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CatalogServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = CatalogServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = CatalogServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CatalogServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CatalogServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CatalogServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = CatalogServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CatalogServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CatalogServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CatalogServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py new file mode 100644 index 00000000..8abb5922 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py @@ -0,0 +1,1502 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.completion_service import CompletionServiceAsyncClient +from google.cloud.retail_v2beta.services.completion_service import CompletionServiceClient +from google.cloud.retail_v2beta.services.completion_service import transports +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CompletionServiceClient._get_default_mtls_endpoint(None) is None + assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CompletionServiceGrpcTransport, "grpc"), + (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_completion_service_client_get_transport_class(): + transport = CompletionServiceClient.get_transport_class() + available_transports = [ + transports.CompletionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CompletionServiceClient.get_transport_class("grpc") + assert transport == transports.CompletionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CompletionServiceClient, CompletionServiceAsyncClient +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_completion_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CompletionServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + ) + response = client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +def test_complete_query_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + client.complete_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + +@pytest.mark.asyncio +async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + )) + response = await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +@pytest.mark.asyncio +async def test_complete_query_async_from_dict(): + await test_complete_query_async(request_type=dict) + + +def test_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) + await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportCompletionDataRequest, + dict, +]) +def test_import_completion_data(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_completion_data_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + client.import_completion_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + +@pytest.mark.asyncio +async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_completion_data_async_from_dict(): + await test_import_completion_data_async(request_type=dict) + + +def test_import_completion_data_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # 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_completion_data_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CompletionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CompletionServiceGrpcTransport, + ) + +def test_completion_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_completion_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'complete_query', + 'import_completion_data', + ) + 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_completion_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_completion_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport() + adc.assert_called_once() + + +def test_completion_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CompletionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, + ], +) +def test_completion_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionServiceGrpcTransport, grpc_helpers), + (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_completion_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_no_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_with_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_completion_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_completion_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_completion_service_grpc_lro_client(): + client = CompletionServiceClient( + 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_completion_service_grpc_lro_async_client(): + client = CompletionServiceAsyncClient( + 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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CompletionServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CompletionServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CompletionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CompletionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = CompletionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CompletionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CompletionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CompletionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = CompletionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CompletionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CompletionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CompletionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CompletionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py new file mode 100644 index 00000000..33a56677 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py @@ -0,0 +1,2605 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.control_service import ControlServiceAsyncClient +from google.cloud.retail_v2beta.services.control_service import ControlServiceClient +from google.cloud.retail_v2beta.services.control_service import pagers +from google.cloud.retail_v2beta.services.control_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.cloud.retail_v2beta.types import search_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ControlServiceClient._get_default_mtls_endpoint(None) is None + assert ControlServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ControlServiceClient, "grpc"), + (ControlServiceAsyncClient, "grpc_asyncio"), +]) +def test_control_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ControlServiceGrpcTransport, "grpc"), + (transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_control_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", [ + (ControlServiceClient, "grpc"), + (ControlServiceAsyncClient, "grpc_asyncio"), +]) +def test_control_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_control_service_client_get_transport_class(): + transport = ControlServiceClient.get_transport_class() + available_transports = [ + transports.ControlServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ControlServiceClient.get_transport_class("grpc") + assert transport == transports.ControlServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +def test_control_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(ControlServiceClient, '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(ControlServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "true"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "false"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_control_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ControlServiceClient, ControlServiceAsyncClient +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +def test_control_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_control_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_control_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_control_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.control_service.transports.ControlServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ControlServiceClient( + 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", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_control_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.CreateControlRequest, + dict, +]) +def test_create_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_create_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.create_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + +@pytest.mark.asyncio +async def test_create_control_async(transport: str = 'grpc_asyncio', request_type=control_service.CreateControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_create_control_async_from_dict(): + await test_create_control_async(request_type=dict) + + +def test_create_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.CreateControlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + call.return_value = gcr_control.Control() + client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.CreateControlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + await client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_control( + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) + assert arg == mock_val + arg = args[0].control_id + mock_val = 'control_id_value' + assert arg == mock_val + + +def test_create_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.CreateControlRequest(), + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_id_value', + ) + +@pytest.mark.asyncio +async def test_create_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_control( + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) + assert arg == mock_val + arg = args[0].control_id + mock_val = 'control_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.CreateControlRequest(), + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.DeleteControlRequest, + dict, +]) +def test_delete_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.delete_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + +@pytest.mark.asyncio +async def test_delete_control_async(transport: str = 'grpc_asyncio', request_type=control_service.DeleteControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_control_async_from_dict(): + await test_delete_control_async(request_type=dict) + + +def test_delete_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.DeleteControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__call__') as call: + call.return_value = None + client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.DeleteControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__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_control( + 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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.DeleteControlRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__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_control( + 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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.DeleteControlRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.UpdateControlRequest, + dict, +]) +def test_update_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_update_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.update_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + +@pytest.mark.asyncio +async def test_update_control_async(transport: str = 'grpc_asyncio', request_type=control_service.UpdateControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_update_control_async_from_dict(): + await test_update_control_async(request_type=dict) + + +def test_update_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.UpdateControlRequest() + + request.control.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + call.return_value = gcr_control.Control() + client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'control.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.UpdateControlRequest() + + request.control.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + await client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'control.name=name_value', + ) in kw['metadata'] + + +def test_update_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_control( + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_control( + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.GetControlRequest, + dict, +]) +def test_get_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_get_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.get_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + +@pytest.mark.asyncio +async def test_get_control_async(transport: str = 'grpc_asyncio', request_type=control_service.GetControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_get_control_async_from_dict(): + await test_get_control_async(request_type=dict) + + +def test_get_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.GetControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + call.return_value = control.Control() + client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.GetControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) + await client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_control( + 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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.GetControlRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_control( + 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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.GetControlRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.ListControlsRequest, + dict, +]) +def test_list_controls(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_controls_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_controls), + '__call__') as call: + client.list_controls() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + +@pytest.mark.asyncio +async def test_list_controls_async(transport: str = 'grpc_asyncio', request_type=control_service.ListControlsRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_controls_async_from_dict(): + await test_list_controls_async(request_type=dict) + + +def test_list_controls_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.ListControlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + call.return_value = control_service.ListControlsResponse() + client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_controls_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.ListControlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) + await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_controls_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_controls( + 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_controls_flattened_error(): + client = ControlServiceClient( + credentials=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_controls( + control_service.ListControlsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_controls_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_controls( + 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_controls_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_controls( + control_service.ListControlsRequest(), + parent='parent_value', + ) + + +def test_list_controls_pager(transport_name: str = "grpc"): + client = ControlServiceClient( + 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_controls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_controls(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, control.Control) + for i in results) +def test_list_controls_pages(transport_name: str = "grpc"): + client = ControlServiceClient( + 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_controls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + pages = list(client.list_controls(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_controls_async_pager(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_controls(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, control.Control) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_controls_async_pages(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_controls(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ControlServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ControlServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ControlServiceClient.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 = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ControlServiceGrpcTransport, + ) + +def test_control_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ControlServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_control_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.control_service.transports.ControlServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ControlServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_control', + 'delete_control', + 'update_control', + 'get_control', + 'list_controls', + ) + 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_control_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.retail_v2beta.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ControlServiceTransport( + 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_control_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.retail_v2beta.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ControlServiceTransport() + adc.assert_called_once() + + +def test_control_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) + ControlServiceClient() + 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.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + ], +) +def test_control_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.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + transports.ControlServiceRestTransport, + ], +) +def test_control_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.ControlServiceGrpcTransport, grpc_helpers), + (transports.ControlServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_control_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_control_service_host_no_port(transport_name): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_control_service_host_with_port(transport_name): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_control_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ControlServiceGrpcTransport( + 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_control_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ControlServiceGrpcAsyncIOTransport( + 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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = ControlServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = ControlServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_control_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + control = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) + actual = ControlServiceClient.control_path(project, location, catalog, control) + assert expected == actual + + +def test_parse_control_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "control": "clam", + } + path = ControlServiceClient.control_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_control_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ControlServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ControlServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ControlServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ControlServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ControlServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ControlServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ControlServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ControlServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.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 = ControlServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ControlServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.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.ControlServiceTransport, '_prep_wrapped_messages') as prep: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ControlServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ControlServiceClient.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 = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ControlServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ControlServiceClient( + 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", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py new file mode 100644 index 00000000..37ea8b9f --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py @@ -0,0 +1,1330 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.prediction_service import PredictionServiceAsyncClient +from google.cloud.retail_v2beta.services.prediction_service import PredictionServiceClient +from google.cloud.retail_v2beta.services.prediction_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import prediction_service +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import promotion +from google.cloud.retail_v2beta.types import user_event +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PredictionServiceClient._get_default_mtls_endpoint(None) is None + assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionServiceGrpcTransport, "grpc"), + (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_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", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_prediction_service_client_get_transport_class(): + transport = PredictionServiceClient.get_transport_class() + available_transports = [ + transports.PredictionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = PredictionServiceClient.get_transport_class("grpc") + assert transport == transports.PredictionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + PredictionServiceClient, PredictionServiceAsyncClient +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_prediction_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_service.PredictRequest, + dict, +]) +def test_predict(request_type, transport: str = 'grpc'): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + response = client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_predict_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + client.predict() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + +@pytest.mark.asyncio +async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + )) + response = await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +@pytest.mark.asyncio +async def test_predict_async_from_dict(): + await test_predict_async(request_type=dict) + + +def test_predict_field_headers(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_predict_field_headers_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) + await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = PredictionServiceClient.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 = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'predict', + ) + 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport( + 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport() + adc.assert_called_once() + + +def test_prediction_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) + PredictionServiceClient() + 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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +def test_prediction_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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + transports.PredictionServiceRestTransport, + ], +) +def test_prediction_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.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_prediction_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_no_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_with_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_prediction_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcTransport( + 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_prediction_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcAsyncIOTransport( + 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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_product_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + product = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + "branch": "winkle", + "product": "nautilus", + } + path = PredictionServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PredictionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = PredictionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = PredictionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = PredictionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PredictionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = PredictionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = PredictionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = PredictionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = PredictionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PredictionServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py new file mode 100644 index 00000000..1f4c5dc7 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py @@ -0,0 +1,4136 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.product_service import ProductServiceAsyncClient +from google.cloud.retail_v2beta.services.product_service import ProductServiceClient +from google.cloud.retail_v2beta.services.product_service import pagers +from google.cloud.retail_v2beta.services.product_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.cloud.retail_v2beta.types import promotion +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProductServiceClient._get_default_mtls_endpoint(None) is None + assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProductServiceGrpcTransport, "grpc"), + (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_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", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_product_service_client_get_transport_class(): + transport = ProductServiceClient.get_transport_class() + available_transports = [ + transports.ProductServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ProductServiceClient.get_transport_class("grpc") + assert transport == transports.ProductServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_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(ProductServiceClient, '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(ProductServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ProductServiceClient, ProductServiceAsyncClient +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_product_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.CreateProductRequest, + dict, +]) +def test_create_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_create_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.create_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + +@pytest.mark.asyncio +async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_create_product_async_from_dict(): + await test_create_product_async(request_type=dict) + + +def test_create_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + + +def test_create_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + +@pytest.mark.asyncio +async def test_create_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_get_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.get_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + +@pytest.mark.asyncio +async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_get_product_async_from_dict(): + await test_get_product_async(request_type=dict) + + +def test_get_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = product.Product() + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.GetProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.GetProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.list_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + +@pytest.mark.asyncio +async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_products_async_from_dict(): + await test_list_products_async(request_type=dict) + + +def test_list_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = product_service.ListProductsResponse() + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products( + 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_products_flattened_error(): + client = ProductServiceClient( + credentials=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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products( + 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_products_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + + +def test_list_products_pager(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_products(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, product.Product) + for i in results) +def test_list_products_pages(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(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_products_async_pager(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(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, product.Product) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_products(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + product_service.UpdateProductRequest, + dict, +]) +def test_update_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_update_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.update_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + +@pytest.mark.asyncio +async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_update_product_async_from_dict(): + await test_update_product_async(request_type=dict) + + +def test_update_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +def test_update_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.DeleteProductRequest, + dict, +]) +def test_delete_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.delete_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + +@pytest.mark.asyncio +async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_product_async_from_dict(): + await test_delete_product_async(request_type=dict) + + +def test_delete_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = None + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportProductsRequest, + dict, +]) +def test_import_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.import_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + +@pytest.mark.asyncio +async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__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_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_products_async_from_dict(): + await test_import_products_async(request_type=dict) + + +def test_import_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + product_service.SetInventoryRequest, + dict, +]) +def test_set_inventory(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_inventory_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + client.set_inventory() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + +@pytest.mark.asyncio +async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_set_inventory_async_from_dict(): + await test_set_inventory_async(request_type=dict) + + +def test_set_inventory_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_inventory_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +def test_set_inventory_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_set_inventory_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_set_inventory_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_inventory_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddFulfillmentPlacesRequest, + dict, +]) +def test_add_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + client.add_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async_from_dict(): + await test_add_fulfillment_places_async(request_type=dict) + + +def test_add_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveFulfillmentPlacesRequest, + dict, +]) +def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + client.remove_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async_from_dict(): + await test_remove_fulfillment_places_async(request_type=dict) + + +def test_remove_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddLocalInventoriesRequest, + dict, +]) +def test_add_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + client.add_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_local_inventories_async_from_dict(): + await test_add_local_inventories_async(request_type=dict) + + +def test_add_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveLocalInventoriesRequest, + dict, +]) +def test_remove_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + client.remove_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_local_inventories_async_from_dict(): + await test_remove_local_inventories_async(request_type=dict) + + +def test_remove_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ProductServiceClient.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 = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProductServiceGrpcTransport, + ) + +def test_product_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_product_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.product_service.transports.ProductServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_product', + 'get_product', + 'list_products', + 'update_product', + 'delete_product', + 'import_products', + 'set_inventory', + 'add_fulfillment_places', + 'remove_fulfillment_places', + 'add_local_inventories', + 'remove_local_inventories', + ) + 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_product_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.retail_v2beta.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport( + 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_product_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.retail_v2beta.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport() + adc.assert_called_once() + + +def test_product_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) + ProductServiceClient() + 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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + ], +) +def test_product_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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + transports.ProductServiceRestTransport, + ], +) +def test_product_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.ProductServiceGrpcTransport, grpc_helpers), + (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_product_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_no_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_with_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_product_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcTransport( + 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_product_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcAsyncIOTransport( + 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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_product_service_grpc_lro_client(): + client = ProductServiceClient( + 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_product_service_grpc_lro_async_client(): + client = ProductServiceAsyncClient( + 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" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = ProductServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = ProductServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = ProductServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = ProductServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProductServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ProductServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProductServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ProductServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProductServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ProductServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ProductServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ProductServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ProductServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ProductServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ProductServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py new file mode 100644 index 00000000..55c11327 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py @@ -0,0 +1,1547 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.search_service import SearchServiceAsyncClient +from google.cloud.retail_v2beta.services.search_service import SearchServiceClient +from google.cloud.retail_v2beta.services.search_service import pagers +from google.cloud.retail_v2beta.services.search_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SearchServiceClient._get_default_mtls_endpoint(None) is None + assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SearchServiceGrpcTransport, "grpc"), + (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_search_service_client_get_transport_class(): + transport = SearchServiceClient.get_transport_class() + available_transports = [ + transports.SearchServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SearchServiceClient.get_transport_class("grpc") + assert transport == transports.SearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SearchServiceClient, SearchServiceAsyncClient +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SearchServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + search_service.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + + +def test_search_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = search_service.SearchResponse() + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_search_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('placement', ''), + )), + ) + pager = client.search(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_async_pager(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = SearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_search_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_search_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport() + adc.assert_called_once() + + +def test_search_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SearchServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + transports.SearchServiceRestTransport, + ], +) +def test_search_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SearchServiceGrpcTransport, grpc_helpers), + (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_search_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_no_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_with_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_branch_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = SearchServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = SearchServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = SearchServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = SearchServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py new file mode 100644 index 00000000..d88b744c --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py @@ -0,0 +1,3330 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.serving_config_service import ServingConfigServiceAsyncClient +from google.cloud.retail_v2beta.services.serving_config_service import ServingConfigServiceClient +from google.cloud.retail_v2beta.services.serving_config_service import pagers +from google.cloud.retail_v2beta.services.serving_config_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ServingConfigServiceClient._get_default_mtls_endpoint(None) is None + assert ServingConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ServingConfigServiceClient, "grpc"), + (ServingConfigServiceAsyncClient, "grpc_asyncio"), +]) +def test_serving_config_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ServingConfigServiceGrpcTransport, "grpc"), + (transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_serving_config_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", [ + (ServingConfigServiceClient, "grpc"), + (ServingConfigServiceAsyncClient, "grpc_asyncio"), +]) +def test_serving_config_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_serving_config_service_client_get_transport_class(): + transport = ServingConfigServiceClient.get_transport_class() + available_transports = [ + transports.ServingConfigServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ServingConfigServiceClient.get_transport_class("grpc") + assert transport == transports.ServingConfigServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +def test_serving_config_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(ServingConfigServiceClient, '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(ServingConfigServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "true"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "false"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_serving_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ServingConfigServiceClient, ServingConfigServiceAsyncClient +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +def test_serving_config_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_serving_config_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_serving_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_serving_config_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ServingConfigServiceClient( + 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", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_serving_config_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.CreateServingConfigRequest, + dict, +]) +def test_create_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_create_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.create_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + +@pytest.mark.asyncio +async def test_create_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.CreateServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_create_serving_config_async_from_dict(): + await test_create_serving_config_async(request_type=dict) + + +def test_create_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.CreateServingConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.CreateServingConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_serving_config( + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].serving_config + mock_val = gcr_serving_config.ServingConfig(name='name_value') + assert arg == mock_val + arg = args[0].serving_config_id + mock_val = 'serving_config_id_value' + assert arg == mock_val + + +def test_create_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.CreateServingConfigRequest(), + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_serving_config( + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].serving_config + mock_val = gcr_serving_config.ServingConfig(name='name_value') + assert arg == mock_val + arg = args[0].serving_config_id + mock_val = 'serving_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.CreateServingConfigRequest(), + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.DeleteServingConfigRequest, + dict, +]) +def test_delete_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.delete_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + +@pytest.mark.asyncio +async def test_delete_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.DeleteServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_serving_config_async_from_dict(): + await test_delete_serving_config_async(request_type=dict) + + +def test_delete_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.DeleteServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__call__') as call: + call.return_value = None + client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.DeleteServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__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_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.DeleteServingConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__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_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.DeleteServingConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.UpdateServingConfigRequest, + dict, +]) +def test_update_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_update_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.update_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + +@pytest.mark.asyncio +async def test_update_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.UpdateServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_update_serving_config_async_from_dict(): + await test_update_serving_config_async(request_type=dict) + + +def test_update_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.UpdateServingConfigRequest() + + request.serving_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.UpdateServingConfigRequest() + + request.serving_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config.name=name_value', + ) in kw['metadata'] + + +def test_update_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_serving_config( + serving_config=gcr_serving_config.ServingConfig(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].serving_config + mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_serving_config( + serving_config=gcr_serving_config.ServingConfig(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].serving_config + mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.GetServingConfigRequest, + dict, +]) +def test_get_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_get_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.get_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + +@pytest.mark.asyncio +async def test_get_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.GetServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_get_serving_config_async_from_dict(): + await test_get_serving_config_async(request_type=dict) + + +def test_get_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.GetServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + call.return_value = serving_config.ServingConfig() + client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.GetServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) + await client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.GetServingConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.GetServingConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.ListServingConfigsRequest, + dict, +]) +def test_list_serving_configs(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_serving_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_configs), + '__call__') as call: + client.list_serving_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + +@pytest.mark.asyncio +async def test_list_serving_configs_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.ListServingConfigsRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_serving_configs_async_from_dict(): + await test_list_serving_configs_async(request_type=dict) + + +def test_list_serving_configs_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.ListServingConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + call.return_value = serving_config_service.ListServingConfigsResponse() + client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_serving_configs_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.ListServingConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) + await client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_serving_configs_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_serving_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_serving_configs_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_serving_configs_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_serving_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_serving_configs_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent='parent_value', + ) + + +def test_list_serving_configs_pager(transport_name: str = "grpc"): + client = ServingConfigServiceClient( + 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_serving_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_serving_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, serving_config.ServingConfig) + for i in results) +def test_list_serving_configs_pages(transport_name: str = "grpc"): + client = ServingConfigServiceClient( + 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_serving_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_serving_configs(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_serving_configs_async_pager(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_serving_configs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, serving_config.ServingConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_serving_configs_async_pages(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_serving_configs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + serving_config_service.AddControlRequest, + dict, +]) +def test_add_control(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_add_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + client.add_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + +@pytest.mark.asyncio +async def test_add_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.AddControlRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_add_control_async_from_dict(): + await test_add_control_async(request_type=dict) + + +def test_add_control_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.AddControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_control_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.AddControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_add_control_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + + +def test_add_control_flattened_error(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_control( + serving_config_service.AddControlRequest(), + serving_config='serving_config_value', + ) + +@pytest.mark.asyncio +async def test_add_control_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_control_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_control( + serving_config_service.AddControlRequest(), + serving_config='serving_config_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.RemoveControlRequest, + dict, +]) +def test_remove_control(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_remove_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + client.remove_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + +@pytest.mark.asyncio +async def test_remove_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.RemoveControlRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_remove_control_async_from_dict(): + await test_remove_control_async(request_type=dict) + + +def test_remove_control_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.RemoveControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_control_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.RemoveControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_remove_control_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + + +def test_remove_control_flattened_error(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config='serving_config_value', + ) + +@pytest.mark.asyncio +async def test_remove_control_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_control_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config='serving_config_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServingConfigServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ServingConfigServiceClient.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 = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ServingConfigServiceGrpcTransport, + ) + +def test_serving_config_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ServingConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_serving_config_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ServingConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_serving_config', + 'delete_serving_config', + 'update_serving_config', + 'get_serving_config', + 'list_serving_configs', + 'add_control', + 'remove_control', + ) + 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_serving_config_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.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServingConfigServiceTransport( + 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_serving_config_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.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServingConfigServiceTransport() + adc.assert_called_once() + + +def test_serving_config_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) + ServingConfigServiceClient() + 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.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + ], +) +def test_serving_config_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.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + transports.ServingConfigServiceRestTransport, + ], +) +def test_serving_config_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.ServingConfigServiceGrpcTransport, grpc_helpers), + (transports.ServingConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_serving_config_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_serving_config_service_host_no_port(transport_name): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_serving_config_service_host_with_port(transport_name): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_serving_config_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServingConfigServiceGrpcTransport( + 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_serving_config_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + 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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = ServingConfigServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = ServingConfigServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + serving_config = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, serving_config=serving_config, ) + actual = ServingConfigServiceClient.serving_config_path(project, location, catalog, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "serving_config": "clam", + } + path = ServingConfigServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ServingConfigServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ServingConfigServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ServingConfigServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ServingConfigServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ServingConfigServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ServingConfigServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ServingConfigServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ServingConfigServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.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 = ServingConfigServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ServingConfigServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.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.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ServingConfigServiceClient.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 = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ServingConfigServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ServingConfigServiceClient( + 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", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py new file mode 100644 index 00000000..6ff51098 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py @@ -0,0 +1,2039 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.retail_v2beta.services.user_event_service import UserEventServiceClient +from google.cloud.retail_v2beta.services.user_event_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import promotion +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + ) + response = client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +def test_write_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) + await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeUserEventsRequest, + dict, +]) +def test_purge_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + client.purge_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + +@pytest.mark.asyncio +async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_user_events_async_from_dict(): + await test_purge_user_events_async(request_type=dict) + + +def test_purge_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_purge_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.RejoinUserEventsRequest, + dict, +]) +def test_rejoin_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_rejoin_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + client.rejoin_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + +@pytest.mark.asyncio +async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_rejoin_user_events_async_from_dict(): + await test_rejoin_user_events_async(request_type=dict) + + +def test_rejoin_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_rejoin_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'purge_user_events', + 'import_user_events', + 'rejoin_user_events', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_user_event_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_user_event_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +def test_user_event_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + UserEventServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +def test_user_event_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = UserEventServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = UserEventServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_product_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + product = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + "branch": "whelk", + "product": "octopus", + } + path = UserEventServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From cba043b1d1e049abb61248d94403294906208f96 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 23 Jun 2022 22:14:08 +0000 Subject: [PATCH 04/11] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../services/catalog_service/client.py | 1 + .../catalog_service/transports/base.py | 16 +- .../catalog_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/completion_service/client.py | 1 + .../completion_service/transports/base.py | 16 +- .../completion_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/prediction_service/client.py | 1 + .../prediction_service/transports/base.py | 16 +- .../prediction_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/product_service/client.py | 1 + .../product_service/transports/base.py | 16 +- .../product_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/search_service/client.py | 1 + .../search_service/transports/base.py | 16 +- .../search_service/transports/grpc.py | 2 + .../search_service/transports/grpc_asyncio.py | 2 + .../services/user_event_service/client.py | 1 + .../user_event_service/transports/base.py | 16 +- .../user_event_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/catalog_service/client.py | 1 + .../catalog_service/transports/base.py | 16 +- .../catalog_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/completion_service/client.py | 1 + .../completion_service/transports/base.py | 16 +- .../completion_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/control_service/client.py | 1 + .../control_service/transports/base.py | 16 +- .../control_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/prediction_service/client.py | 1 + .../prediction_service/transports/base.py | 16 +- .../prediction_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/product_service/client.py | 1 + .../product_service/transports/base.py | 16 +- .../product_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/search_service/client.py | 1 + .../search_service/transports/base.py | 16 +- .../search_service/transports/grpc.py | 2 + .../search_service/transports/grpc_asyncio.py | 2 + .../services/serving_config_service/client.py | 1 + .../serving_config_service/transports/base.py | 16 +- .../serving_config_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/user_event_service/client.py | 1 + .../user_event_service/transports/base.py | 16 +- .../user_event_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/catalog_service/client.py | 1 + .../catalog_service/transports/base.py | 16 +- .../catalog_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/completion_service/client.py | 1 + .../completion_service/transports/base.py | 16 +- .../completion_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/control_service/client.py | 1 + .../control_service/transports/base.py | 16 +- .../control_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/prediction_service/client.py | 1 + .../prediction_service/transports/base.py | 16 +- .../prediction_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/product_service/client.py | 1 + .../product_service/transports/base.py | 16 +- .../product_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/search_service/client.py | 1 + .../search_service/transports/base.py | 16 +- .../search_service/transports/grpc.py | 2 + .../search_service/transports/grpc_asyncio.py | 2 + .../services/serving_config_service/client.py | 1 + .../serving_config_service/transports/base.py | 16 +- .../serving_config_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/user_event_service/client.py | 1 + .../user_event_service/transports/base.py | 16 +- .../user_event_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + owl-bot-staging/v2/.coveragerc | 17 - owl-bot-staging/v2/.flake8 | 33 - owl-bot-staging/v2/MANIFEST.in | 2 - owl-bot-staging/v2/README.rst | 49 - owl-bot-staging/v2/docs/conf.py | 376 - owl-bot-staging/v2/docs/index.rst | 7 - .../v2/docs/retail_v2/catalog_service.rst | 10 - .../v2/docs/retail_v2/completion_service.rst | 6 - .../v2/docs/retail_v2/prediction_service.rst | 6 - .../v2/docs/retail_v2/product_service.rst | 10 - .../v2/docs/retail_v2/search_service.rst | 10 - .../v2/docs/retail_v2/services.rst | 11 - owl-bot-staging/v2/docs/retail_v2/types.rst | 7 - .../v2/docs/retail_v2/user_event_service.rst | 6 - .../v2/google/cloud/retail/__init__.py | 193 - .../v2/google/cloud/retail/py.typed | 2 - .../v2/google/cloud/retail_v2/__init__.py | 194 - .../cloud/retail_v2/gapic_metadata.json | 333 - .../v2/google/cloud/retail_v2/py.typed | 2 - .../cloud/retail_v2/services/__init__.py | 15 - .../services/catalog_service/__init__.py | 22 - .../services/catalog_service/async_client.py | 653 -- .../services/catalog_service/client.py | 862 -- .../services/catalog_service/pagers.py | 140 - .../catalog_service/transports/__init__.py | 33 - .../catalog_service/transports/base.py | 198 - .../catalog_service/transports/grpc.py | 381 - .../transports/grpc_asyncio.py | 380 - .../services/completion_service/__init__.py | 22 - .../completion_service/async_client.py | 391 - .../services/completion_service/client.py | 593 -- .../completion_service/transports/__init__.py | 33 - .../completion_service/transports/base.py | 176 - .../completion_service/transports/grpc.py | 325 - .../transports/grpc_asyncio.py | 324 - .../services/prediction_service/__init__.py | 22 - .../prediction_service/async_client.py | 279 - .../services/prediction_service/client.py | 480 -- .../prediction_service/transports/__init__.py | 33 - .../prediction_service/transports/base.py | 154 - .../prediction_service/transports/grpc.py | 264 - .../transports/grpc_asyncio.py | 263 - .../services/product_service/__init__.py | 22 - .../services/product_service/async_client.py | 1701 ---- .../services/product_service/client.py | 1904 ----- .../services/product_service/pagers.py | 140 - .../product_service/transports/__init__.py | 33 - .../product_service/transports/base.py | 312 - .../product_service/transports/grpc.py | 680 -- .../transports/grpc_asyncio.py | 679 -- .../services/search_service/__init__.py | 22 - .../services/search_service/async_client.py | 303 - .../services/search_service/client.py | 513 -- .../services/search_service/pagers.py | 139 - .../search_service/transports/__init__.py | 33 - .../search_service/transports/base.py | 154 - .../search_service/transports/grpc.py | 270 - .../search_service/transports/grpc_asyncio.py | 269 - .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 730 -- .../services/user_event_service/client.py | 930 --- .../user_event_service/transports/__init__.py | 33 - .../user_event_service/transports/base.py | 235 - .../user_event_service/transports/grpc.py | 417 - .../transports/grpc_asyncio.py | 416 - .../google/cloud/retail_v2/types/__init__.py | 194 - .../google/cloud/retail_v2/types/catalog.py | 131 - .../cloud/retail_v2/types/catalog_service.py | 248 - .../v2/google/cloud/retail_v2/types/common.py | 736 -- .../retail_v2/types/completion_service.py | 229 - .../cloud/retail_v2/types/import_config.py | 697 -- .../retail_v2/types/prediction_service.py | 275 - .../google/cloud/retail_v2/types/product.py | 701 -- .../cloud/retail_v2/types/product_service.py | 858 -- .../google/cloud/retail_v2/types/promotion.py | 50 - .../cloud/retail_v2/types/purge_config.py | 107 - .../cloud/retail_v2/types/search_service.py | 1150 --- .../cloud/retail_v2/types/user_event.py | 508 -- .../retail_v2/types/user_event_service.py | 154 - owl-bot-staging/v2/mypy.ini | 3 - owl-bot-staging/v2/noxfile.py | 180 - ...atalog_service_get_default_branch_async.py | 44 - ...catalog_service_get_default_branch_sync.py | 44 - ...ted_catalog_service_list_catalogs_async.py | 46 - ...ated_catalog_service_list_catalogs_sync.py | 46 - ...atalog_service_set_default_branch_async.py | 42 - ...catalog_service_set_default_branch_sync.py | 42 - ...ed_catalog_service_update_catalog_async.py | 49 - ...ted_catalog_service_update_catalog_sync.py | 49 - ...completion_service_complete_query_async.py | 46 - ..._completion_service_complete_query_sync.py | 46 - ...on_service_import_completion_data_async.py | 54 - ...ion_service_import_completion_data_sync.py | 54 - ...erated_prediction_service_predict_async.py | 50 - ...nerated_prediction_service_predict_sync.py | 50 - ...ct_service_add_fulfillment_places_async.py | 51 - ...uct_service_add_fulfillment_places_sync.py | 51 - ...uct_service_add_local_inventories_async.py | 49 - ...duct_service_add_local_inventories_sync.py | 49 - ...ed_product_service_create_product_async.py | 50 - ...ted_product_service_create_product_sync.py | 50 - ...ed_product_service_delete_product_async.py | 43 - ...ted_product_service_delete_product_sync.py | 43 - ...rated_product_service_get_product_async.py | 45 - ...erated_product_service_get_product_sync.py | 45 - ...d_product_service_import_products_async.py | 53 - ...ed_product_service_import_products_sync.py | 53 - ...ted_product_service_list_products_async.py | 46 - ...ated_product_service_list_products_sync.py | 46 - ...service_remove_fulfillment_places_async.py | 51 - ..._service_remove_fulfillment_places_sync.py | 51 - ..._service_remove_local_inventories_async.py | 50 - ...t_service_remove_local_inventories_sync.py | 50 - ...ted_product_service_set_inventory_async.py | 52 - ...ated_product_service_set_inventory_sync.py | 52 - ...ed_product_service_update_product_async.py | 48 - ...ted_product_service_update_product_sync.py | 48 - ...2_generated_search_service_search_async.py | 47 - ...v2_generated_search_service_search_sync.py | 47 - ..._event_service_collect_user_event_async.py | 46 - ...r_event_service_collect_user_event_sync.py | 46 - ..._event_service_import_user_events_async.py | 54 - ...r_event_service_import_user_events_sync.py | 54 - ...r_event_service_purge_user_events_async.py | 50 - ...er_event_service_purge_user_events_sync.py | 50 - ..._event_service_rejoin_user_events_async.py | 49 - ...r_event_service_rejoin_user_events_sync.py | 49 - ...er_event_service_write_user_event_async.py | 50 - ...ser_event_service_write_user_event_sync.py | 50 - .../snippet_metadata_retail_v2.json | 3826 --------- .../v2/scripts/fixup_retail_v2_keywords.py | 199 - owl-bot-staging/v2/setup.py | 59 - owl-bot-staging/v2/tests/__init__.py | 16 - owl-bot-staging/v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../v2/tests/unit/gapic/retail_v2/__init__.py | 16 - .../gapic/retail_v2/test_catalog_service.py | 2318 ------ .../retail_v2/test_completion_service.py | 1502 ---- .../retail_v2/test_prediction_service.py | 1330 ---- .../gapic/retail_v2/test_product_service.py | 4136 ---------- .../gapic/retail_v2/test_search_service.py | 1547 ---- .../retail_v2/test_user_event_service.py | 2039 ----- owl-bot-staging/v2alpha/.coveragerc | 17 - owl-bot-staging/v2alpha/.flake8 | 33 - owl-bot-staging/v2alpha/MANIFEST.in | 2 - owl-bot-staging/v2alpha/README.rst | 49 - owl-bot-staging/v2alpha/docs/conf.py | 376 - owl-bot-staging/v2alpha/docs/index.rst | 7 - .../docs/retail_v2alpha/catalog_service.rst | 10 - .../retail_v2alpha/completion_service.rst | 6 - .../docs/retail_v2alpha/control_service.rst | 10 - .../retail_v2alpha/prediction_service.rst | 6 - .../docs/retail_v2alpha/product_service.rst | 10 - .../docs/retail_v2alpha/search_service.rst | 10 - .../v2alpha/docs/retail_v2alpha/services.rst | 13 - .../retail_v2alpha/serving_config_service.rst | 10 - .../v2alpha/docs/retail_v2alpha/types.rst | 7 - .../retail_v2alpha/user_event_service.rst | 6 - .../v2alpha/google/cloud/retail/__init__.py | 281 - .../v2alpha/google/cloud/retail/py.typed | 2 - .../google/cloud/retail_v2alpha/__init__.py | 282 - .../cloud/retail_v2alpha/gapic_metadata.json | 561 -- .../google/cloud/retail_v2alpha/py.typed | 2 - .../cloud/retail_v2alpha/services/__init__.py | 15 - .../services/catalog_service/__init__.py | 22 - .../services/catalog_service/async_client.py | 1352 ---- .../services/catalog_service/client.py | 1582 ---- .../services/catalog_service/pagers.py | 140 - .../catalog_service/transports/__init__.py | 33 - .../catalog_service/transports/base.py | 297 - .../catalog_service/transports/grpc.py | 600 -- .../transports/grpc_asyncio.py | 599 -- .../services/completion_service/__init__.py | 22 - .../completion_service/async_client.py | 391 - .../services/completion_service/client.py | 593 -- .../completion_service/transports/__init__.py | 33 - .../completion_service/transports/base.py | 176 - .../completion_service/transports/grpc.py | 325 - .../transports/grpc_asyncio.py | 324 - .../services/control_service/__init__.py | 22 - .../services/control_service/async_client.py | 744 -- .../services/control_service/client.py | 953 --- .../services/control_service/pagers.py | 140 - .../control_service/transports/__init__.py | 33 - .../control_service/transports/base.py | 213 - .../control_service/transports/grpc.py | 382 - .../transports/grpc_asyncio.py | 381 - .../services/prediction_service/__init__.py | 22 - .../prediction_service/async_client.py | 279 - .../services/prediction_service/client.py | 480 -- .../prediction_service/transports/__init__.py | 33 - .../prediction_service/transports/base.py | 154 - .../prediction_service/transports/grpc.py | 264 - .../transports/grpc_asyncio.py | 263 - .../services/product_service/__init__.py | 22 - .../services/product_service/async_client.py | 1804 ----- .../services/product_service/client.py | 2008 ----- .../services/product_service/pagers.py | 140 - .../product_service/transports/__init__.py | 33 - .../product_service/transports/base.py | 327 - .../product_service/transports/grpc.py | 726 -- .../transports/grpc_asyncio.py | 725 -- .../services/search_service/__init__.py | 22 - .../services/search_service/async_client.py | 303 - .../services/search_service/client.py | 513 -- .../services/search_service/pagers.py | 139 - .../search_service/transports/__init__.py | 33 - .../search_service/transports/base.py | 154 - .../search_service/transports/grpc.py | 270 - .../search_service/transports/grpc_asyncio.py | 269 - .../serving_config_service/__init__.py | 22 - .../serving_config_service/async_client.py | 954 --- .../services/serving_config_service/client.py | 1163 --- .../services/serving_config_service/pagers.py | 140 - .../transports/__init__.py | 33 - .../serving_config_service/transports/base.py | 241 - .../serving_config_service/transports/grpc.py | 440 - .../transports/grpc_asyncio.py | 439 - .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 730 -- .../services/user_event_service/client.py | 930 --- .../user_event_service/transports/__init__.py | 33 - .../user_event_service/transports/base.py | 235 - .../user_event_service/transports/grpc.py | 417 - .../transports/grpc_asyncio.py | 416 - .../cloud/retail_v2alpha/types/__init__.py | 284 - .../cloud/retail_v2alpha/types/catalog.py | 528 -- .../retail_v2alpha/types/catalog_service.py | 453 -- .../cloud/retail_v2alpha/types/common.py | 1179 --- .../types/completion_service.py | 223 - .../cloud/retail_v2alpha/types/control.py | 123 - .../retail_v2alpha/types/control_service.py | 197 - .../retail_v2alpha/types/export_config.py | 134 - .../retail_v2alpha/types/import_config.py | 691 -- .../types/prediction_service.py | 263 - .../cloud/retail_v2alpha/types/product.py | 705 -- .../retail_v2alpha/types/product_service.py | 877 -- .../cloud/retail_v2alpha/types/promotion.py | 50 - .../retail_v2alpha/types/purge_config.py | 251 - .../retail_v2alpha/types/search_service.py | 1099 --- .../retail_v2alpha/types/serving_config.py | 309 - .../types/serving_config_service.py | 234 - .../cloud/retail_v2alpha/types/user_event.py | 507 -- .../types/user_event_service.py | 154 - owl-bot-staging/v2alpha/mypy.ini | 3 - owl-bot-staging/v2alpha/noxfile.py | 180 - ...log_service_add_catalog_attribute_async.py | 49 - ...alog_service_add_catalog_attribute_sync.py | 49 - ...log_service_get_attributes_config_async.py | 45 - ...alog_service_get_attributes_config_sync.py | 45 - ...log_service_get_completion_config_async.py | 45 - ...alog_service_get_completion_config_sync.py | 45 - ...atalog_service_get_default_branch_async.py | 44 - ...catalog_service_get_default_branch_sync.py | 44 - ...ted_catalog_service_list_catalogs_async.py | 46 - ...ated_catalog_service_list_catalogs_sync.py | 46 - ..._service_remove_catalog_attribute_async.py | 46 - ...g_service_remove_catalog_attribute_sync.py | 46 - ...service_replace_catalog_attribute_async.py | 49 - ..._service_replace_catalog_attribute_sync.py | 49 - ...atalog_service_set_default_branch_async.py | 42 - ...catalog_service_set_default_branch_sync.py | 42 - ..._service_update_attributes_config_async.py | 48 - ...g_service_update_attributes_config_sync.py | 48 - ...ed_catalog_service_update_catalog_async.py | 49 - ...ted_catalog_service_update_catalog_sync.py | 49 - ..._service_update_completion_config_async.py | 48 - ...g_service_update_completion_config_sync.py | 48 - ...completion_service_complete_query_async.py | 46 - ..._completion_service_complete_query_sync.py | 46 - ...on_service_import_completion_data_async.py | 54 - ...ion_service_import_completion_data_sync.py | 54 - ...ed_control_service_create_control_async.py | 53 - ...ted_control_service_create_control_sync.py | 53 - ...ed_control_service_delete_control_async.py | 43 - ...ted_control_service_delete_control_sync.py | 43 - ...rated_control_service_get_control_async.py | 45 - ...erated_control_service_get_control_sync.py | 45 - ...ted_control_service_list_controls_async.py | 46 - ...ated_control_service_list_controls_sync.py | 46 - ...ed_control_service_update_control_async.py | 51 - ...ted_control_service_update_control_sync.py | 51 - ...erated_prediction_service_predict_async.py | 50 - ...nerated_prediction_service_predict_sync.py | 50 - ...ct_service_add_fulfillment_places_async.py | 51 - ...uct_service_add_fulfillment_places_sync.py | 51 - ...uct_service_add_local_inventories_async.py | 49 - ...duct_service_add_local_inventories_sync.py | 49 - ...ed_product_service_create_product_async.py | 50 - ...ted_product_service_create_product_sync.py | 50 - ...ed_product_service_delete_product_async.py | 43 - ...ted_product_service_delete_product_sync.py | 43 - ...rated_product_service_get_product_async.py | 45 - ...erated_product_service_get_product_sync.py | 45 - ...d_product_service_import_products_async.py | 53 - ...ed_product_service_import_products_sync.py | 53 - ...ted_product_service_list_products_async.py | 46 - ...ated_product_service_list_products_sync.py | 46 - ...ed_product_service_purge_products_async.py | 50 - ...ted_product_service_purge_products_sync.py | 50 - ...service_remove_fulfillment_places_async.py | 51 - ..._service_remove_fulfillment_places_sync.py | 51 - ..._service_remove_local_inventories_async.py | 50 - ...t_service_remove_local_inventories_sync.py | 50 - ...ted_product_service_set_inventory_async.py | 52 - ...ated_product_service_set_inventory_sync.py | 52 - ...ed_product_service_update_product_async.py | 48 - ...ted_product_service_update_product_sync.py | 48 - ...a_generated_search_service_search_async.py | 47 - ...ha_generated_search_service_search_sync.py | 47 - ...erving_config_service_add_control_async.py | 46 - ...serving_config_service_add_control_sync.py | 46 - ...fig_service_create_serving_config_async.py | 51 - ...nfig_service_create_serving_config_sync.py | 51 - ...fig_service_delete_serving_config_async.py | 43 - ...nfig_service_delete_serving_config_sync.py | 43 - ...config_service_get_serving_config_async.py | 45 - ..._config_service_get_serving_config_sync.py | 45 - ...nfig_service_list_serving_configs_async.py | 46 - ...onfig_service_list_serving_configs_sync.py | 46 - ...ing_config_service_remove_control_async.py | 46 - ...ving_config_service_remove_control_sync.py | 46 - ...fig_service_update_serving_config_async.py | 49 - ...nfig_service_update_serving_config_sync.py | 49 - ..._event_service_collect_user_event_async.py | 46 - ...r_event_service_collect_user_event_sync.py | 46 - ..._event_service_import_user_events_async.py | 54 - ...r_event_service_import_user_events_sync.py | 54 - ...r_event_service_purge_user_events_async.py | 50 - ...er_event_service_purge_user_events_sync.py | 50 - ..._event_service_rejoin_user_events_async.py | 49 - ...r_event_service_rejoin_user_events_sync.py | 49 - ...er_event_service_write_user_event_async.py | 50 - ...ser_event_service_write_user_event_sync.py | 50 - .../snippet_metadata_retail_v2alpha.json | 7066 ----------------- .../scripts/fixup_retail_v2alpha_keywords.py | 219 - owl-bot-staging/v2alpha/setup.py | 59 - owl-bot-staging/v2alpha/tests/__init__.py | 16 - .../v2alpha/tests/unit/__init__.py | 16 - .../v2alpha/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/retail_v2alpha/__init__.py | 16 - .../retail_v2alpha/test_catalog_service.py | 3844 --------- .../retail_v2alpha/test_completion_service.py | 1502 ---- .../retail_v2alpha/test_control_service.py | 2617 ------ .../retail_v2alpha/test_prediction_service.py | 1330 ---- .../retail_v2alpha/test_product_service.py | 4288 ---------- .../retail_v2alpha/test_search_service.py | 1547 ---- .../test_serving_config_service.py | 3330 -------- .../retail_v2alpha/test_user_event_service.py | 2039 ----- owl-bot-staging/v2beta/.coveragerc | 17 - owl-bot-staging/v2beta/.flake8 | 33 - owl-bot-staging/v2beta/MANIFEST.in | 2 - owl-bot-staging/v2beta/README.rst | 49 - owl-bot-staging/v2beta/docs/conf.py | 376 - owl-bot-staging/v2beta/docs/index.rst | 7 - .../docs/retail_v2beta/catalog_service.rst | 10 - .../docs/retail_v2beta/completion_service.rst | 6 - .../docs/retail_v2beta/control_service.rst | 10 - .../docs/retail_v2beta/prediction_service.rst | 6 - .../docs/retail_v2beta/product_service.rst | 10 - .../docs/retail_v2beta/search_service.rst | 10 - .../v2beta/docs/retail_v2beta/services.rst | 13 - .../retail_v2beta/serving_config_service.rst | 10 - .../v2beta/docs/retail_v2beta/types.rst | 7 - .../docs/retail_v2beta/user_event_service.rst | 6 - .../v2beta/google/cloud/retail/__init__.py | 275 - .../v2beta/google/cloud/retail/py.typed | 2 - .../google/cloud/retail_v2beta/__init__.py | 276 - .../cloud/retail_v2beta/gapic_metadata.json | 551 -- .../google/cloud/retail_v2beta/py.typed | 2 - .../cloud/retail_v2beta/services/__init__.py | 15 - .../services/catalog_service/__init__.py | 22 - .../services/catalog_service/async_client.py | 1350 ---- .../services/catalog_service/client.py | 1580 ---- .../services/catalog_service/pagers.py | 140 - .../catalog_service/transports/__init__.py | 33 - .../catalog_service/transports/base.py | 297 - .../catalog_service/transports/grpc.py | 600 -- .../transports/grpc_asyncio.py | 599 -- .../services/completion_service/__init__.py | 22 - .../completion_service/async_client.py | 391 - .../services/completion_service/client.py | 593 -- .../completion_service/transports/__init__.py | 33 - .../completion_service/transports/base.py | 176 - .../completion_service/transports/grpc.py | 325 - .../transports/grpc_asyncio.py | 324 - .../services/control_service/__init__.py | 22 - .../services/control_service/async_client.py | 742 -- .../services/control_service/client.py | 951 --- .../services/control_service/pagers.py | 140 - .../control_service/transports/__init__.py | 33 - .../control_service/transports/base.py | 213 - .../control_service/transports/grpc.py | 382 - .../transports/grpc_asyncio.py | 381 - .../services/prediction_service/__init__.py | 22 - .../prediction_service/async_client.py | 279 - .../services/prediction_service/client.py | 480 -- .../prediction_service/transports/__init__.py | 33 - .../prediction_service/transports/base.py | 154 - .../prediction_service/transports/grpc.py | 264 - .../transports/grpc_asyncio.py | 263 - .../services/product_service/__init__.py | 22 - .../services/product_service/async_client.py | 1692 ---- .../services/product_service/client.py | 1895 ----- .../services/product_service/pagers.py | 140 - .../product_service/transports/__init__.py | 33 - .../product_service/transports/base.py | 312 - .../product_service/transports/grpc.py | 680 -- .../transports/grpc_asyncio.py | 679 -- .../services/search_service/__init__.py | 22 - .../services/search_service/async_client.py | 303 - .../services/search_service/client.py | 513 -- .../services/search_service/pagers.py | 139 - .../search_service/transports/__init__.py | 33 - .../search_service/transports/base.py | 154 - .../search_service/transports/grpc.py | 270 - .../search_service/transports/grpc_asyncio.py | 269 - .../serving_config_service/__init__.py | 22 - .../serving_config_service/async_client.py | 954 --- .../services/serving_config_service/client.py | 1163 --- .../services/serving_config_service/pagers.py | 140 - .../transports/__init__.py | 33 - .../serving_config_service/transports/base.py | 241 - .../serving_config_service/transports/grpc.py | 440 - .../transports/grpc_asyncio.py | 439 - .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 730 -- .../services/user_event_service/client.py | 930 --- .../user_event_service/transports/__init__.py | 33 - .../user_event_service/transports/base.py | 235 - .../user_event_service/transports/grpc.py | 417 - .../transports/grpc_asyncio.py | 416 - .../cloud/retail_v2beta/types/__init__.py | 278 - .../cloud/retail_v2beta/types/catalog.py | 528 -- .../retail_v2beta/types/catalog_service.py | 453 -- .../cloud/retail_v2beta/types/common.py | 1178 --- .../retail_v2beta/types/completion_service.py | 223 - .../cloud/retail_v2beta/types/control.py | 112 - .../retail_v2beta/types/control_service.py | 197 - .../retail_v2beta/types/export_config.py | 134 - .../retail_v2beta/types/import_config.py | 691 -- .../retail_v2beta/types/prediction_service.py | 263 - .../cloud/retail_v2beta/types/product.py | 705 -- .../retail_v2beta/types/product_service.py | 844 -- .../cloud/retail_v2beta/types/promotion.py | 50 - .../cloud/retail_v2beta/types/purge_config.py | 107 - .../retail_v2beta/types/search_service.py | 1074 --- .../retail_v2beta/types/serving_config.py | 309 - .../types/serving_config_service.py | 234 - .../cloud/retail_v2beta/types/user_event.py | 507 -- .../retail_v2beta/types/user_event_service.py | 154 - owl-bot-staging/v2beta/mypy.ini | 3 - owl-bot-staging/v2beta/noxfile.py | 180 - ...log_service_add_catalog_attribute_async.py | 49 - ...alog_service_add_catalog_attribute_sync.py | 49 - ...log_service_get_attributes_config_async.py | 45 - ...alog_service_get_attributes_config_sync.py | 45 - ...log_service_get_completion_config_async.py | 45 - ...alog_service_get_completion_config_sync.py | 45 - ...atalog_service_get_default_branch_async.py | 44 - ...catalog_service_get_default_branch_sync.py | 44 - ...ted_catalog_service_list_catalogs_async.py | 46 - ...ated_catalog_service_list_catalogs_sync.py | 46 - ..._service_remove_catalog_attribute_async.py | 46 - ...g_service_remove_catalog_attribute_sync.py | 46 - ...service_replace_catalog_attribute_async.py | 49 - ..._service_replace_catalog_attribute_sync.py | 49 - ...atalog_service_set_default_branch_async.py | 42 - ...catalog_service_set_default_branch_sync.py | 42 - ..._service_update_attributes_config_async.py | 48 - ...g_service_update_attributes_config_sync.py | 48 - ...ed_catalog_service_update_catalog_async.py | 49 - ...ted_catalog_service_update_catalog_sync.py | 49 - ..._service_update_completion_config_async.py | 48 - ...g_service_update_completion_config_sync.py | 48 - ...completion_service_complete_query_async.py | 46 - ..._completion_service_complete_query_sync.py | 46 - ...on_service_import_completion_data_async.py | 54 - ...ion_service_import_completion_data_sync.py | 54 - ...ed_control_service_create_control_async.py | 52 - ...ted_control_service_create_control_sync.py | 52 - ...ed_control_service_delete_control_async.py | 43 - ...ted_control_service_delete_control_sync.py | 43 - ...rated_control_service_get_control_async.py | 45 - ...erated_control_service_get_control_sync.py | 45 - ...ted_control_service_list_controls_async.py | 46 - ...ated_control_service_list_controls_sync.py | 46 - ...ed_control_service_update_control_async.py | 50 - ...ted_control_service_update_control_sync.py | 50 - ...erated_prediction_service_predict_async.py | 50 - ...nerated_prediction_service_predict_sync.py | 50 - ...ct_service_add_fulfillment_places_async.py | 51 - ...uct_service_add_fulfillment_places_sync.py | 51 - ...uct_service_add_local_inventories_async.py | 49 - ...duct_service_add_local_inventories_sync.py | 49 - ...ed_product_service_create_product_async.py | 50 - ...ted_product_service_create_product_sync.py | 50 - ...ed_product_service_delete_product_async.py | 43 - ...ted_product_service_delete_product_sync.py | 43 - ...rated_product_service_get_product_async.py | 45 - ...erated_product_service_get_product_sync.py | 45 - ...d_product_service_import_products_async.py | 53 - ...ed_product_service_import_products_sync.py | 53 - ...ted_product_service_list_products_async.py | 46 - ...ated_product_service_list_products_sync.py | 46 - ...service_remove_fulfillment_places_async.py | 51 - ..._service_remove_fulfillment_places_sync.py | 51 - ..._service_remove_local_inventories_async.py | 50 - ...t_service_remove_local_inventories_sync.py | 50 - ...ted_product_service_set_inventory_async.py | 52 - ...ated_product_service_set_inventory_sync.py | 52 - ...ed_product_service_update_product_async.py | 48 - ...ted_product_service_update_product_sync.py | 48 - ...a_generated_search_service_search_async.py | 47 - ...ta_generated_search_service_search_sync.py | 47 - ...erving_config_service_add_control_async.py | 46 - ...serving_config_service_add_control_sync.py | 46 - ...fig_service_create_serving_config_async.py | 51 - ...nfig_service_create_serving_config_sync.py | 51 - ...fig_service_delete_serving_config_async.py | 43 - ...nfig_service_delete_serving_config_sync.py | 43 - ...config_service_get_serving_config_async.py | 45 - ..._config_service_get_serving_config_sync.py | 45 - ...nfig_service_list_serving_configs_async.py | 46 - ...onfig_service_list_serving_configs_sync.py | 46 - ...ing_config_service_remove_control_async.py | 46 - ...ving_config_service_remove_control_sync.py | 46 - ...fig_service_update_serving_config_async.py | 49 - ...nfig_service_update_serving_config_sync.py | 49 - ..._event_service_collect_user_event_async.py | 46 - ...r_event_service_collect_user_event_sync.py | 46 - ..._event_service_import_user_events_async.py | 54 - ...r_event_service_import_user_events_sync.py | 54 - ...r_event_service_purge_user_events_async.py | 50 - ...er_event_service_purge_user_events_sync.py | 50 - ..._event_service_rejoin_user_events_async.py | 49 - ...r_event_service_rejoin_user_events_sync.py | 49 - ...er_event_service_write_user_event_async.py | 50 - ...ser_event_service_write_user_event_sync.py | 50 - .../snippet_metadata_retail_v2beta.json | 6913 ---------------- .../scripts/fixup_retail_v2beta_keywords.py | 218 - owl-bot-staging/v2beta/setup.py | 59 - owl-bot-staging/v2beta/tests/__init__.py | 16 - owl-bot-staging/v2beta/tests/unit/__init__.py | 16 - .../v2beta/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/retail_v2beta/__init__.py | 16 - .../retail_v2beta/test_catalog_service.py | 3844 --------- .../retail_v2beta/test_completion_service.py | 1502 ---- .../retail_v2beta/test_control_service.py | 2605 ------ .../retail_v2beta/test_prediction_service.py | 1330 ---- .../retail_v2beta/test_product_service.py | 4136 ---------- .../retail_v2beta/test_search_service.py | 1547 ---- .../test_serving_config_service.py | 3330 -------- .../retail_v2beta/test_user_event_service.py | 2039 ----- .../gapic/retail_v2/test_catalog_service.py | 53 + .../retail_v2/test_completion_service.py | 53 + .../retail_v2/test_prediction_service.py | 53 + .../gapic/retail_v2/test_product_service.py | 53 + .../gapic/retail_v2/test_search_service.py | 53 + .../retail_v2/test_user_event_service.py | 53 + .../retail_v2alpha/test_catalog_service.py | 53 + .../retail_v2alpha/test_completion_service.py | 53 + .../retail_v2alpha/test_control_service.py | 53 + .../retail_v2alpha/test_prediction_service.py | 53 + .../retail_v2alpha/test_product_service.py | 53 + .../retail_v2alpha/test_search_service.py | 53 + .../test_serving_config_service.py | 53 + .../retail_v2alpha/test_user_event_service.py | 53 + .../retail_v2beta/test_catalog_service.py | 53 + .../retail_v2beta/test_completion_service.py | 53 + .../retail_v2beta/test_control_service.py | 53 + .../retail_v2beta/test_prediction_service.py | 53 + .../retail_v2beta/test_product_service.py | 53 + .../retail_v2beta/test_search_service.py | 53 + .../test_serving_config_service.py | 53 + .../retail_v2beta/test_user_event_service.py | 53 + 664 files changed, 1518 insertions(+), 175625 deletions(-) delete mode 100644 owl-bot-staging/v2/.coveragerc delete mode 100644 owl-bot-staging/v2/.flake8 delete mode 100644 owl-bot-staging/v2/MANIFEST.in delete mode 100644 owl-bot-staging/v2/README.rst delete mode 100644 owl-bot-staging/v2/docs/conf.py delete mode 100644 owl-bot-staging/v2/docs/index.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/catalog_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/completion_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/prediction_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/product_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/search_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/services.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/types.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/user_event_service.rst delete mode 100644 owl-bot-staging/v2/google/cloud/retail/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/common.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/product.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py delete mode 100644 owl-bot-staging/v2/mypy.ini delete mode 100644 owl-bot-staging/v2/noxfile.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json delete mode 100644 owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py delete mode 100644 owl-bot-staging/v2/setup.py delete mode 100644 owl-bot-staging/v2/tests/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py delete mode 100644 owl-bot-staging/v2alpha/.coveragerc delete mode 100644 owl-bot-staging/v2alpha/.flake8 delete mode 100644 owl-bot-staging/v2alpha/MANIFEST.in delete mode 100644 owl-bot-staging/v2alpha/README.rst delete mode 100644 owl-bot-staging/v2alpha/docs/conf.py delete mode 100644 owl-bot-staging/v2alpha/docs/index.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail/py.typed delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py delete mode 100644 owl-bot-staging/v2alpha/mypy.ini delete mode 100644 owl-bot-staging/v2alpha/noxfile.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json delete mode 100644 owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py delete mode 100644 owl-bot-staging/v2alpha/setup.py delete mode 100644 owl-bot-staging/v2alpha/tests/__init__.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py delete mode 100644 owl-bot-staging/v2beta/.coveragerc delete mode 100644 owl-bot-staging/v2beta/.flake8 delete mode 100644 owl-bot-staging/v2beta/MANIFEST.in delete mode 100644 owl-bot-staging/v2beta/README.rst delete mode 100644 owl-bot-staging/v2beta/docs/conf.py delete mode 100644 owl-bot-staging/v2beta/docs/index.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/services.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/types.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail/py.typed delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py delete mode 100644 owl-bot-staging/v2beta/mypy.ini delete mode 100644 owl-bot-staging/v2beta/noxfile.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json delete mode 100644 owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py delete mode 100644 owl-bot-staging/v2beta/setup.py delete mode 100644 owl-bot-staging/v2beta/tests/__init__.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py diff --git a/google/cloud/retail_v2/services/catalog_service/client.py b/google/cloud/retail_v2/services/catalog_service/client.py index 3ae00a3e..befb9cab 100644 --- a/google/cloud/retail_v2/services/catalog_service/client.py +++ b/google/cloud/retail_v2/services/catalog_service/client.py @@ -454,6 +454,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def list_catalogs( diff --git a/google/cloud/retail_v2/services/catalog_service/transports/base.py b/google/cloud/retail_v2/services/catalog_service/transports/base.py index f2153ee0..6aea02e1 100644 --- a/google/cloud/retail_v2/services/catalog_service/transports/base.py +++ b/google/cloud/retail_v2/services/catalog_service/transports/base.py @@ -56,6 +56,7 @@ def __init__( 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. @@ -83,11 +84,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -108,6 +104,11 @@ def __init__( 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 ( @@ -120,6 +121,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2/services/catalog_service/transports/grpc.py b/google/cloud/retail_v2/services/catalog_service/transports/grpc.py index a7ca7252..019d95f2 100644 --- a/google/cloud/retail_v2/services/catalog_service/transports/grpc.py +++ b/google/cloud/retail_v2/services/catalog_service/transports/grpc.py @@ -59,6 +59,7 @@ def __init__( 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. @@ -154,6 +155,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py b/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py index 5e23c65d..92691563 100644 --- a/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py @@ -104,6 +104,7 @@ def __init__( quota_project_id=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. @@ -199,6 +200,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2/services/completion_service/client.py b/google/cloud/retail_v2/services/completion_service/client.py index 47b5e807..e8e3948d 100644 --- a/google/cloud/retail_v2/services/completion_service/client.py +++ b/google/cloud/retail_v2/services/completion_service/client.py @@ -431,6 +431,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def complete_query( diff --git a/google/cloud/retail_v2/services/completion_service/transports/base.py b/google/cloud/retail_v2/services/completion_service/transports/base.py index 3c55560d..29260ba8 100644 --- a/google/cloud/retail_v2/services/completion_service/transports/base.py +++ b/google/cloud/retail_v2/services/completion_service/transports/base.py @@ -55,6 +55,7 @@ def __init__( 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. @@ -82,11 +83,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -107,6 +103,11 @@ def __init__( 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 ( @@ -119,6 +120,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2/services/completion_service/transports/grpc.py b/google/cloud/retail_v2/services/completion_service/transports/grpc.py index d05b4ef6..c202d62f 100644 --- a/google/cloud/retail_v2/services/completion_service/transports/grpc.py +++ b/google/cloud/retail_v2/services/completion_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -157,6 +158,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py b/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py index 2c9f3e06..249b3223 100644 --- a/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py @@ -106,6 +106,7 @@ def __init__( quota_project_id=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. @@ -202,6 +203,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2/services/prediction_service/client.py b/google/cloud/retail_v2/services/prediction_service/client.py index 6b25b7dc..d9599a05 100644 --- a/google/cloud/retail_v2/services/prediction_service/client.py +++ b/google/cloud/retail_v2/services/prediction_service/client.py @@ -428,6 +428,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def predict( diff --git a/google/cloud/retail_v2/services/prediction_service/transports/base.py b/google/cloud/retail_v2/services/prediction_service/transports/base.py index a40dfe48..bd2747fb 100644 --- a/google/cloud/retail_v2/services/prediction_service/transports/base.py +++ b/google/cloud/retail_v2/services/prediction_service/transports/base.py @@ -54,6 +54,7 @@ def __init__( 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. @@ -81,11 +82,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -106,6 +102,11 @@ def __init__( 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 ( @@ -118,6 +119,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2/services/prediction_service/transports/grpc.py b/google/cloud/retail_v2/services/prediction_service/transports/grpc.py index ed9592f8..19e31dd2 100644 --- a/google/cloud/retail_v2/services/prediction_service/transports/grpc.py +++ b/google/cloud/retail_v2/services/prediction_service/transports/grpc.py @@ -57,6 +57,7 @@ def __init__( 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. @@ -152,6 +153,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py b/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py index 41a3c6c3..64b78449 100644 --- a/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py @@ -102,6 +102,7 @@ def __init__( quota_project_id=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. @@ -197,6 +198,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2/services/product_service/client.py b/google/cloud/retail_v2/services/product_service/client.py index 49bce788..dba0d9e4 100644 --- a/google/cloud/retail_v2/services/product_service/client.py +++ b/google/cloud/retail_v2/services/product_service/client.py @@ -465,6 +465,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def create_product( diff --git a/google/cloud/retail_v2/services/product_service/transports/base.py b/google/cloud/retail_v2/services/product_service/transports/base.py index 852a714b..4c5e7d4a 100644 --- a/google/cloud/retail_v2/services/product_service/transports/base.py +++ b/google/cloud/retail_v2/services/product_service/transports/base.py @@ -59,6 +59,7 @@ def __init__( 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. @@ -86,11 +87,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -111,6 +107,11 @@ def __init__( 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 ( @@ -123,6 +124,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2/services/product_service/transports/grpc.py b/google/cloud/retail_v2/services/product_service/transports/grpc.py index 18a1234c..464359f2 100644 --- a/google/cloud/retail_v2/services/product_service/transports/grpc.py +++ b/google/cloud/retail_v2/services/product_service/transports/grpc.py @@ -63,6 +63,7 @@ def __init__( 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. @@ -159,6 +160,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py b/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py index 1c9546ca..b0a24e89 100644 --- a/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py @@ -108,6 +108,7 @@ def __init__( quota_project_id=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. @@ -204,6 +205,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2/services/search_service/client.py b/google/cloud/retail_v2/services/search_service/client.py index 2af50bbf..a99fd559 100644 --- a/google/cloud/retail_v2/services/search_service/client.py +++ b/google/cloud/retail_v2/services/search_service/client.py @@ -455,6 +455,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def search( diff --git a/google/cloud/retail_v2/services/search_service/transports/base.py b/google/cloud/retail_v2/services/search_service/transports/base.py index cb5fb798..b196bdb0 100644 --- a/google/cloud/retail_v2/services/search_service/transports/base.py +++ b/google/cloud/retail_v2/services/search_service/transports/base.py @@ -54,6 +54,7 @@ def __init__( 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. @@ -81,11 +82,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -106,6 +102,11 @@ def __init__( 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 ( @@ -118,6 +119,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2/services/search_service/transports/grpc.py b/google/cloud/retail_v2/services/search_service/transports/grpc.py index 152b6801..1ff143ef 100644 --- a/google/cloud/retail_v2/services/search_service/transports/grpc.py +++ b/google/cloud/retail_v2/services/search_service/transports/grpc.py @@ -60,6 +60,7 @@ def __init__( 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. @@ -155,6 +156,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py b/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py index aa590ea7..04e2604a 100644 --- a/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py @@ -105,6 +105,7 @@ def __init__( quota_project_id=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. @@ -200,6 +201,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2/services/user_event_service/client.py b/google/cloud/retail_v2/services/user_event_service/client.py index 84eec3f6..23fa9c67 100644 --- a/google/cloud/retail_v2/services/user_event_service/client.py +++ b/google/cloud/retail_v2/services/user_event_service/client.py @@ -464,6 +464,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def write_user_event( diff --git a/google/cloud/retail_v2/services/user_event_service/transports/base.py b/google/cloud/retail_v2/services/user_event_service/transports/base.py index 3bd8b209..afaa18ba 100644 --- a/google/cloud/retail_v2/services/user_event_service/transports/base.py +++ b/google/cloud/retail_v2/services/user_event_service/transports/base.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -88,11 +89,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -113,6 +109,11 @@ def __init__( 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 ( @@ -125,6 +126,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2/services/user_event_service/transports/grpc.py b/google/cloud/retail_v2/services/user_event_service/transports/grpc.py index 12a4bc7c..a31662c7 100644 --- a/google/cloud/retail_v2/services/user_event_service/transports/grpc.py +++ b/google/cloud/retail_v2/services/user_event_service/transports/grpc.py @@ -65,6 +65,7 @@ def __init__( 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. @@ -161,6 +162,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py b/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py index 0c391f22..2b8f35f2 100644 --- a/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py @@ -110,6 +110,7 @@ def __init__( quota_project_id=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. @@ -206,6 +207,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/catalog_service/client.py b/google/cloud/retail_v2alpha/services/catalog_service/client.py index cbf8c743..41d08913 100644 --- a/google/cloud/retail_v2alpha/services/catalog_service/client.py +++ b/google/cloud/retail_v2alpha/services/catalog_service/client.py @@ -498,6 +498,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def list_catalogs( diff --git a/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py b/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py index 493790be..f850ccb4 100644 --- a/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py +++ b/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py @@ -57,6 +57,7 @@ def __init__( 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. @@ -84,11 +85,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -109,6 +105,11 @@ def __init__( 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 ( @@ -121,6 +122,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py b/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py index 85548f4d..4f115280 100644 --- a/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py +++ b/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py @@ -60,6 +60,7 @@ def __init__( 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. @@ -155,6 +156,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py b/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py index 1fe5bcc4..f563e2b6 100644 --- a/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py @@ -105,6 +105,7 @@ def __init__( quota_project_id=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. @@ -200,6 +201,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/completion_service/client.py b/google/cloud/retail_v2alpha/services/completion_service/client.py index e68de1ab..f3806761 100644 --- a/google/cloud/retail_v2alpha/services/completion_service/client.py +++ b/google/cloud/retail_v2alpha/services/completion_service/client.py @@ -431,6 +431,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def complete_query( diff --git a/google/cloud/retail_v2alpha/services/completion_service/transports/base.py b/google/cloud/retail_v2alpha/services/completion_service/transports/base.py index cfd2a4db..afc278f1 100644 --- a/google/cloud/retail_v2alpha/services/completion_service/transports/base.py +++ b/google/cloud/retail_v2alpha/services/completion_service/transports/base.py @@ -55,6 +55,7 @@ def __init__( 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. @@ -82,11 +83,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -107,6 +103,11 @@ def __init__( 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 ( @@ -119,6 +120,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py b/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py index 49d17e5b..5d13d20d 100644 --- a/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py +++ b/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -157,6 +158,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py b/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py index 4cf5f150..e067f73e 100644 --- a/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py @@ -106,6 +106,7 @@ def __init__( quota_project_id=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. @@ -202,6 +203,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/control_service/client.py b/google/cloud/retail_v2alpha/services/control_service/client.py index d6cbb723..04a787e4 100644 --- a/google/cloud/retail_v2alpha/services/control_service/client.py +++ b/google/cloud/retail_v2alpha/services/control_service/client.py @@ -454,6 +454,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def create_control( diff --git a/google/cloud/retail_v2alpha/services/control_service/transports/base.py b/google/cloud/retail_v2alpha/services/control_service/transports/base.py index 8cf805fa..b064b382 100644 --- a/google/cloud/retail_v2alpha/services/control_service/transports/base.py +++ b/google/cloud/retail_v2alpha/services/control_service/transports/base.py @@ -57,6 +57,7 @@ def __init__( 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. @@ -84,11 +85,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -109,6 +105,11 @@ def __init__( 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 ( @@ -121,6 +122,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py b/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py index b42b1a3b..cf90fc60 100644 --- a/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py +++ b/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py @@ -60,6 +60,7 @@ def __init__( 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. @@ -155,6 +156,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py b/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py index 4f63553b..4ec82bd9 100644 --- a/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py @@ -105,6 +105,7 @@ def __init__( quota_project_id=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. @@ -200,6 +201,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/prediction_service/client.py b/google/cloud/retail_v2alpha/services/prediction_service/client.py index 94a14e41..c1f0609f 100644 --- a/google/cloud/retail_v2alpha/services/prediction_service/client.py +++ b/google/cloud/retail_v2alpha/services/prediction_service/client.py @@ -428,6 +428,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def predict( diff --git a/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py b/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py index 8388a449..cf764606 100644 --- a/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py +++ b/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py @@ -54,6 +54,7 @@ def __init__( 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. @@ -81,11 +82,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -106,6 +102,11 @@ def __init__( 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 ( @@ -118,6 +119,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py b/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py index 04ede321..036ca6c5 100644 --- a/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py +++ b/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py @@ -57,6 +57,7 @@ def __init__( 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. @@ -152,6 +153,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py b/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py index b43274ff..228e9217 100644 --- a/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py @@ -102,6 +102,7 @@ def __init__( quota_project_id=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. @@ -197,6 +198,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/product_service/client.py b/google/cloud/retail_v2alpha/services/product_service/client.py index fe3b725e..2a0625b5 100644 --- a/google/cloud/retail_v2alpha/services/product_service/client.py +++ b/google/cloud/retail_v2alpha/services/product_service/client.py @@ -465,6 +465,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def create_product( diff --git a/google/cloud/retail_v2alpha/services/product_service/transports/base.py b/google/cloud/retail_v2alpha/services/product_service/transports/base.py index ecc6e921..ad656a6a 100644 --- a/google/cloud/retail_v2alpha/services/product_service/transports/base.py +++ b/google/cloud/retail_v2alpha/services/product_service/transports/base.py @@ -59,6 +59,7 @@ def __init__( 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. @@ -86,11 +87,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -111,6 +107,11 @@ def __init__( 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 ( @@ -123,6 +124,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py b/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py index 2b188dee..3839c911 100644 --- a/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py +++ b/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py @@ -63,6 +63,7 @@ def __init__( 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. @@ -159,6 +160,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py b/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py index 01a9347a..32ae3981 100644 --- a/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py @@ -108,6 +108,7 @@ def __init__( quota_project_id=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. @@ -204,6 +205,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/search_service/client.py b/google/cloud/retail_v2alpha/services/search_service/client.py index db33e977..69a32b77 100644 --- a/google/cloud/retail_v2alpha/services/search_service/client.py +++ b/google/cloud/retail_v2alpha/services/search_service/client.py @@ -455,6 +455,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def search( diff --git a/google/cloud/retail_v2alpha/services/search_service/transports/base.py b/google/cloud/retail_v2alpha/services/search_service/transports/base.py index 2ae848f3..5c58a0ed 100644 --- a/google/cloud/retail_v2alpha/services/search_service/transports/base.py +++ b/google/cloud/retail_v2alpha/services/search_service/transports/base.py @@ -54,6 +54,7 @@ def __init__( 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. @@ -81,11 +82,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -106,6 +102,11 @@ def __init__( 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 ( @@ -118,6 +119,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py b/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py index d29bdba7..c80255b6 100644 --- a/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py +++ b/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py @@ -60,6 +60,7 @@ def __init__( 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. @@ -155,6 +156,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py b/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py index d6c182a7..bc41f156 100644 --- a/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py @@ -105,6 +105,7 @@ def __init__( quota_project_id=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. @@ -200,6 +201,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/serving_config_service/client.py b/google/cloud/retail_v2alpha/services/serving_config_service/client.py index d6169cbc..453bc59d 100644 --- a/google/cloud/retail_v2alpha/services/serving_config_service/client.py +++ b/google/cloud/retail_v2alpha/services/serving_config_service/client.py @@ -454,6 +454,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def create_serving_config( diff --git a/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py b/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py index b7398a03..51463656 100644 --- a/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py +++ b/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py @@ -57,6 +57,7 @@ def __init__( 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. @@ -84,11 +85,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -109,6 +105,11 @@ def __init__( 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 ( @@ -121,6 +122,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py b/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py index 28c2de96..680219d2 100644 --- a/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py +++ b/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py @@ -60,6 +60,7 @@ def __init__( 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. @@ -155,6 +156,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py b/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py index 296f675c..227a2a78 100644 --- a/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py @@ -105,6 +105,7 @@ def __init__( quota_project_id=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. @@ -200,6 +201,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/user_event_service/client.py b/google/cloud/retail_v2alpha/services/user_event_service/client.py index 54d4a8e2..63a2a23f 100644 --- a/google/cloud/retail_v2alpha/services/user_event_service/client.py +++ b/google/cloud/retail_v2alpha/services/user_event_service/client.py @@ -464,6 +464,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def write_user_event( diff --git a/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py b/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py index 6beb6990..91870745 100644 --- a/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py +++ b/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -88,11 +89,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -113,6 +109,11 @@ def __init__( 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 ( @@ -125,6 +126,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py b/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py index e91069b1..6e968f87 100644 --- a/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py +++ b/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py @@ -65,6 +65,7 @@ def __init__( 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. @@ -161,6 +162,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py b/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py index c6c472af..cbe77cb2 100644 --- a/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py @@ -110,6 +110,7 @@ def __init__( quota_project_id=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. @@ -206,6 +207,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/catalog_service/client.py b/google/cloud/retail_v2beta/services/catalog_service/client.py index 731c269b..fcf72475 100644 --- a/google/cloud/retail_v2beta/services/catalog_service/client.py +++ b/google/cloud/retail_v2beta/services/catalog_service/client.py @@ -498,6 +498,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def list_catalogs( diff --git a/google/cloud/retail_v2beta/services/catalog_service/transports/base.py b/google/cloud/retail_v2beta/services/catalog_service/transports/base.py index cbb3b940..fb3e7748 100644 --- a/google/cloud/retail_v2beta/services/catalog_service/transports/base.py +++ b/google/cloud/retail_v2beta/services/catalog_service/transports/base.py @@ -57,6 +57,7 @@ def __init__( 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. @@ -84,11 +85,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -109,6 +105,11 @@ def __init__( 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 ( @@ -121,6 +122,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py b/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py index 14904384..bb8d7233 100644 --- a/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py +++ b/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py @@ -60,6 +60,7 @@ def __init__( 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. @@ -155,6 +156,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py b/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py index 7bf56661..80ef39d6 100644 --- a/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py @@ -105,6 +105,7 @@ def __init__( quota_project_id=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. @@ -200,6 +201,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/completion_service/client.py b/google/cloud/retail_v2beta/services/completion_service/client.py index 0c7e8ab1..564d7a01 100644 --- a/google/cloud/retail_v2beta/services/completion_service/client.py +++ b/google/cloud/retail_v2beta/services/completion_service/client.py @@ -431,6 +431,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def complete_query( diff --git a/google/cloud/retail_v2beta/services/completion_service/transports/base.py b/google/cloud/retail_v2beta/services/completion_service/transports/base.py index 7f9d8fca..9f89d658 100644 --- a/google/cloud/retail_v2beta/services/completion_service/transports/base.py +++ b/google/cloud/retail_v2beta/services/completion_service/transports/base.py @@ -55,6 +55,7 @@ def __init__( 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. @@ -82,11 +83,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -107,6 +103,11 @@ def __init__( 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 ( @@ -119,6 +120,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py b/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py index dee73567..1c52e57d 100644 --- a/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py +++ b/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -157,6 +158,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py b/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py index b60c251b..73b2f5bc 100644 --- a/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py @@ -106,6 +106,7 @@ def __init__( quota_project_id=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. @@ -202,6 +203,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/control_service/client.py b/google/cloud/retail_v2beta/services/control_service/client.py index d5f16c0a..1f13cd70 100644 --- a/google/cloud/retail_v2beta/services/control_service/client.py +++ b/google/cloud/retail_v2beta/services/control_service/client.py @@ -454,6 +454,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def create_control( diff --git a/google/cloud/retail_v2beta/services/control_service/transports/base.py b/google/cloud/retail_v2beta/services/control_service/transports/base.py index 02b0af96..583115d7 100644 --- a/google/cloud/retail_v2beta/services/control_service/transports/base.py +++ b/google/cloud/retail_v2beta/services/control_service/transports/base.py @@ -57,6 +57,7 @@ def __init__( 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. @@ -84,11 +85,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -109,6 +105,11 @@ def __init__( 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 ( @@ -121,6 +122,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2beta/services/control_service/transports/grpc.py b/google/cloud/retail_v2beta/services/control_service/transports/grpc.py index e4c08927..e6a99d24 100644 --- a/google/cloud/retail_v2beta/services/control_service/transports/grpc.py +++ b/google/cloud/retail_v2beta/services/control_service/transports/grpc.py @@ -60,6 +60,7 @@ def __init__( 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. @@ -155,6 +156,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py b/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py index 043d7c08..0433ade3 100644 --- a/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py @@ -105,6 +105,7 @@ def __init__( quota_project_id=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. @@ -200,6 +201,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/prediction_service/client.py b/google/cloud/retail_v2beta/services/prediction_service/client.py index 6f96175f..12fc20a0 100644 --- a/google/cloud/retail_v2beta/services/prediction_service/client.py +++ b/google/cloud/retail_v2beta/services/prediction_service/client.py @@ -428,6 +428,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def predict( diff --git a/google/cloud/retail_v2beta/services/prediction_service/transports/base.py b/google/cloud/retail_v2beta/services/prediction_service/transports/base.py index a86552da..3c7d19c8 100644 --- a/google/cloud/retail_v2beta/services/prediction_service/transports/base.py +++ b/google/cloud/retail_v2beta/services/prediction_service/transports/base.py @@ -54,6 +54,7 @@ def __init__( 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. @@ -81,11 +82,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -106,6 +102,11 @@ def __init__( 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 ( @@ -118,6 +119,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py b/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py index 5f36a999..904cb51b 100644 --- a/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py +++ b/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py @@ -57,6 +57,7 @@ def __init__( 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. @@ -152,6 +153,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py b/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py index ada39c3c..64626eed 100644 --- a/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py @@ -102,6 +102,7 @@ def __init__( quota_project_id=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. @@ -197,6 +198,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/product_service/client.py b/google/cloud/retail_v2beta/services/product_service/client.py index dabc7d86..d6cab145 100644 --- a/google/cloud/retail_v2beta/services/product_service/client.py +++ b/google/cloud/retail_v2beta/services/product_service/client.py @@ -465,6 +465,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def create_product( diff --git a/google/cloud/retail_v2beta/services/product_service/transports/base.py b/google/cloud/retail_v2beta/services/product_service/transports/base.py index 46ac2791..bf5c9b07 100644 --- a/google/cloud/retail_v2beta/services/product_service/transports/base.py +++ b/google/cloud/retail_v2beta/services/product_service/transports/base.py @@ -59,6 +59,7 @@ def __init__( 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. @@ -86,11 +87,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -111,6 +107,11 @@ def __init__( 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 ( @@ -123,6 +124,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2beta/services/product_service/transports/grpc.py b/google/cloud/retail_v2beta/services/product_service/transports/grpc.py index afea5e32..d238a07a 100644 --- a/google/cloud/retail_v2beta/services/product_service/transports/grpc.py +++ b/google/cloud/retail_v2beta/services/product_service/transports/grpc.py @@ -63,6 +63,7 @@ def __init__( 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. @@ -159,6 +160,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py b/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py index 8f8db144..3bc0aefa 100644 --- a/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py @@ -108,6 +108,7 @@ def __init__( quota_project_id=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. @@ -204,6 +205,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/search_service/client.py b/google/cloud/retail_v2beta/services/search_service/client.py index 7e2c9461..63de7577 100644 --- a/google/cloud/retail_v2beta/services/search_service/client.py +++ b/google/cloud/retail_v2beta/services/search_service/client.py @@ -455,6 +455,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def search( diff --git a/google/cloud/retail_v2beta/services/search_service/transports/base.py b/google/cloud/retail_v2beta/services/search_service/transports/base.py index c44e6d0f..261dfaad 100644 --- a/google/cloud/retail_v2beta/services/search_service/transports/base.py +++ b/google/cloud/retail_v2beta/services/search_service/transports/base.py @@ -54,6 +54,7 @@ def __init__( 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. @@ -81,11 +82,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -106,6 +102,11 @@ def __init__( 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 ( @@ -118,6 +119,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2beta/services/search_service/transports/grpc.py b/google/cloud/retail_v2beta/services/search_service/transports/grpc.py index e9969814..ed77783d 100644 --- a/google/cloud/retail_v2beta/services/search_service/transports/grpc.py +++ b/google/cloud/retail_v2beta/services/search_service/transports/grpc.py @@ -60,6 +60,7 @@ def __init__( 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. @@ -155,6 +156,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py b/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py index c0ed602b..6f55904f 100644 --- a/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py @@ -105,6 +105,7 @@ def __init__( quota_project_id=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. @@ -200,6 +201,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/serving_config_service/client.py b/google/cloud/retail_v2beta/services/serving_config_service/client.py index 4137667f..aa6db776 100644 --- a/google/cloud/retail_v2beta/services/serving_config_service/client.py +++ b/google/cloud/retail_v2beta/services/serving_config_service/client.py @@ -454,6 +454,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def create_serving_config( diff --git a/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py b/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py index 612f99e6..b12471cf 100644 --- a/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py +++ b/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py @@ -57,6 +57,7 @@ def __init__( 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. @@ -84,11 +85,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -109,6 +105,11 @@ def __init__( 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 ( @@ -121,6 +122,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py b/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py index 5bd42490..c6d90fe8 100644 --- a/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py +++ b/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py @@ -60,6 +60,7 @@ def __init__( 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. @@ -155,6 +156,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py b/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py index 245c6561..835da1dc 100644 --- a/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py @@ -105,6 +105,7 @@ def __init__( quota_project_id=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. @@ -200,6 +201,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/user_event_service/client.py b/google/cloud/retail_v2beta/services/user_event_service/client.py index abb51a3d..62799ce6 100644 --- a/google/cloud/retail_v2beta/services/user_event_service/client.py +++ b/google/cloud/retail_v2beta/services/user_event_service/client.py @@ -464,6 +464,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def write_user_event( diff --git a/google/cloud/retail_v2beta/services/user_event_service/transports/base.py b/google/cloud/retail_v2beta/services/user_event_service/transports/base.py index d047d3dc..8431b510 100644 --- a/google/cloud/retail_v2beta/services/user_event_service/transports/base.py +++ b/google/cloud/retail_v2beta/services/user_event_service/transports/base.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -88,11 +89,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -113,6 +109,11 @@ def __init__( 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 ( @@ -125,6 +126,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py b/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py index 5891669f..b2a3c32b 100644 --- a/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py +++ b/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py @@ -65,6 +65,7 @@ def __init__( 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. @@ -161,6 +162,7 @@ def __init__( 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: diff --git a/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py b/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py index 4195b496..dff289fc 100644 --- a/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py +++ b/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py @@ -110,6 +110,7 @@ def __init__( quota_project_id=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. @@ -206,6 +207,7 @@ def __init__( 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: diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc deleted file mode 100644 index a8b114f0..00000000 --- a/owl-bot-staging/v2/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/retail/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2/.flake8 b/owl-bot-staging/v2/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v2/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in deleted file mode 100644 index 985b915c..00000000 --- a/owl-bot-staging/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/retail *.py -recursive-include google/cloud/retail_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst deleted file mode 100644 index cb039760..00000000 --- a/owl-bot-staging/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Retail API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Retail API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py deleted file mode 100644 index 5be9eb4b..00000000 --- a/owl-bot-staging/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-retail documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-retail" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-retail-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-retail.tex", - u"google-cloud-retail Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-retail", - u"Google Cloud Retail Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-retail", - u"google-cloud-retail Documentation", - author, - "google-cloud-retail", - "GAPIC library for Google Cloud Retail API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst deleted file mode 100644 index c70f61bc..00000000 --- a/owl-bot-staging/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - retail_v2/services - retail_v2/types diff --git a/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst b/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst deleted file mode 100644 index 5b7227d9..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CatalogService --------------------------------- - -.. automodule:: google.cloud.retail_v2.services.catalog_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2.services.catalog_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/completion_service.rst b/owl-bot-staging/v2/docs/retail_v2/completion_service.rst deleted file mode 100644 index 551f89ed..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/completion_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CompletionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2.services.completion_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst b/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst deleted file mode 100644 index 12ffb6ee..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -PredictionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2.services.prediction_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/product_service.rst b/owl-bot-staging/v2/docs/retail_v2/product_service.rst deleted file mode 100644 index 0b8fa911..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/product_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ProductService --------------------------------- - -.. automodule:: google.cloud.retail_v2.services.product_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2.services.product_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/search_service.rst b/owl-bot-staging/v2/docs/retail_v2/search_service.rst deleted file mode 100644 index af72819d..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SearchService -------------------------------- - -.. automodule:: google.cloud.retail_v2.services.search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2.services.search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/services.rst b/owl-bot-staging/v2/docs/retail_v2/services.rst deleted file mode 100644 index f86138d7..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/services.rst +++ /dev/null @@ -1,11 +0,0 @@ -Services for Google Cloud Retail v2 API -======================================= -.. toctree:: - :maxdepth: 2 - - catalog_service - completion_service - prediction_service - product_service - search_service - user_event_service diff --git a/owl-bot-staging/v2/docs/retail_v2/types.rst b/owl-bot-staging/v2/docs/retail_v2/types.rst deleted file mode 100644 index 54951beb..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Retail v2 API -==================================== - -.. automodule:: google.cloud.retail_v2.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst b/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst deleted file mode 100644 index 00e214a9..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.retail_v2.services.user_event_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/google/cloud/retail/__init__.py b/owl-bot-staging/v2/google/cloud/retail/__init__.py deleted file mode 100644 index 0d70ed64..00000000 --- a/owl-bot-staging/v2/google/cloud/retail/__init__.py +++ /dev/null @@ -1,193 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.retail_v2.services.catalog_service.client import CatalogServiceClient -from google.cloud.retail_v2.services.catalog_service.async_client import CatalogServiceAsyncClient -from google.cloud.retail_v2.services.completion_service.client import CompletionServiceClient -from google.cloud.retail_v2.services.completion_service.async_client import CompletionServiceAsyncClient -from google.cloud.retail_v2.services.prediction_service.client import PredictionServiceClient -from google.cloud.retail_v2.services.prediction_service.async_client import PredictionServiceAsyncClient -from google.cloud.retail_v2.services.product_service.client import ProductServiceClient -from google.cloud.retail_v2.services.product_service.async_client import ProductServiceAsyncClient -from google.cloud.retail_v2.services.search_service.client import SearchServiceClient -from google.cloud.retail_v2.services.search_service.async_client import SearchServiceAsyncClient -from google.cloud.retail_v2.services.user_event_service.client import UserEventServiceClient -from google.cloud.retail_v2.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.retail_v2.types.catalog import Catalog -from google.cloud.retail_v2.types.catalog import ProductLevelConfig -from google.cloud.retail_v2.types.catalog_service import GetDefaultBranchRequest -from google.cloud.retail_v2.types.catalog_service import GetDefaultBranchResponse -from google.cloud.retail_v2.types.catalog_service import ListCatalogsRequest -from google.cloud.retail_v2.types.catalog_service import ListCatalogsResponse -from google.cloud.retail_v2.types.catalog_service import SetDefaultBranchRequest -from google.cloud.retail_v2.types.catalog_service import UpdateCatalogRequest -from google.cloud.retail_v2.types.common import Audience -from google.cloud.retail_v2.types.common import ColorInfo -from google.cloud.retail_v2.types.common import CustomAttribute -from google.cloud.retail_v2.types.common import FulfillmentInfo -from google.cloud.retail_v2.types.common import Image -from google.cloud.retail_v2.types.common import Interval -from google.cloud.retail_v2.types.common import LocalInventory -from google.cloud.retail_v2.types.common import PriceInfo -from google.cloud.retail_v2.types.common import Rating -from google.cloud.retail_v2.types.common import UserInfo -from google.cloud.retail_v2.types.completion_service import CompleteQueryRequest -from google.cloud.retail_v2.types.completion_service import CompleteQueryResponse -from google.cloud.retail_v2.types.import_config import BigQuerySource -from google.cloud.retail_v2.types.import_config import CompletionDataInputConfig -from google.cloud.retail_v2.types.import_config import GcsSource -from google.cloud.retail_v2.types.import_config import ImportCompletionDataRequest -from google.cloud.retail_v2.types.import_config import ImportCompletionDataResponse -from google.cloud.retail_v2.types.import_config import ImportErrorsConfig -from google.cloud.retail_v2.types.import_config import ImportMetadata -from google.cloud.retail_v2.types.import_config import ImportProductsRequest -from google.cloud.retail_v2.types.import_config import ImportProductsResponse -from google.cloud.retail_v2.types.import_config import ImportUserEventsRequest -from google.cloud.retail_v2.types.import_config import ImportUserEventsResponse -from google.cloud.retail_v2.types.import_config import ProductInlineSource -from google.cloud.retail_v2.types.import_config import ProductInputConfig -from google.cloud.retail_v2.types.import_config import UserEventImportSummary -from google.cloud.retail_v2.types.import_config import UserEventInlineSource -from google.cloud.retail_v2.types.import_config import UserEventInputConfig -from google.cloud.retail_v2.types.prediction_service import PredictRequest -from google.cloud.retail_v2.types.prediction_service import PredictResponse -from google.cloud.retail_v2.types.product import Product -from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesMetadata -from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesRequest -from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesResponse -from google.cloud.retail_v2.types.product_service import AddLocalInventoriesMetadata -from google.cloud.retail_v2.types.product_service import AddLocalInventoriesRequest -from google.cloud.retail_v2.types.product_service import AddLocalInventoriesResponse -from google.cloud.retail_v2.types.product_service import CreateProductRequest -from google.cloud.retail_v2.types.product_service import DeleteProductRequest -from google.cloud.retail_v2.types.product_service import GetProductRequest -from google.cloud.retail_v2.types.product_service import ListProductsRequest -from google.cloud.retail_v2.types.product_service import ListProductsResponse -from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesMetadata -from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesRequest -from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesResponse -from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesMetadata -from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesRequest -from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesResponse -from google.cloud.retail_v2.types.product_service import SetInventoryMetadata -from google.cloud.retail_v2.types.product_service import SetInventoryRequest -from google.cloud.retail_v2.types.product_service import SetInventoryResponse -from google.cloud.retail_v2.types.product_service import UpdateProductRequest -from google.cloud.retail_v2.types.promotion import Promotion -from google.cloud.retail_v2.types.purge_config import PurgeMetadata -from google.cloud.retail_v2.types.purge_config import PurgeUserEventsRequest -from google.cloud.retail_v2.types.purge_config import PurgeUserEventsResponse -from google.cloud.retail_v2.types.search_service import SearchRequest -from google.cloud.retail_v2.types.search_service import SearchResponse -from google.cloud.retail_v2.types.user_event import CompletionDetail -from google.cloud.retail_v2.types.user_event import ProductDetail -from google.cloud.retail_v2.types.user_event import PurchaseTransaction -from google.cloud.retail_v2.types.user_event import UserEvent -from google.cloud.retail_v2.types.user_event_service import CollectUserEventRequest -from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsMetadata -from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsRequest -from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsResponse -from google.cloud.retail_v2.types.user_event_service import WriteUserEventRequest - -__all__ = ('CatalogServiceClient', - 'CatalogServiceAsyncClient', - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', - 'ProductServiceClient', - 'ProductServiceAsyncClient', - 'SearchServiceClient', - 'SearchServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'Catalog', - 'ProductLevelConfig', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'SetDefaultBranchRequest', - 'UpdateCatalogRequest', - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2/google/cloud/retail/py.typed b/owl-bot-staging/v2/google/cloud/retail/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2/google/cloud/retail/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py deleted file mode 100644 index c7f56a8d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.catalog_service import CatalogServiceClient -from .services.catalog_service import CatalogServiceAsyncClient -from .services.completion_service import CompletionServiceClient -from .services.completion_service import CompletionServiceAsyncClient -from .services.prediction_service import PredictionServiceClient -from .services.prediction_service import PredictionServiceAsyncClient -from .services.product_service import ProductServiceClient -from .services.product_service import ProductServiceAsyncClient -from .services.search_service import SearchServiceClient -from .services.search_service import SearchServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.catalog import Catalog -from .types.catalog import ProductLevelConfig -from .types.catalog_service import GetDefaultBranchRequest -from .types.catalog_service import GetDefaultBranchResponse -from .types.catalog_service import ListCatalogsRequest -from .types.catalog_service import ListCatalogsResponse -from .types.catalog_service import SetDefaultBranchRequest -from .types.catalog_service import UpdateCatalogRequest -from .types.common import Audience -from .types.common import ColorInfo -from .types.common import CustomAttribute -from .types.common import FulfillmentInfo -from .types.common import Image -from .types.common import Interval -from .types.common import LocalInventory -from .types.common import PriceInfo -from .types.common import Rating -from .types.common import UserInfo -from .types.completion_service import CompleteQueryRequest -from .types.completion_service import CompleteQueryResponse -from .types.import_config import BigQuerySource -from .types.import_config import CompletionDataInputConfig -from .types.import_config import GcsSource -from .types.import_config import ImportCompletionDataRequest -from .types.import_config import ImportCompletionDataResponse -from .types.import_config import ImportErrorsConfig -from .types.import_config import ImportMetadata -from .types.import_config import ImportProductsRequest -from .types.import_config import ImportProductsResponse -from .types.import_config import ImportUserEventsRequest -from .types.import_config import ImportUserEventsResponse -from .types.import_config import ProductInlineSource -from .types.import_config import ProductInputConfig -from .types.import_config import UserEventImportSummary -from .types.import_config import UserEventInlineSource -from .types.import_config import UserEventInputConfig -from .types.prediction_service import PredictRequest -from .types.prediction_service import PredictResponse -from .types.product import Product -from .types.product_service import AddFulfillmentPlacesMetadata -from .types.product_service import AddFulfillmentPlacesRequest -from .types.product_service import AddFulfillmentPlacesResponse -from .types.product_service import AddLocalInventoriesMetadata -from .types.product_service import AddLocalInventoriesRequest -from .types.product_service import AddLocalInventoriesResponse -from .types.product_service import CreateProductRequest -from .types.product_service import DeleteProductRequest -from .types.product_service import GetProductRequest -from .types.product_service import ListProductsRequest -from .types.product_service import ListProductsResponse -from .types.product_service import RemoveFulfillmentPlacesMetadata -from .types.product_service import RemoveFulfillmentPlacesRequest -from .types.product_service import RemoveFulfillmentPlacesResponse -from .types.product_service import RemoveLocalInventoriesMetadata -from .types.product_service import RemoveLocalInventoriesRequest -from .types.product_service import RemoveLocalInventoriesResponse -from .types.product_service import SetInventoryMetadata -from .types.product_service import SetInventoryRequest -from .types.product_service import SetInventoryResponse -from .types.product_service import UpdateProductRequest -from .types.promotion import Promotion -from .types.purge_config import PurgeMetadata -from .types.purge_config import PurgeUserEventsRequest -from .types.purge_config import PurgeUserEventsResponse -from .types.search_service import SearchRequest -from .types.search_service import SearchResponse -from .types.user_event import CompletionDetail -from .types.user_event import ProductDetail -from .types.user_event import PurchaseTransaction -from .types.user_event import UserEvent -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import RejoinUserEventsMetadata -from .types.user_event_service import RejoinUserEventsRequest -from .types.user_event_service import RejoinUserEventsResponse -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CatalogServiceAsyncClient', - 'CompletionServiceAsyncClient', - 'PredictionServiceAsyncClient', - 'ProductServiceAsyncClient', - 'SearchServiceAsyncClient', - 'UserEventServiceAsyncClient', -'AddFulfillmentPlacesMetadata', -'AddFulfillmentPlacesRequest', -'AddFulfillmentPlacesResponse', -'AddLocalInventoriesMetadata', -'AddLocalInventoriesRequest', -'AddLocalInventoriesResponse', -'Audience', -'BigQuerySource', -'Catalog', -'CatalogServiceClient', -'CollectUserEventRequest', -'ColorInfo', -'CompleteQueryRequest', -'CompleteQueryResponse', -'CompletionDataInputConfig', -'CompletionDetail', -'CompletionServiceClient', -'CreateProductRequest', -'CustomAttribute', -'DeleteProductRequest', -'FulfillmentInfo', -'GcsSource', -'GetDefaultBranchRequest', -'GetDefaultBranchResponse', -'GetProductRequest', -'Image', -'ImportCompletionDataRequest', -'ImportCompletionDataResponse', -'ImportErrorsConfig', -'ImportMetadata', -'ImportProductsRequest', -'ImportProductsResponse', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'Interval', -'ListCatalogsRequest', -'ListCatalogsResponse', -'ListProductsRequest', -'ListProductsResponse', -'LocalInventory', -'PredictRequest', -'PredictResponse', -'PredictionServiceClient', -'PriceInfo', -'Product', -'ProductDetail', -'ProductInlineSource', -'ProductInputConfig', -'ProductLevelConfig', -'ProductServiceClient', -'Promotion', -'PurchaseTransaction', -'PurgeMetadata', -'PurgeUserEventsRequest', -'PurgeUserEventsResponse', -'Rating', -'RejoinUserEventsMetadata', -'RejoinUserEventsRequest', -'RejoinUserEventsResponse', -'RemoveFulfillmentPlacesMetadata', -'RemoveFulfillmentPlacesRequest', -'RemoveFulfillmentPlacesResponse', -'RemoveLocalInventoriesMetadata', -'RemoveLocalInventoriesRequest', -'RemoveLocalInventoriesResponse', -'SearchRequest', -'SearchResponse', -'SearchServiceClient', -'SetDefaultBranchRequest', -'SetInventoryMetadata', -'SetInventoryRequest', -'SetInventoryResponse', -'UpdateCatalogRequest', -'UpdateProductRequest', -'UserEvent', -'UserEventImportSummary', -'UserEventInlineSource', -'UserEventInputConfig', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json deleted file mode 100644 index 9e04aec8..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json +++ /dev/null @@ -1,333 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.retail_v2", - "protoPackage": "google.cloud.retail.v2", - "schema": "1.0", - "services": { - "CatalogService": { - "clients": { - "grpc": { - "libraryClient": "CatalogServiceClient", - "rpcs": { - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CatalogServiceAsyncClient", - "rpcs": { - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - } - } - } - } - }, - "CompletionService": { - "clients": { - "grpc": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CompletionServiceAsyncClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - } - } - }, - "PredictionService": { - "clients": { - "grpc": { - "libraryClient": "PredictionServiceClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PredictionServiceAsyncClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - } - } - }, - "ProductService": { - "clients": { - "grpc": { - "libraryClient": "ProductServiceClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProductServiceAsyncClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - } - } - }, - "SearchService": { - "clients": { - "grpc": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SearchServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/py.typed b/owl-bot-staging/v2/google/cloud/retail_v2/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py deleted file mode 100644 index d276b897..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CatalogServiceClient -from .async_client import CatalogServiceAsyncClient - -__all__ = ( - 'CatalogServiceClient', - 'CatalogServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py deleted file mode 100644 index b0a1b99e..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py +++ /dev/null @@ -1,653 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.services.catalog_service import pagers -from google.cloud.retail_v2.types import catalog -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport -from .client import CatalogServiceClient - - -class CatalogServiceAsyncClient: - """Service for managing catalog configuration.""" - - _client: CatalogServiceClient - - DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(CatalogServiceClient.branch_path) - parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) - catalog_path = staticmethod(CatalogServiceClient.catalog_path) - parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) - common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CatalogServiceClient.common_project_path) - parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) - common_location_path = staticmethod(CatalogServiceClient.common_location_path) - parse_common_location_path = staticmethod(CatalogServiceClient.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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CatalogServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsAsyncPager: - r"""Lists all the [Catalog][google.cloud.retail.v2.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_list_catalogs(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - parent (:class:`str`): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2.Catalog]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.retail_v2.services.catalog_service.pagers.ListCatalogsAsyncPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.ListCatalogsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_catalogs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCatalogsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_update_catalog(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] - method. - catalog (:class:`google.cloud.retail_v2.types.Catalog`): - Required. The [Catalog][google.cloud.retail.v2.Catalog] - to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2.Catalog], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCatalogRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_catalog, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_set_default_branch(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (:class:`str`): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.SetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_get_default_branch(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (:class:`str`): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # 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_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py deleted file mode 100644 index dab9ff8c..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py +++ /dev/null @@ -1,862 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.services.catalog_service import pagers -from google.cloud.retail_v2.types import catalog -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CatalogServiceGrpcTransport -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -class CatalogServiceClientMeta(type): - """Metaclass for the CatalogService 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[CatalogServiceTransport]] - _transport_registry["grpc"] = CatalogServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CatalogServiceTransport]: - """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): - """Service for managing catalog configuration.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CatalogServiceClient: 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: - CatalogServiceClient: 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) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CatalogServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CatalogServiceTransport): - # transport is a CatalogServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsPager: - r"""Lists all the [Catalog][google.cloud.retail.v2.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_list_catalogs(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2.Catalog]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.retail_v2.services.catalog_service.pagers.ListCatalogsPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ListCatalogsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ListCatalogsRequest): - request = catalog_service.ListCatalogsRequest(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_catalogs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCatalogsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_update_catalog(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] - method. - catalog (google.cloud.retail_v2.types.Catalog): - Required. The [Catalog][google.cloud.retail.v2.Catalog] - to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2.Catalog], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCatalogRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCatalogRequest): - request = catalog_service.UpdateCatalogRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - 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_catalog] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_set_default_branch(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.SetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.SetDefaultBranchRequest): - request = catalog_service.SetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_get_default_branch(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetDefaultBranchRequest): - request = catalog_service.GetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py deleted file mode 100644 index 11dd0677..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2.types import catalog -from google.cloud.retail_v2.types import catalog_service - - -class ListCatalogsPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.ListCatalogsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.ListCatalogsResponse` - 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[..., catalog_service.ListCatalogsResponse], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - for page in self.pages: - yield from page.catalogs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCatalogsAsyncPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.ListCatalogsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.ListCatalogsResponse` - 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[catalog_service.ListCatalogsResponse]], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - async def async_generator(): - async for page in self.pages: - for response in page.catalogs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py deleted file mode 100644 index 0cffa336..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CatalogServiceTransport -from .grpc import CatalogServiceGrpcTransport -from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] -_transport_registry['grpc'] = CatalogServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport - -__all__ = ( - 'CatalogServiceTransport', - 'CatalogServiceGrpcTransport', - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py deleted file mode 100644 index 661247c1..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py +++ /dev/null @@ -1,198 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CatalogServiceTransport(abc.ABC): - """Abstract transport class for CatalogService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_catalogs: gapic_v1.method.wrap_method( - self.list_catalogs, - default_timeout=None, - client_info=client_info, - ), - self.update_catalog: gapic_v1.method.wrap_method( - self.update_catalog, - default_timeout=None, - client_info=client_info, - ), - self.set_default_branch: gapic_v1.method.wrap_method( - self.set_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_default_branch: gapic_v1.method.wrap_method( - self.get_default_branch, - 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Union[ - catalog_service.ListCatalogsResponse, - Awaitable[catalog_service.ListCatalogsResponse] - ]]: - raise NotImplementedError() - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Union[ - gcr_catalog.Catalog, - Awaitable[gcr_catalog.Catalog] - ]]: - raise NotImplementedError() - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Union[ - catalog_service.GetDefaultBranchResponse, - Awaitable[catalog_service.GetDefaultBranchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CatalogServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py deleted file mode 100644 index 17492b4a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py +++ /dev/null @@ -1,381 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO - - -class CatalogServiceGrpcTransport(CatalogServiceTransport): - """gRPC backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - catalog_service.ListCatalogsResponse]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - ~.ListCatalogsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - gcr_catalog.Catalog]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - ~.Catalog]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - empty_pb2.Empty]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - ~.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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - catalog_service.GetDefaultBranchResponse]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - ~.GetDefaultBranchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CatalogServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py deleted file mode 100644 index dfc3cd7b..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,380 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CatalogServiceGrpcTransport - - -class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): - """gRPC AsyncIO backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Awaitable[catalog_service.ListCatalogsResponse]]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - Awaitable[~.ListCatalogsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Awaitable[gcr_catalog.Catalog]]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - Awaitable[~.Catalog]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - 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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Awaitable[catalog_service.GetDefaultBranchResponse]]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - Awaitable[~.GetDefaultBranchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py deleted file mode 100644 index b8af95bd..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CompletionServiceClient -from .async_client import CompletionServiceAsyncClient - -__all__ = ( - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py deleted file mode 100644 index 9e5d6432..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py +++ /dev/null @@ -1,391 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .client import CompletionServiceClient - - -class CompletionServiceAsyncClient: - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: CompletionServiceClient - - DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(CompletionServiceClient.catalog_path) - parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) - common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CompletionServiceClient.common_project_path) - parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) - common_location_path = staticmethod(CompletionServiceClient.common_location_path) - parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CompletionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_complete_query(): - # Create a client - client = retail_v2.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.complete_query, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_import_completion_data(): - # Create a client - client = retail_v2.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. - 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. - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_completion_data, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py deleted file mode 100644 index ca5bb55d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py +++ /dev/null @@ -1,593 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CompletionServiceGrpcTransport -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -class CompletionServiceClientMeta(type): - """Metaclass for the CompletionService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] - _transport_registry["grpc"] = CompletionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CompletionServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class CompletionServiceClient(metaclass=CompletionServiceClientMeta): - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CompletionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CompletionServiceTransport): - # transport is a CompletionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_complete_query(): - # Create a client - client = retail_v2.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a completion_service.CompleteQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, completion_service.CompleteQueryRequest): - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_import_completion_data(): - # Create a client - client = retail_v2.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. - 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. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportCompletionDataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportCompletionDataRequest): - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_completion_data] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py deleted file mode 100644 index a0c9542f..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CompletionServiceTransport -from .grpc import CompletionServiceGrpcTransport -from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] -_transport_registry['grpc'] = CompletionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport - -__all__ = ( - 'CompletionServiceTransport', - 'CompletionServiceGrpcTransport', - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py deleted file mode 100644 index 7b2cb516..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py +++ /dev/null @@ -1,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CompletionServiceTransport(abc.ABC): - """Abstract transport class for CompletionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.complete_query: gapic_v1.method.wrap_method( - self.complete_query, - default_timeout=None, - client_info=client_info, - ), - self.import_completion_data: gapic_v1.method.wrap_method( - self.import_completion_data, - 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Union[ - completion_service.CompleteQueryResponse, - Awaitable[completion_service.CompleteQueryResponse] - ]]: - raise NotImplementedError() - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CompletionServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py deleted file mode 100644 index 44cb929b..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py +++ /dev/null @@ -1,325 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO - - -class CompletionServiceGrpcTransport(CompletionServiceTransport): - """gRPC backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - ~.CompleteQueryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - operations_pb2.Operation]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CompletionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py deleted file mode 100644 index f7131541..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,324 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CompletionServiceGrpcTransport - - -class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): - """gRPC AsyncIO backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Awaitable[completion_service.CompleteQueryResponse]]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - Awaitable[~.CompleteQueryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - 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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py deleted file mode 100644 index 7c079c80..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import PredictionServiceClient -from .async_client import PredictionServiceAsyncClient - -__all__ = ( - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py deleted file mode 100644 index ae9f9c86..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py +++ /dev/null @@ -1,279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport -from .client import PredictionServiceClient - - -class PredictionServiceAsyncClient: - """Service for making recommendation prediction.""" - - _client: PredictionServiceClient - - DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT - - product_path = staticmethod(PredictionServiceClient.product_path) - parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) - common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(PredictionServiceClient.common_project_path) - parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) - common_location_path = staticmethod(PredictionServiceClient.common_location_path) - parse_common_location_path = staticmethod(PredictionServiceClient.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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PredictionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_predict(): - # Create a client - client = retail_v2.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - request = prediction_service.PredictRequest(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.predict, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py deleted file mode 100644 index 67a94f53..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py +++ /dev/null @@ -1,480 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PredictionServiceGrpcTransport -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -class PredictionServiceClientMeta(type): - """Metaclass for the PredictionService 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[PredictionServiceTransport]] - _transport_registry["grpc"] = PredictionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PredictionServiceTransport]: - """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): - """Service for making recommendation prediction.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PredictionServiceClient: 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: - PredictionServiceClient: 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) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, PredictionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, PredictionServiceTransport): - # transport is a PredictionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_predict(): - # Create a client - client = retail_v2.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a prediction_service.PredictRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_service.PredictRequest): - request = prediction_service.PredictRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.predict] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py deleted file mode 100644 index bb65c664..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PredictionServiceTransport -from .grpc import PredictionServiceGrpcTransport -from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] -_transport_registry['grpc'] = PredictionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport - -__all__ = ( - 'PredictionServiceTransport', - 'PredictionServiceGrpcTransport', - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py deleted file mode 100644 index f3b77c06..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import prediction_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PredictionServiceTransport(abc.ABC): - """Abstract transport class for PredictionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.predict: gapic_v1.method.wrap_method( - self.predict, - 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - Union[ - prediction_service.PredictResponse, - Awaitable[prediction_service.PredictResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PredictionServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py deleted file mode 100644 index 0e86800c..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py +++ /dev/null @@ -1,264 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO - - -class PredictionServiceGrpcTransport(PredictionServiceTransport): - """gRPC backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - prediction_service.PredictResponse]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - ~.PredictResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PredictionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py deleted file mode 100644 index 472e079a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import PredictionServiceGrpcTransport - - -class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): - """gRPC AsyncIO backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def predict(self) -> Callable[ - [prediction_service.PredictRequest], - Awaitable[prediction_service.PredictResponse]]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - Awaitable[~.PredictResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py deleted file mode 100644 index 0fa6330a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ProductServiceClient -from .async_client import ProductServiceAsyncClient - -__all__ = ( - 'ProductServiceClient', - 'ProductServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py deleted file mode 100644 index db29be72..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py +++ /dev/null @@ -1,1701 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.services.product_service import pagers -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.cloud.retail_v2.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport -from .client import ProductServiceClient - - -class ProductServiceAsyncClient: - """Service for ingesting [Product][google.cloud.retail.v2.Product] - information of the customer's website. - """ - - _client: ProductServiceClient - - DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(ProductServiceClient.branch_path) - parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) - product_path = staticmethod(ProductServiceClient.product_path) - parse_product_path = staticmethod(ProductServiceClient.parse_product_path) - common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProductServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProductServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ProductServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) - common_location_path = staticmethod(ProductServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProductServiceClient.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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ProductServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ProductServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_create_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (:class:`str`): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (:class:`google.cloud.retail_v2.types.Product`): - Required. The [Product][google.cloud.retail.v2.Product] - to create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (:class:`str`): - Required. The ID to use for the - [Product][google.cloud.retail.v2.Product], which will - become the final component of the - [Product.name][google.cloud.retail.v2.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2.Product]s with the same - [parent][google.cloud.retail.v2.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.CreateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_get_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested - [Product][google.cloud.retail.v2.Product] 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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.GetProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsAsyncPager: - r"""Gets a list of [Product][google.cloud.retail.v2.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_list_products(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - parent (:class:`str`): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2.Product]s under this - branch, regardless of whether or not this branch exists, - a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.services.product_service.pagers.ListProductsAsyncPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.ListProductsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_products, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProductsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_update_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (:class:`google.cloud.retail_v2.types.Product`): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2.Product] to update. The - immutable and output only fields are NOT supported. If - not set, all supported fields (the fields that are - neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - The attribute key can be updated by setting the mask - path as "attributes.${key_name}". If a key name is - present in the mask but not in the patching product from - the request, this key will be deleted after the update. - - 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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.UpdateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_delete_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2.Product] to delete - can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] with more than - one - [variants][google.cloud.retail.v2.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.DeleteProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2.Product]s. - - Request processing may be synchronous. Non-existing items are - created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2.Product]s to be successfully - updated. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_import_products(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2.Product] while respecting the - last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_set_inventory(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2.Product() - inventory.title = "title_value" - - request = retail_v2.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (:class:`google.cloud.retail_v2.types.Product`): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product] named in - [Product.name][google.cloud.retail.v2.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.SetInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_inventory, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - async def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places, - while respecting the last update timestamps of each inventory - field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_add_local_inventories(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.AddLocalInventoriesResponse` Response of the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - API. Currently empty because there is no meaningful - response populated from the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places at - a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_remove_local_inventories(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py deleted file mode 100644 index dc6ce5c9..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py +++ /dev/null @@ -1,1904 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.services.product_service import pagers -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.cloud.retail_v2.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProductServiceGrpcTransport -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -class ProductServiceClientMeta(type): - """Metaclass for the ProductService 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[ProductServiceTransport]] - _transport_registry["grpc"] = ProductServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ProductServiceTransport]: - """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 ProductServiceClient(metaclass=ProductServiceClientMeta): - """Service for ingesting [Product][google.cloud.retail.v2.Product] - information of the customer's website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProductServiceClient: 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: - ProductServiceClient: 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) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProductServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ProductServiceTransport): - # transport is a ProductServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_create_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (google.cloud.retail_v2.types.Product): - Required. The [Product][google.cloud.retail.v2.Product] - to create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2.Product], which will - become the final component of the - [Product.name][google.cloud.retail.v2.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2.Product]s with the same - [parent][google.cloud.retail.v2.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.CreateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.CreateProductRequest): - request = product_service.CreateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_get_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested - [Product][google.cloud.retail.v2.Product] 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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.GetProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.GetProductRequest): - request = product_service.GetProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsPager: - r"""Gets a list of [Product][google.cloud.retail.v2.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_list_products(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2.Product]s under this - branch, regardless of whether or not this branch exists, - a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.services.product_service.pagers.ListProductsPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.ListProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.ListProductsRequest): - request = product_service.ListProductsRequest(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_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProductsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_update_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (google.cloud.retail_v2.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2.Product] to update. The - immutable and output only fields are NOT supported. If - not set, all supported fields (the fields that are - neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - The attribute key can be updated by setting the mask - path as "attributes.${key_name}". If a key name is - present in the mask but not in the patching product from - the request, this key will be deleted after the update. - - 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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.UpdateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.UpdateProductRequest): - request = product_service.UpdateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - 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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_delete_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2.Product] to delete - can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] with more than - one - [variants][google.cloud.retail.v2.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.DeleteProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.DeleteProductRequest): - request = product_service.DeleteProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2.Product]s. - - Request processing may be synchronous. Non-existing items are - created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2.Product]s to be successfully - updated. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_import_products(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportProductsRequest): - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2.Product] while respecting the - last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_set_inventory(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2.Product() - inventory.title = "title_value" - - request = retail_v2.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (google.cloud.retail_v2.types.Product): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product] named in - [Product.name][google.cloud.retail.v2.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.SetInventoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.SetInventoryRequest): - request = product_service.SetInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_add_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddFulfillmentPlacesRequest): - request = product_service.AddFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): - request = product_service.RemoveFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places, - while respecting the last update timestamps of each inventory - field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_add_local_inventories(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.AddLocalInventoriesResponse` Response of the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - API. Currently empty because there is no meaningful - response populated from the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddLocalInventoriesRequest): - request = product_service.AddLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places at - a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_remove_local_inventories(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveLocalInventoriesRequest): - request = product_service.RemoveLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py deleted file mode 100644 index f9e49958..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product_service - - -class ListProductsPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.ListProductsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.ListProductsResponse` - 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[..., product_service.ListProductsResponse], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[product_service.ListProductsResponse]: - 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[product.Product]: - for page in self.pages: - yield from page.products - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProductsAsyncPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.ListProductsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.ListProductsResponse` - 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[product_service.ListProductsResponse]], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: - 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[product.Product]: - async def async_generator(): - async for page in self.pages: - for response in page.products: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py deleted file mode 100644 index db824dec..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ProductServiceTransport -from .grpc import ProductServiceGrpcTransport -from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] -_transport_registry['grpc'] = ProductServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport - -__all__ = ( - 'ProductServiceTransport', - 'ProductServiceGrpcTransport', - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py deleted file mode 100644 index e3de653c..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py +++ /dev/null @@ -1,312 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ProductServiceTransport(abc.ABC): - """Abstract transport class for ProductService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_product: gapic_v1.method.wrap_method( - self.create_product, - default_timeout=None, - client_info=client_info, - ), - self.get_product: gapic_v1.method.wrap_method( - self.get_product, - default_timeout=None, - client_info=client_info, - ), - self.list_products: gapic_v1.method.wrap_method( - self.list_products, - default_timeout=None, - client_info=client_info, - ), - self.update_product: gapic_v1.method.wrap_method( - self.update_product, - default_timeout=None, - client_info=client_info, - ), - self.delete_product: gapic_v1.method.wrap_method( - self.delete_product, - default_timeout=None, - client_info=client_info, - ), - self.import_products: gapic_v1.method.wrap_method( - self.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.set_inventory: gapic_v1.method.wrap_method( - self.set_inventory, - default_timeout=None, - client_info=client_info, - ), - self.add_fulfillment_places: gapic_v1.method.wrap_method( - self.add_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.remove_fulfillment_places: gapic_v1.method.wrap_method( - self.remove_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.add_local_inventories: gapic_v1.method.wrap_method( - self.add_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.remove_local_inventories: gapic_v1.method.wrap_method( - self.remove_local_inventories, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Union[ - product.Product, - Awaitable[product.Product] - ]]: - raise NotImplementedError() - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Union[ - product_service.ListProductsResponse, - Awaitable[product_service.ListProductsResponse] - ]]: - raise NotImplementedError() - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ProductServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py deleted file mode 100644 index 108f3215..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py +++ /dev/null @@ -1,680 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO - - -class ProductServiceGrpcTransport(ProductServiceTransport): - """gRPC backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - gcr_product.Product]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.CreateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - product.Product]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.GetProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - product_service.ListProductsResponse]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - ~.ListProductsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - gcr_product.Product]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - ~.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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2.Product]s. - - Request processing may be synchronous. Non-existing items are - created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2.Product]s to be successfully - updated. - - Returns: - Callable[[~.ImportProductsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - operations_pb2.Operation]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2.Product] while respecting the - last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places, - while respecting the last update timestamps of each inventory - field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places at - a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProductServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py deleted file mode 100644 index 1d4ccc2d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,679 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ProductServiceGrpcTransport - - -class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): - """gRPC AsyncIO backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.CreateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Awaitable[product.Product]]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.GetProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Awaitable[product_service.ListProductsResponse]]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - Awaitable[~.ListProductsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - 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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2.Product]s. - - Request processing may be synchronous. Non-existing items are - created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2.Product]s to be successfully - updated. - - Returns: - Callable[[~.ImportProductsRequest], - 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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2.Product] while respecting the - last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - 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 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - 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 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places, - while respecting the last update timestamps of each inventory - field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - 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 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places at - a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - 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 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py deleted file mode 100644 index 2f63fc22..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SearchServiceClient -from .async_client import SearchServiceAsyncClient - -__all__ = ( - 'SearchServiceClient', - 'SearchServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py deleted file mode 100644 index c48710b8..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.services.search_service import pagers -from google.cloud.retail_v2.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .client import SearchServiceClient - - -class SearchServiceAsyncClient: - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: SearchServiceClient - - DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(SearchServiceClient.branch_path) - parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) - product_path = staticmethod(SearchServiceClient.product_path) - parse_product_path = staticmethod(SearchServiceClient.parse_product_path) - common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(SearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SearchServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAsyncPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_search(): - # Create a client - client = retail_v2.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.services.search_service.pagers.SearchAsyncPager: - Response message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py deleted file mode 100644 index 0072e3b0..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py +++ /dev/null @@ -1,513 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.services.search_service import pagers -from google.cloud.retail_v2.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SearchServiceGrpcTransport -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -class SearchServiceClientMeta(type): - """Metaclass for the SearchService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] - _transport_registry["grpc"] = SearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SearchServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SearchServiceClient(metaclass=SearchServiceClientMeta): - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SearchServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SearchServiceTransport): - # transport is a SearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_search(): - # Create a client - client = retail_v2.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.services.search_service.pagers.SearchPager: - Response message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a search_service.SearchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, search_service.SearchRequest): - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py deleted file mode 100644 index 524810e2..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2.types import search_service - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., search_service.SearchResponse], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[search_service.SearchResponse]], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py deleted file mode 100644 index 7917cd1d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SearchServiceTransport -from .grpc import SearchServiceGrpcTransport -from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] -_transport_registry['grpc'] = SearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport - -__all__ = ( - 'SearchServiceTransport', - 'SearchServiceGrpcTransport', - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py deleted file mode 100644 index 541055f5..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import search_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class SearchServiceTransport(abc.ABC): - """Abstract transport class for SearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search: gapic_v1.method.wrap_method( - self.search, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Union[ - search_service.SearchResponse, - Awaitable[search_service.SearchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SearchServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py deleted file mode 100644 index ee53c769..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py +++ /dev/null @@ -1,270 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO - - -class SearchServiceGrpcTransport(SearchServiceTransport): - """gRPC backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py deleted file mode 100644 index 6c6e5f29..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SearchServiceGrpcTransport - - -class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): - """gRPC AsyncIO backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Awaitable[search_service.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py deleted file mode 100644 index 5f5171c1..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py deleted file mode 100644 index 99002514..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py +++ /dev/null @@ -1,730 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on the customer - website. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(UserEventServiceClient.catalog_path) - parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) - product_path = staticmethod(UserEventServiceClient.product_path) - parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_write_user_event(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_collect_user_event(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_purge_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_import_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_rejoin_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py deleted file mode 100644 index cd1d35d8..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py +++ /dev/null @@ -1,930 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[UserEventServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on the customer - website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_write_user_event(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_collect_user_event(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_purge_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeUserEventsRequest): - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_import_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportUserEventsRequest): - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_rejoin_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.RejoinUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.RejoinUserEventsRequest): - request = user_event_service.RejoinUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py deleted file mode 100644 index f53ee5d7..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py deleted file mode 100644 index 661a2d50..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py +++ /dev/null @@ -1,235 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_timeout=None, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_timeout=None, - client_info=client_info, - ), - self.purge_user_events: gapic_v1.method.wrap_method( - self.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.rejoin_user_events: gapic_v1.method.wrap_method( - self.rejoin_user_events, - 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 write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - user_event.UserEvent, - Awaitable[user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py deleted file mode 100644 index af50579d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index cdc1a2f9..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - 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 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py deleted file mode 100644 index 8e0ea23a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .catalog import ( - Catalog, - ProductLevelConfig, -) -from .catalog_service import ( - GetDefaultBranchRequest, - GetDefaultBranchResponse, - ListCatalogsRequest, - ListCatalogsResponse, - SetDefaultBranchRequest, - UpdateCatalogRequest, -) -from .common import ( - Audience, - ColorInfo, - CustomAttribute, - FulfillmentInfo, - Image, - Interval, - LocalInventory, - PriceInfo, - Rating, - UserInfo, -) -from .completion_service import ( - CompleteQueryRequest, - CompleteQueryResponse, -) -from .import_config import ( - BigQuerySource, - CompletionDataInputConfig, - GcsSource, - ImportCompletionDataRequest, - ImportCompletionDataResponse, - ImportErrorsConfig, - ImportMetadata, - ImportProductsRequest, - ImportProductsResponse, - ImportUserEventsRequest, - ImportUserEventsResponse, - ProductInlineSource, - ProductInputConfig, - UserEventImportSummary, - UserEventInlineSource, - UserEventInputConfig, -) -from .prediction_service import ( - PredictRequest, - PredictResponse, -) -from .product import ( - Product, -) -from .product_service import ( - AddFulfillmentPlacesMetadata, - AddFulfillmentPlacesRequest, - AddFulfillmentPlacesResponse, - AddLocalInventoriesMetadata, - AddLocalInventoriesRequest, - AddLocalInventoriesResponse, - CreateProductRequest, - DeleteProductRequest, - GetProductRequest, - ListProductsRequest, - ListProductsResponse, - RemoveFulfillmentPlacesMetadata, - RemoveFulfillmentPlacesRequest, - RemoveFulfillmentPlacesResponse, - RemoveLocalInventoriesMetadata, - RemoveLocalInventoriesRequest, - RemoveLocalInventoriesResponse, - SetInventoryMetadata, - SetInventoryRequest, - SetInventoryResponse, - UpdateProductRequest, -) -from .promotion import ( - Promotion, -) -from .purge_config import ( - PurgeMetadata, - PurgeUserEventsRequest, - PurgeUserEventsResponse, -) -from .search_service import ( - SearchRequest, - SearchResponse, -) -from .user_event import ( - CompletionDetail, - ProductDetail, - PurchaseTransaction, - UserEvent, -) -from .user_event_service import ( - CollectUserEventRequest, - RejoinUserEventsMetadata, - RejoinUserEventsRequest, - RejoinUserEventsResponse, - WriteUserEventRequest, -) - -__all__ = ( - 'Catalog', - 'ProductLevelConfig', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'SetDefaultBranchRequest', - 'UpdateCatalogRequest', - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py deleted file mode 100644 index 47a372fb..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py +++ /dev/null @@ -1,131 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'ProductLevelConfig', - 'Catalog', - }, -) - - -class ProductLevelConfig(proto.Message): - r"""Configures what level the product should be uploaded with - regards to how users will be send events and how predictions - will be made. - - Attributes: - ingestion_product_type (str): - The type of [Product][google.cloud.retail.v2.Product]s - allowed to be ingested into the catalog. Acceptable values - are: - - - ``primary`` (default): You can ingest - [Product][google.cloud.retail.v2.Product]s of all types. - When ingesting a - [Product][google.cloud.retail.v2.Product], its type will - default to - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - if unset. - - ``variant`` (incompatible with Retail Search): You can - only ingest - [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s. This means - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] - cannot be empty. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``variant`` and - [merchant_center_product_id_field][google.cloud.retail.v2.ProductLevelConfig.merchant_center_product_id_field] - is ``itemGroupId``, an INVALID_ARGUMENT error is returned. - - See `Product - levels `__ - for more details. - merchant_center_product_id_field (str): - Which field of `Merchant Center - Product `__ - should be imported as - [Product.id][google.cloud.retail.v2.Product.id]. Acceptable - values are: - - - ``offerId`` (default): Import ``offerId`` as the product - ID. - - ``itemGroupId``: Import ``itemGroupId`` as the product - ID. Notice that Retail API will choose one item from the - ones with the same ``itemGroupId``, and use it to - represent the item group. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``itemGroupId`` and - [ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] - is ``variant``, an INVALID_ARGUMENT error is returned. - - See `Product - levels `__ - for more details. - """ - - ingestion_product_type = proto.Field( - proto.STRING, - number=1, - ) - merchant_center_product_id_field = proto.Field( - proto.STRING, - number=2, - ) - - -class Catalog(proto.Message): - r"""The catalog configuration. - - Attributes: - name (str): - Required. Immutable. The fully qualified - resource name of the catalog. - display_name (str): - Required. Immutable. The catalog display name. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - product_level_config (google.cloud.retail_v2.types.ProductLevelConfig): - Required. The product level configuration. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - product_level_config = proto.Field( - proto.MESSAGE, - number=4, - message='ProductLevelConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py deleted file mode 100644 index 721ef858..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py +++ /dev/null @@ -1,248 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'UpdateCatalogRequest', - 'SetDefaultBranchRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - }, -) - - -class ListCatalogsRequest(proto.Message): - r"""Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - - Attributes: - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2.Catalog]s under this - location, regardless of whether or not this location exists, - a PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of [Catalog][google.cloud.retail.v2.Catalog]s - to return. If unspecified, defaults to 50. The maximum - allowed value is 1000. Values above 1000 will be coerced to - 1000. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [ListCatalogsResponse.next_page_token][google.cloud.retail.v2.ListCatalogsResponse.next_page_token], - received from a previous - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListCatalogsResponse(proto.Message): - r"""Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - - Attributes: - catalogs (Sequence[google.cloud.retail_v2.types.Catalog]): - All the customer's - [Catalog][google.cloud.retail.v2.Catalog]s. - next_page_token (str): - A token that can be sent as - [ListCatalogsRequest.page_token][google.cloud.retail.v2.ListCatalogsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - catalogs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateCatalogRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] - method. - - Attributes: - catalog (google.cloud.retail_v2.types.Catalog): - Required. The [Catalog][google.cloud.retail.v2.Catalog] to - update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2.Catalog], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2.Catalog] 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 - [Catalog][google.cloud.retail.v2.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - catalog = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class SetDefaultBranchRequest(proto.Message): - r"""Request message to set a specified branch as new default_branch. - - Attributes: - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - branch_id (str): - The final component of the resource name of a branch. - - This field must be one of "0", "1" or "2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If there are no sufficient active products in the targeted - branch and - [force][google.cloud.retail.v2.SetDefaultBranchRequest.force] - is not set, a FAILED_PRECONDITION error is returned. - note (str): - Some note on this request, this can be retrieved by - [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch] - before next valid default branch set occurs. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - force (bool): - If set to true, it permits switching to a branch with - [branch_id][google.cloud.retail.v2.SetDefaultBranchRequest.branch_id] - even if it has no sufficient active products. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - force = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetDefaultBranchRequest(proto.Message): - r"""Request message to show which branch is currently the default - branch. - - Attributes: - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - - -class GetDefaultBranchResponse(proto.Message): - r"""Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. - - Attributes: - branch (str): - Full resource name of the branch id currently - set as default branch. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when this branch is set to default. - note (str): - This corresponds to - [SetDefaultBranchRequest.note][google.cloud.retail.v2.SetDefaultBranchRequest.note] - field, when this branch was set as default. - """ - - branch = proto.Field( - proto.STRING, - number=1, - ) - set_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py deleted file mode 100644 index fe50745a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py +++ /dev/null @@ -1,736 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'LocalInventory', - }, -) - - -class Audience(proto.Message): - r"""An intended audience of the - [Product][google.cloud.retail.v2.Product] for whom it's sold. - - Attributes: - genders (Sequence[str]): - The genders of the audience. Strongly encouraged to use the - standard values: "male", "female", "unisex". - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `gender `__. - Schema.org property - `Product.audience.suggestedGender `__. - age_groups (Sequence[str]): - The age groups of the audience. Strongly encouraged to use - the standard values: "newborn" (up to 3 months old), - "infant" (3–12 months old), "toddler" (1–5 years old), - "kids" (5–13 years old), "adult" (typically teens or older). - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `age_group `__. - Schema.org property - `Product.audience.suggestedMinAge `__ - and - `Product.audience.suggestedMaxAge `__. - """ - - genders = proto.RepeatedField( - proto.STRING, - number=1, - ) - age_groups = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class ColorInfo(proto.Message): - r"""The color information of a - [Product][google.cloud.retail.v2.Product]. - - Attributes: - color_families (Sequence[str]): - The standard color families. Strongly recommended to use the - following standard color groups: "Red", "Pink", "Orange", - "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", - "White", "Gray", "Black" and "Mixed". Normally it is - expected to have only 1 color family. May consider using - single "Mixed" instead of multiple values. - - A maximum of 5 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - colors (Sequence[str]): - The color display names, which may be different from - standard color family names, such as the color aliases used - in the website frontend. Normally it is expected to have - only 1 color. May consider using single "Mixed" instead of - multiple values. - - A maximum of 25 colors are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - """ - - color_families = proto.RepeatedField( - proto.STRING, - number=1, - ) - colors = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class CustomAttribute(proto.Message): - r"""A custom attribute that is not explicitly modeled in - [Product][google.cloud.retail.v2.Product]. - - Attributes: - text (Sequence[str]): - The textual values of this custom attribute. For example, - ``["yellow", "green"]`` when the key is "color". - - Empty string is not allowed. Otherwise, an INVALID_ARGUMENT - error is returned. - - Exactly one of - [text][google.cloud.retail.v2.CustomAttribute.text] or - [numbers][google.cloud.retail.v2.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - numbers (Sequence[float]): - The numerical values of this custom attribute. For example, - ``[2.3, 15.4]`` when the key is "lengths_cm". - - Exactly one of - [text][google.cloud.retail.v2.CustomAttribute.text] or - [numbers][google.cloud.retail.v2.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - searchable (bool): - This field is normally ignored unless - [AttributesConfig.attribute_config_level][] of the - [Catalog][google.cloud.retail.v2.Catalog] is set to the - deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For - information about product-level attribute configuration, see - `Configuration - modes `__. - If true, custom attribute values are searchable by text - queries in - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2.UserEvent]. - - Only set if type - [text][google.cloud.retail.v2.CustomAttribute.text] is set. - Otherwise, a INVALID_ARGUMENT error is returned. - - This field is a member of `oneof`_ ``_searchable``. - indexable (bool): - This field is normally ignored unless - [AttributesConfig.attribute_config_level][] of the - [Catalog][google.cloud.retail.v2.Catalog] is set to the - deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For - information about product-level attribute configuration, see - `Configuration - modes `__. - If true, custom attribute values are indexed, so that they - can be filtered, faceted or boosted in - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2.UserEvent]. - - See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter], - [SearchRequest.facet_specs][google.cloud.retail.v2.SearchRequest.facet_specs] - and - [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] - for more details. - - This field is a member of `oneof`_ ``_indexable``. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - numbers = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - searchable = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - indexable = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - -class FulfillmentInfo(proto.Message): - r"""Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - Attributes: - type_ (str): - The fulfillment type, including commonly used types (such as - pickup in store and same day delivery), and custom types. - Customers have to map custom types to their display names - before rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - place_ids (Sequence[str]): - The IDs for this - [type][google.cloud.retail.v2.FulfillmentInfo.type], such as - the store IDs for - [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2.FulfillmentInfo.type] - or the region IDs for - [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2.FulfillmentInfo.type]. - - A maximum of 3000 values are allowed. Each value must be a - string with a length limit of 30 characters, matching the - pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". - Otherwise, an INVALID_ARGUMENT error is returned. - """ - - type_ = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class Image(proto.Message): - r"""[Product][google.cloud.retail.v2.Product] image. Recommendations AI - and Retail Search do not use product images to improve prediction - and search results. However, product images can be returned in - results, and are shown in prediction or search previews in the - console. - - Attributes: - uri (str): - Required. URI of the image. - - This field must be a valid UTF-8 encoded URI with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - height (int): - Height of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - width (int): - Width of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - height = proto.Field( - proto.INT32, - number=2, - ) - width = proto.Field( - proto.INT32, - number=3, - ) - - -class Interval(proto.Message): - r"""A floating point interval. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - minimum (float): - Inclusive lower bound. - - This field is a member of `oneof`_ ``min``. - exclusive_minimum (float): - Exclusive lower bound. - - This field is a member of `oneof`_ ``min``. - maximum (float): - Inclusive upper bound. - - This field is a member of `oneof`_ ``max``. - exclusive_maximum (float): - Exclusive upper bound. - - This field is a member of `oneof`_ ``max``. - """ - - minimum = proto.Field( - proto.DOUBLE, - number=1, - oneof='min', - ) - exclusive_minimum = proto.Field( - proto.DOUBLE, - number=2, - oneof='min', - ) - maximum = proto.Field( - proto.DOUBLE, - number=3, - oneof='max', - ) - exclusive_maximum = proto.Field( - proto.DOUBLE, - number=4, - oneof='max', - ) - - -class PriceInfo(proto.Message): - r"""The price information of a - [Product][google.cloud.retail.v2.Product]. - - Attributes: - currency_code (str): - The 3-letter currency code defined in `ISO - 4217 `__. - - If this field is an unrecognizable currency code, an - INVALID_ARGUMENT error is returned. - - The - [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s with the same - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] - must share the same - [currency_code][google.cloud.retail.v2.PriceInfo.currency_code]. - Otherwise, a FAILED_PRECONDITION error is returned. - price (float): - Price of the product. - - Google Merchant Center property - `price `__. - Schema.org property - `Offer.price `__. - original_price (float): - Price of the product without any discount. If zero, by - default set to be the - [price][google.cloud.retail.v2.PriceInfo.price]. If set, - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - should be greater than or equal to - [price][google.cloud.retail.v2.PriceInfo.price], otherwise - an INVALID_ARGUMENT error is thrown. - cost (float): - The costs associated with the sale of a particular product. - Used for gross profit reporting. - - - Profit = [price][google.cloud.retail.v2.PriceInfo.price] - - [cost][google.cloud.retail.v2.PriceInfo.cost] - - Google Merchant Center property - `cost_of_goods_sold `__. - price_effective_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2.PriceInfo.price] starts to be - effective. This can be set as a future timestamp, and the - [price][google.cloud.retail.v2.PriceInfo.price] is only used - for search after - [price_effective_time][google.cloud.retail.v2.PriceInfo.price_effective_time]. - If so, the - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - is used before - [price_effective_time][google.cloud.retail.v2.PriceInfo.price_effective_time]. - - Do not set if - [price][google.cloud.retail.v2.PriceInfo.price] is always - effective because it will cause additional latency during - search. - price_expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2.PriceInfo.price] stops to be - effective. The - [price][google.cloud.retail.v2.PriceInfo.price] is used for - search before - [price_expire_time][google.cloud.retail.v2.PriceInfo.price_expire_time]. - If this field is set, the - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - is used after - [price_expire_time][google.cloud.retail.v2.PriceInfo.price_expire_time]. - - Do not set if - [price][google.cloud.retail.v2.PriceInfo.price] is always - effective because it will cause additional latency during - search. - price_range (google.cloud.retail_v2.types.PriceInfo.PriceRange): - Output only. The price range of all the child - [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s grouped together - on the - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]. Only populated - for - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]. - Do not set this field in API requests. - """ - - class PriceRange(proto.Message): - r"""The price range of all - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. - - Attributes: - price (google.cloud.retail_v2.types.Interval): - The inclusive - [Product.pricing_info.price][google.cloud.retail.v2.PriceInfo.price] - interval of all - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. - original_price (google.cloud.retail_v2.types.Interval): - The inclusive - [Product.pricing_info.original_price][google.cloud.retail.v2.PriceInfo.original_price] - internal of all - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. - """ - - price = proto.Field( - proto.MESSAGE, - number=1, - message='Interval', - ) - original_price = proto.Field( - proto.MESSAGE, - number=2, - message='Interval', - ) - - currency_code = proto.Field( - proto.STRING, - number=1, - ) - price = proto.Field( - proto.FLOAT, - number=2, - ) - original_price = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - price_effective_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - price_expire_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - price_range = proto.Field( - proto.MESSAGE, - number=7, - message=PriceRange, - ) - - -class Rating(proto.Message): - r"""The rating of a [Product][google.cloud.retail.v2.Product]. - - Attributes: - rating_count (int): - The total number of ratings. This value is independent of - the value of - [rating_histogram][google.cloud.retail.v2.Rating.rating_histogram]. - - This value must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - average_rating (float): - The average rating of the - [Product][google.cloud.retail.v2.Product]. - - The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT - error is returned. - rating_histogram (Sequence[int]): - List of rating counts per rating value (index = rating - 1). - The list is empty if there is no rating. If the list is - non-empty, its size is always 5. Otherwise, an - INVALID_ARGUMENT error is returned. - - For example, [41, 14, 13, 47, 303]. It means that the - [Product][google.cloud.retail.v2.Product] got 41 ratings - with 1 star, 14 ratings with 2 star, and so on. - """ - - rating_count = proto.Field( - proto.INT32, - number=1, - ) - average_rating = proto.Field( - proto.FLOAT, - number=2, - ) - rating_histogram = proto.RepeatedField( - proto.INT32, - number=3, - ) - - -class UserInfo(proto.Message): - r"""Information of an end user. - - Attributes: - user_id (str): - Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. Don't set for - anonymous users. - - Always use a hashed value for this ID. - - Don't set the field to the same fixed ID for different - users. This mixes the event history of those users together, - which results in degraded model quality. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - ip_address (str): - The end user's IP address. This field is used to extract - location information for personalization. - - This field must be either an IPv4 address (e.g. - "104.133.9.80") or an IPv6 address (e.g. - "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an - INVALID_ARGUMENT error is returned. - - This should not be set when: - - - setting - [SearchRequest.user_info][google.cloud.retail.v2.SearchRequest.user_info]. - - using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request] - is set. - user_agent (str): - User agent as included in the HTTP header. Required for - getting - [SearchResponse.sponsored_results][google.cloud.retail.v2.SearchResponse.sponsored_results]. - - The field must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This should not be set when using the client side event - reporting with GTM or JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request] - is set. - direct_user_request (bool): - True if the request is made directly from the end user, in - which case the - [ip_address][google.cloud.retail.v2.UserInfo.ip_address] and - [user_agent][google.cloud.retail.v2.UserInfo.user_agent] can - be populated from the HTTP request. This flag should be set - only if the API request is made directly from the end user - such as a mobile app (and not if a gateway or a server is - processing and pushing the user events). - - This should not be set when using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent]. - """ - - user_id = proto.Field( - proto.STRING, - number=1, - ) - ip_address = proto.Field( - proto.STRING, - number=2, - ) - user_agent = proto.Field( - proto.STRING, - number=3, - ) - direct_user_request = proto.Field( - proto.BOOL, - number=4, - ) - - -class LocalInventory(proto.Message): - r"""The inventory information at a place (e.g. a store) - identified by a place ID. - - Attributes: - place_id (str): - The place ID for the current set of inventory - information. - price_info (google.cloud.retail_v2.types.PriceInfo): - Product price and cost information. - - Google Merchant Center property - `price `__. - attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): - Additional local inventory attributes, for example, store - name, promotion tags, etc. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - At most 30 attributes are allowed. - - The key must be a UTF-8 encoded string with a length - limit of 32 characters. - - The key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis - or KEY_1_LIKE_THIS. - - The attribute values must be of the same type (text or - number). - - Only 1 value is allowed for each attribute. - - For text values, the length limit is 256 UTF-8 - characters. - - The attribute does not support search. The ``searchable`` - field should be unset or set to false. - - The max summed total bytes of custom attribute keys and - values per product is 5MiB. - fulfillment_types (Sequence[str]): - Input only. Supported fulfillment types. Valid fulfillment - type values include commonly used types (such as pickup in - store and same day delivery), and custom types. Customers - have to map custom types to their display names before - rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - All the elements must be distinct. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - place_id = proto.Field( - proto.STRING, - number=1, - ) - price_info = proto.Field( - proto.MESSAGE, - number=2, - message='PriceInfo', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='CustomAttribute', - ) - fulfillment_types = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py deleted file mode 100644 index 421cc1c0..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py +++ /dev/null @@ -1,229 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'CompleteQueryRequest', - 'CompleteQueryResponse', - }, -) - - -class CompleteQueryRequest(proto.Message): - r"""Auto-complete parameters. - - Attributes: - catalog (str): - Required. Catalog for which the completion is performed. - - Full resource name of catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - query (str): - Required. The query used to generate - suggestions. - The maximum number of allowed characters is 255. - visitor_id (str): - Required field. A unique identifier for tracking visitors. - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - language_codes (Sequence[str]): - The language filters applied to the output suggestions. If - set, it should contain the language of the query. If not - set, suggestions are returned without considering language - restrictions. This is the BCP-47 language code, such as - "en-US" or "sr-Latn". For more information, see `Tags for - Identifying - Languages `__. The - maximum number of language codes is 3. - device_type (str): - The device type context for completion suggestions. It is - useful to apply different suggestions on different device - types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the - suggestions are across all device types. - - Supported formats: - - - ``UNKNOWN_DEVICE_TYPE`` - - - ``DESKTOP`` - - - ``MOBILE`` - - - A customized string starts with ``OTHER_``, e.g. - ``OTHER_IPHONE``. - dataset (str): - Determines which dataset to use for fetching completion. - "user-data" will use the imported dataset through - [CompletionService.ImportCompletionData][google.cloud.retail.v2.CompletionService.ImportCompletionData]. - "cloud-retail" will use the dataset generated by cloud - retail based on user events. If leave empty, it will use the - "user-data". - - Current supported values: - - - user-data - - - cloud-retail: This option requires enabling auto-learning - function first. See - `guidelines `__. - max_suggestions (int): - Completion max suggestions. If left unset or set to 0, then - will fallback to the configured value - [CompletionConfig.max_suggestions][]. - - The maximum allowed max suggestions is 20. If it is set - higher, it will be capped by 20. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - visitor_id = proto.Field( - proto.STRING, - number=7, - ) - language_codes = proto.RepeatedField( - proto.STRING, - number=3, - ) - device_type = proto.Field( - proto.STRING, - number=4, - ) - dataset = proto.Field( - proto.STRING, - number=6, - ) - max_suggestions = proto.Field( - proto.INT32, - number=5, - ) - - -class CompleteQueryResponse(proto.Message): - r"""Response of the auto-complete query. - - Attributes: - completion_results (Sequence[google.cloud.retail_v2.types.CompleteQueryResponse.CompletionResult]): - Results of the matching suggestions. The - result list is ordered and the first result is - top suggestion. - attribution_token (str): - A unique complete token. This should be included in the - [UserEvent.completion_detail][google.cloud.retail.v2.UserEvent.completion_detail] - for search events resulting from this completion, which - enables accurate attribution of complete model performance. - recent_search_results (Sequence[google.cloud.retail_v2.types.CompleteQueryResponse.RecentSearchResult]): - Matched recent searches of this user. The maximum number of - recent searches is 10. This field is a restricted feature. - Contact Retail Search support team if you are interested in - enabling it. - - This feature is only available when - [CompleteQueryRequest.visitor_id][google.cloud.retail.v2.CompleteQueryRequest.visitor_id] - field is set and - [UserEvent][google.cloud.retail.v2.UserEvent] is imported. - The recent searches satisfy the follow rules: - - - They are ordered from latest to oldest. - - - They are matched with - [CompleteQueryRequest.query][google.cloud.retail.v2.CompleteQueryRequest.query] - case insensitively. - - - They are transformed to lower cases. - - - They are UTF-8 safe. - - Recent searches are deduplicated. More recent searches will - be reserved when duplication happens. - """ - - class CompletionResult(proto.Message): - r"""Resource that represents completion results. - - Attributes: - suggestion (str): - The suggestion for the query. - attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): - Custom attributes for the suggestion term. - - - For "user-data", the attributes are additional custom - attributes ingested through BigQuery. - - - For "cloud-retail", the attributes are product attributes - generated by Cloud Retail. This is an experimental - feature. Contact Retail Search support team if you are - interested in enabling it. - """ - - suggestion = proto.Field( - proto.STRING, - number=1, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=common.CustomAttribute, - ) - - class RecentSearchResult(proto.Message): - r"""Recent search of this user. - - Attributes: - recent_search (str): - The recent search query. - """ - - recent_search = proto.Field( - proto.STRING, - number=1, - ) - - completion_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=CompletionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - recent_search_results = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=RecentSearchResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py deleted file mode 100644 index 983e15df..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py +++ /dev/null @@ -1,697 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import user_event -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'GcsSource', - 'BigQuerySource', - 'ProductInlineSource', - 'UserEventInlineSource', - 'ImportErrorsConfig', - 'ImportProductsRequest', - 'ImportUserEventsRequest', - 'ImportCompletionDataRequest', - 'ProductInputConfig', - 'UserEventInputConfig', - 'CompletionDataInputConfig', - 'ImportMetadata', - 'ImportProductsResponse', - 'ImportUserEventsResponse', - 'UserEventImportSummary', - 'ImportCompletionDataResponse', - }, -) - - -class GcsSource(proto.Message): - r"""Google Cloud Storage location for input content. - format. - - Attributes: - input_uris (Sequence[str]): - Required. Google Cloud Storage URIs to input files. URI can - be up to 2000 characters long. URIs can match the full - object path (for example, - ``gs://bucket/directory/object.json``) or a pattern matching - one or more files, such as ``gs://bucket/directory/*.json``. - A request can contain at most 100 files, and each file can - be up to 2 GB. See `Importing product - information `__ - for the expected file format and setup instructions. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2.Product] per line. Each - product must have a valid - [Product.id][google.cloud.retail.v2.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2.UserEvent] per line. - - ``user_event_ga360``: Using - https://support.google.com/analytics/answer/3437719. - - Supported values for control imports: - - - 'control' (default): One JSON [Control][] per line. - - Supported values for catalog attribute imports: - - - 'catalog_attribute' (default): One CSV - [CatalogAttribute][] per line. - """ - - input_uris = proto.RepeatedField( - proto.STRING, - number=1, - ) - data_schema = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""BigQuery source import data from. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - partition_date (google.type.date_pb2.Date): - BigQuery time partitioned table's \_PARTITIONDATE in - YYYY-MM-DD format. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - - This field is a member of `oneof`_ ``partition``. - project_id (str): - The project ID (can be project # or ID) that - the BigQuery source is in with a length limit of - 128 characters. If not specified, inherits the - project ID from the parent request. - dataset_id (str): - Required. The BigQuery data set to copy the - data from with a length limit of 1,024 - characters. - table_id (str): - Required. The BigQuery table to copy the data - from with a length limit of 1,024 characters. - gcs_staging_dir (str): - Intermediate Cloud Storage directory used for - the import with a length limit of 2,000 - characters. Can be specified if one wants to - have the BigQuery export to a specific Cloud - Storage directory. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2.Product] per line. Each - product must have a valid - [Product.id][google.cloud.retail.v2.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2.UserEvent] per line. - - ``user_event_ga360``: The schema is available here: - https://support.google.com/analytics/answer/3437719. - - ``user_event_ga4``: This feature is in private preview. - Please contact the support team for importing Google - Analytics 4 events. The schema is available here: - https://support.google.com/analytics/answer/7029846. - - Supported values for auto-completion imports: - - - ``suggestions`` (default): One JSON completion suggestion - per line. - - ``denylist``: One JSON deny suggestion per line. - - ``allowlist``: One JSON allow suggestion per line. - """ - - partition_date = proto.Field( - proto.MESSAGE, - number=6, - oneof='partition', - message=date_pb2.Date, - ) - project_id = proto.Field( - proto.STRING, - number=5, - ) - dataset_id = proto.Field( - proto.STRING, - number=1, - ) - table_id = proto.Field( - proto.STRING, - number=2, - ) - gcs_staging_dir = proto.Field( - proto.STRING, - number=3, - ) - data_schema = proto.Field( - proto.STRING, - number=4, - ) - - -class ProductInlineSource(proto.Message): - r"""The inline source for the input config for ImportProducts - method. - - Attributes: - products (Sequence[google.cloud.retail_v2.types.Product]): - Required. A list of products to update/create. Each product - must have a valid - [Product.id][google.cloud.retail.v2.Product.id]. Recommended - max of 100 items. - """ - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=product.Product, - ) - - -class UserEventInlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (Sequence[google.cloud.retail_v2.types.UserEvent]): - Required. A list of user events to import. - Recommended max of 10k items. - """ - - user_events = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - -class ImportErrorsConfig(proto.Message): - r"""Configuration of destination for Import related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage prefix for import errors. This must be - an empty, existing Cloud Storage directory. Import errors - will be written to sharded files in this directory, one per - line, as a JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportProductsRequest(proto.Message): - r"""Request message for Import methods. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` - - If no updateMask is specified, requires products.create - permission. If updateMask is specified, requires - products.update permission. - request_id (str): - Deprecated. This field has no effect. - input_config (google.cloud.retail_v2.types.ProductInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - imported 'products' to update. If not set, will - by default update all fields. - reconciliation_mode (google.cloud.retail_v2.types.ImportProductsRequest.ReconciliationMode): - The mode of reconciliation between existing products and the - products to be imported. Defaults to - [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. - notification_pubsub_topic (str): - Full Pub/Sub topic name for receiving notification. If this - field is set, when the import is finished, a notification - will be sent to specified Pub/Sub topic. The message data - will be JSON string of a - [Operation][google.longrunning.Operation]. - - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. It has to be within - the same project as - [ImportProductsRequest.parent][google.cloud.retail.v2.ImportProductsRequest.parent]. - Make sure that both - ``cloud-retail-customer-data-access@system.gserviceaccount.com`` - and - ``service-@gcp-sa-retail.iam.gserviceaccount.com`` - have the ``pubsub.topics.publish`` IAM permission on the - topic. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - """ - class ReconciliationMode(proto.Enum): - r"""Indicates how imported products are reconciled with the - existing products created or imported before. - """ - RECONCILIATION_MODE_UNSPECIFIED = 0 - INCREMENTAL = 1 - FULL = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - request_id = proto.Field( - proto.STRING, - number=6, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='ProductInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - reconciliation_mode = proto.Field( - proto.ENUM, - number=5, - enum=ReconciliationMode, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=7, - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog`` - input_config (google.cloud.retail_v2.types.UserEventInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. Cannot be set for inline user - event imports. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='UserEventInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - - -class ImportCompletionDataRequest(proto.Message): - r"""Request message for ImportCompletionData methods. - - Attributes: - parent (str): - Required. The catalog which the suggestions dataset belongs - to. - - Format: - ``projects/1234/locations/global/catalogs/default_catalog``. - input_config (google.cloud.retail_v2.types.CompletionDataInputConfig): - Required. The desired input location of the - data. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='CompletionDataInputConfig', - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=3, - ) - - -class ProductInputConfig(proto.Message): - r"""The input config source for products. - - 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: - product_inline_source (google.cloud.retail_v2.types.ProductInlineSource): - The Inline source for the input content for - products. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2.types.GcsSource): - Google Cloud Storage location for the input - content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - product_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='ProductInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class UserEventInputConfig(proto.Message): - r"""The input config source for user events. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - user_event_inline_source (google.cloud.retail_v2.types.UserEventInlineSource): - Required. The Inline source for the input - content for UserEvents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2.types.GcsSource): - Required. Google Cloud Storage location for - the input content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2.types.BigQuerySource): - Required. BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - user_event_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='UserEventInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class CompletionDataInputConfig(proto.Message): - r"""The input config source for completion data. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - big_query_source (google.cloud.retail_v2.types.BigQuerySource): - Required. BigQuery input source. - Add the IAM permission "BigQuery Data Viewer" - for - cloud-retail-customer-data-access@system.gserviceaccount.com - before using this feature otherwise an error is - thrown. - - This field is a member of `oneof`_ ``source``. - """ - - big_query_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='BigQuerySource', - ) - - -class ImportMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - request_id (str): - Deprecated. This field is never set. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=3, - ) - failure_count = proto.Field( - proto.INT64, - number=4, - ) - request_id = proto.Field( - proto.STRING, - number=5, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=6, - ) - - -class ImportProductsResponse(proto.Message): - r"""Response of the - [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. - If the long running operation is done, then this message is returned - by the google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - import_summary (google.cloud.retail_v2.types.UserEventImportSummary): - Aggregated statistics of user event import - status. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - import_summary = proto.Field( - proto.MESSAGE, - number=3, - message='UserEventImportSummary', - ) - - -class UserEventImportSummary(proto.Message): - r"""A summary of import result. The UserEventImportSummary - summarizes the import status for user events. - - Attributes: - joined_events_count (int): - Count of user events imported with complete - existing catalog information. - unjoined_events_count (int): - Count of user events imported, but with - catalog information not found in the imported - catalog. - """ - - joined_events_count = proto.Field( - proto.INT64, - number=1, - ) - unjoined_events_count = proto.Field( - proto.INT64, - number=2, - ) - - -class ImportCompletionDataResponse(proto.Message): - r"""Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. - 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 (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py deleted file mode 100644 index 68e8c74b..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py +++ /dev/null @@ -1,275 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import user_event as gcr_user_event -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'PredictRequest', - 'PredictResponse', - }, -) - - -class PredictRequest(proto.Message): - r"""Request message for Predict method. - - Attributes: - placement (str): - Required. Full resource name of the format: - {name=projects/*/locations/global/catalogs/default_catalog/placements/*} - The ID of the Recommendations AI placement. Before you can - request predictions from your model, you must create at - least one placement for it. For more information, see - `Managing - placements `__. - - The full list of available placements can be seen at - https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements - user_event (google.cloud.retail_v2.types.UserEvent): - Required. Context about the user, what they are looking at - and what action they took to trigger the predict request. - Note that this user event detail won't be ingested to - userEvent logs. Thus, a separate userEvent write request is - required for event logging. - - Don't set - [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] - or - [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] - to the same fixed ID for different users. If you are trying - to receive non-personalized recommendations (not - recommended; this can negatively impact model performance), - instead set - [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] - to a random unique ID and leave - [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] - unset. - page_size (int): - Maximum number of results to return per page. - Set this property to the number of prediction - results needed. If zero, the service will choose - a reasonable default. The maximum allowed value - is 100. Values above 100 will be coerced to 100. - page_token (str): - The previous PredictResponse.next_page_token. - filter (str): - Filter for restricting prediction results with a length - limit of 5,000 characters. Accepts values for tags and the - ``filterOutOfStockItems`` flag. - - - Tag expressions. Restricts predictions to products that - match all of the specified tags. Boolean operators ``OR`` - and ``NOT`` are supported if the expression is enclosed - in parentheses, and must be separated from the tag values - by a space. ``-"tagA"`` is also supported and is - equivalent to ``NOT "tagA"``. Tag values must be double - quoted UTF-8 encoded strings with a size limit of 1,000 - characters. - - Note: "Recently viewed" models don't support tag - filtering at the moment. - - - filterOutOfStockItems. Restricts predictions to products - that do not have a stockState value of OUT_OF_STOCK. - - Examples: - - - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT - "promotional") - - filterOutOfStockItems tag=(-"promotional") - - filterOutOfStockItems - - If your filter blocks all prediction results, the API will - return generic (unfiltered) popular products. If you only - want results strictly matching the filters, set - ``strictFiltering`` to True in ``PredictRequest.params`` to - receive empty results instead. Note that the API will never - return items with storageStatus of "EXPIRED" or "DELETED" - regardless of filter choices. - validate_only (bool): - Use validate only mode for this prediction - query. If set to true, a dummy model will be - used that returns arbitrary products. Note that - the validate only mode should only be used for - testing the API, or if the model is not ready. - params (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional domain specific parameters for the predictions. - - Allowed values: - - - ``returnProduct``: Boolean. If set to true, the - associated product object will be returned in the - ``results.metadata`` field in the prediction response. - - ``returnScore``: Boolean. If set to true, the prediction - 'score' corresponding to each returned product will be - set in the ``results.metadata`` field in the prediction - response. The given 'score' indicates the probability of - an product being clicked/purchased given the user's - context and history. - - ``strictFiltering``: Boolean. True by default. If set to - false, the service will return generic (unfiltered) - popular products instead of empty if your filter blocks - all prediction results. - - ``priceRerankLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of - {'no-price-reranking', 'low-price-reranking', - 'medium-price-reranking', 'high-price-reranking'}. This - gives request-level control and adjusts prediction - results based on product price. - - ``diversityLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of {'no-diversity', - 'low-diversity', 'medium-diversity', 'high-diversity', - 'auto-diversity'}. This gives request-level control and - adjusts prediction results based on product category. - labels (Mapping[str, str]): - The labels applied to a resource must meet the following - requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - """ - - placement = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - validate_only = proto.Field( - proto.BOOL, - number=6, - ) - params = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class PredictResponse(proto.Message): - r"""Response message for predict method. - - Attributes: - results (Sequence[google.cloud.retail_v2.types.PredictResponse.PredictionResult]): - A list of recommended products. The order - represents the ranking (from the most relevant - product to the least). - attribution_token (str): - A unique attribution token. This should be included in the - [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting - from this recommendation, which enables accurate attribution - of recommendation model performance. - missing_ids (Sequence[str]): - IDs of products in the request that were - missing from the inventory. - validate_only (bool): - True if the validateOnly property was set in - the request. - """ - - class PredictionResult(proto.Message): - r"""PredictionResult represents the recommendation prediction - results. - - Attributes: - id (str): - ID of the recommended product - metadata (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional product metadata / annotations. - - Possible values: - - - ``product``: JSON representation of the product. Is set - if ``returnProduct`` is set to true in - ``PredictRequest.params``. - - ``score``: Prediction score in double value. Is set if - ``returnScore`` is set to true in - ``PredictRequest.params``. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - metadata = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=PredictionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - missing_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py deleted file mode 100644 index bff41d83..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py +++ /dev/null @@ -1,701 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'Product', - }, -) - - -class Product(proto.Message): - r"""Product captures all metadata information of items to be - recommended or searched. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this product becomes unavailable for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - - If it is set, the [Product][google.cloud.retail.v2.Product] - is not available for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - after - [expire_time][google.cloud.retail.v2.Product.expire_time]. - However, the product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - [expire_time][google.cloud.retail.v2.Product.expire_time] - must be later than - [available_time][google.cloud.retail.v2.Product.available_time] - and - [publish_time][google.cloud.retail.v2.Product.publish_time], - otherwise an INVALID_ARGUMENT error is thrown. - - Corresponding properties: Google Merchant Center property - `expiration_date `__. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Input only. The TTL (time to live) of the product. - - If it is set, it must be a non-negative value, and - [expire_time][google.cloud.retail.v2.Product.expire_time] is - set as current timestamp plus - [ttl][google.cloud.retail.v2.Product.ttl]. The derived - [expire_time][google.cloud.retail.v2.Product.expire_time] is - returned in the output and - [ttl][google.cloud.retail.v2.Product.ttl] is left blank when - retrieving the [Product][google.cloud.retail.v2.Product]. - - If it is set, the product is not available for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - after current timestamp plus - [ttl][google.cloud.retail.v2.Product.ttl]. However, the - product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This field is a member of `oneof`_ ``expiration``. - name (str): - Immutable. Full resource name of the product, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. - id (str): - Immutable. [Product][google.cloud.retail.v2.Product] - identifier, which is the final component of - [name][google.cloud.retail.v2.Product.name]. For example, - this field is "id_1", if - [name][google.cloud.retail.v2.Product.name] is - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `id `__. - Schema.org property - `Product.sku `__. - type_ (google.cloud.retail_v2.types.Product.Type): - Immutable. The type of the product. Default to - [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] - if unset. - primary_product_id (str): - Variant group identifier. Must be an - [id][google.cloud.retail.v2.Product.id], with the same - parent branch with this product. Otherwise, an error is - thrown. - - For - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]s, this field can - only be empty or set to the same value as - [id][google.cloud.retail.v2.Product.id]. - - For VARIANT [Product][google.cloud.retail.v2.Product]s, this - field cannot be empty. A maximum of 2,000 products are - allowed to share the same - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `item_group_id `__. - Schema.org property - `Product.inProductGroupWithID `__. - collection_member_ids (Sequence[str]): - The [id][google.cloud.retail.v2.Product.id] of the - collection members when - [type][google.cloud.retail.v2.Product.type] is - [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]. - - Non-existent product ids are allowed. The - [type][google.cloud.retail.v2.Product.type] of the members - must be either - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - or - [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - otherwise and INVALID_ARGUMENT error is thrown. Should not - set it for other types. A maximum of 1000 values are - allowed. Otherwise, an INVALID_ARGUMENT error is return. - gtin (str): - The Global Trade Item Number (GTIN) of the product. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This field must be a Unigram. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `gtin `__. - Schema.org property - `Product.isbn `__, - `Product.gtin8 `__, - `Product.gtin12 `__, - `Product.gtin13 `__, or - `Product.gtin14 `__. - - If the value is not a valid GTIN, an INVALID_ARGUMENT error - is returned. - categories (Sequence[str]): - Product categories. This field is repeated for supporting - one product belonging to several parallel categories. - Strongly recommended using the full path for better search / - recommendation quality. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - For example, if a shoes product belongs to both ["Shoes & - Accessories" -> "Shoes"] and ["Sports & Fitness" -> - "Athletic Clothing" -> "Shoes"], it could be represented as: - - :: - - "categories": [ - "Shoes & Accessories > Shoes", - "Sports & Fitness > Athletic Clothing > Shoes" - ] - - Must be set for - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] otherwise an - INVALID_ARGUMENT error is returned. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2.Product]. Empty values are - not allowed. Each value must be a UTF-8 encoded string with - a length limit of 5,000 characters. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `google_product_category `__. - Schema.org property [Product.category] - (https://schema.org/category). - title (str): - Required. Product title. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `title `__. - Schema.org property - `Product.name `__. - brands (Sequence[str]): - The brands of the product. - - A maximum of 30 brands are allowed. Each brand must be a - UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `brand `__. - Schema.org property - `Product.brand `__. - description (str): - Product description. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `description `__. - Schema.org property - `Product.description `__. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. - - For product prediction, this field is ignored and the model - automatically detects the text language. The - [Product][google.cloud.retail.v2.Product] can include text - in different languages, but duplicating - [Product][google.cloud.retail.v2.Product]s to provide text - in multiple languages can result in degraded model - performance. - - For product search this field is in use. It defaults to - "en-US" if unset. - attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): - Highly encouraged. Extra product attributes to be included. - For example, for products, this could include the store - name, vendor, style, color, etc. These are very strong - signals for recommendation model, thus we highly recommend - providing the attributes here. - - Features that can take on one of a limited number of - possible values. Two types of features can be set are: - - Textual features. some examples would be the brand/maker of - a product, or country of a customer. Numerical features. - Some examples would be the height/weight of a product, or - age of a customer. - - For example: - ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - Max entries count: 200. - - The key must be a UTF-8 encoded string with a length - limit of 128 characters. - - For indexable attribute, the key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, - ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a - non-empty UTF-8 encoded string with a length limit of 256 - characters. - - For number attributes, at most 400 values are allowed. - tags (Sequence[str]): - Custom tags associated with the product. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2.Product]. This value must - be a UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This tag can be used for filtering recommendation results by - passing the tag as part of the - [PredictRequest.filter][google.cloud.retail.v2.PredictRequest.filter]. - - Corresponding properties: Google Merchant Center property - `custom_label_0–4 `__. - price_info (google.cloud.retail_v2.types.PriceInfo): - Product price and cost information. - - Corresponding properties: Google Merchant Center property - `price `__. - rating (google.cloud.retail_v2.types.Rating): - The rating of this product. - available_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this - [Product][google.cloud.retail.v2.Product] becomes available - for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - availability (google.cloud.retail_v2.types.Product.Availability): - The online availability of the - [Product][google.cloud.retail.v2.Product]. Default to - [Availability.IN_STOCK][google.cloud.retail.v2.Product.Availability.IN_STOCK]. - - Corresponding properties: Google Merchant Center property - `availability `__. - Schema.org property - `Offer.availability `__. - available_quantity (google.protobuf.wrappers_pb2.Int32Value): - The available quantity of the item. - fulfillment_info (Sequence[google.cloud.retail_v2.types.FulfillmentInfo]): - Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - All the elements must have distinct - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type]. - Otherwise, an INVALID_ARGUMENT error is returned. - uri (str): - Canonical URL directly linking to the product detail page. - - It is strongly recommended to provide a valid uri for the - product, otherwise the service performance could be - significantly degraded. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `link `__. - Schema.org property `Offer.url `__. - images (Sequence[google.cloud.retail_v2.types.Image]): - Product images for the product. We highly recommend putting - the main image first. - - A maximum of 300 images are allowed. - - Corresponding properties: Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - audience (google.cloud.retail_v2.types.Audience): - The target group associated with a given - audience (e.g. male, veterans, car owners, - musicians, etc.) of the product. - color_info (google.cloud.retail_v2.types.ColorInfo): - The color of the product. - - Corresponding properties: Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - sizes (Sequence[str]): - The size of the product. To represent different size systems - or size types, consider using this format: - [[[size_system:]size_type:]size_value]. - - For example, in "US:MENS:M", "US" represents size system; - "MENS" represents size type; "M" represents size value. In - "GIRLS:27", size system is empty; "GIRLS" represents size - type; "27" represents size value. In "32 inches", both size - system and size type are empty, while size value is "32 - inches". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2.Product]. Each value must - be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `size `__, - `size_type `__, - and - `size_system `__. - Schema.org property - `Product.size `__. - materials (Sequence[str]): - The material of the product. For example, "leather", - "wooden". - - A maximum of 20 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 200 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `material `__. - Schema.org property - `Product.material `__. - patterns (Sequence[str]): - The pattern or graphic print of the product. For example, - "striped", "polka dot", "paisley". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2.Product]. Each value must - be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `pattern `__. - Schema.org property - `Product.pattern `__. - conditions (Sequence[str]): - The condition of the product. Strongly encouraged to use the - standard values: "new", "refurbished", "used". - - A maximum of 1 value is allowed per - [Product][google.cloud.retail.v2.Product]. Each value must - be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `condition `__. - Schema.org property - `Offer.itemCondition `__. - promotions (Sequence[google.cloud.retail_v2.types.Promotion]): - The promotions applied to the product. A maximum of 10 - values are allowed per - [Product][google.cloud.retail.v2.Product]. Only - [Promotion.promotion_id][google.cloud.retail.v2.Promotion.promotion_id] - will be used, other fields will be ignored if set. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the product is published by the retailer - for the first time, which indicates the freshness of the - products. Note that this field is different from - [available_time][google.cloud.retail.v2.Product.available_time], - given it purely describes product freshness regardless of - when it is available on search and recommendation. - retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the - [Product][google.cloud.retail.v2.Product]s are returned in - [SearchResponse][google.cloud.retail.v2.SearchResponse]. - - Supported fields for all - [type][google.cloud.retail.v2.Product.type]s: - - - [audience][google.cloud.retail.v2.Product.audience] - - [availability][google.cloud.retail.v2.Product.availability] - - [brands][google.cloud.retail.v2.Product.brands] - - [color_info][google.cloud.retail.v2.Product.color_info] - - [conditions][google.cloud.retail.v2.Product.conditions] - - [gtin][google.cloud.retail.v2.Product.gtin] - - [materials][google.cloud.retail.v2.Product.materials] - - [name][google.cloud.retail.v2.Product.name] - - [patterns][google.cloud.retail.v2.Product.patterns] - - [price_info][google.cloud.retail.v2.Product.price_info] - - [rating][google.cloud.retail.v2.Product.rating] - - [sizes][google.cloud.retail.v2.Product.sizes] - - [title][google.cloud.retail.v2.Product.title] - - [uri][google.cloud.retail.v2.Product.uri] - - Supported fields only for - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]: - - - [categories][google.cloud.retail.v2.Product.categories] - - [description][google.cloud.retail.v2.Product.description] - - [images][google.cloud.retail.v2.Product.images] - - Supported fields only for - [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT]: - - - Only the first image in - [images][google.cloud.retail.v2.Product.images] - - To mark - [attributes][google.cloud.retail.v2.Product.attributes] as - retrievable, include paths of the form "attributes.key" - where "key" is the key of a custom attribute, as specified - in [attributes][google.cloud.retail.v2.Product.attributes]. - - For - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION], - the following fields are always returned in - [SearchResponse][google.cloud.retail.v2.SearchResponse] by - default: - - - [name][google.cloud.retail.v2.Product.name] - - For - [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT], - the following fields are always returned in by default: - - - [name][google.cloud.retail.v2.Product.name] - - [color_info][google.cloud.retail.v2.Product.color_info] - - The maximum number of paths is 30. Otherwise, an - INVALID_ARGUMENT error is returned. - - Note: Returning more fields in - [SearchResponse][google.cloud.retail.v2.SearchResponse] can - increase response payload size and serving latency. - variants (Sequence[google.cloud.retail_v2.types.Product]): - Output only. Product variants grouped together on primary - product which share similar product attributes. It's - automatically grouped by - [primary_product_id][google.cloud.retail.v2.Product.primary_product_id] - for all the product variants. Only populated for - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]. - Do not set this field in API requests. - """ - class Type(proto.Enum): - r"""The type of this product.""" - TYPE_UNSPECIFIED = 0 - PRIMARY = 1 - VARIANT = 2 - COLLECTION = 3 - - class Availability(proto.Enum): - r"""Product availability. If this field is unspecified, the - product is assumed to be in stock. - """ - AVAILABILITY_UNSPECIFIED = 0 - IN_STOCK = 1 - OUT_OF_STOCK = 2 - PREORDER = 3 - BACKORDER = 4 - - expire_time = proto.Field( - proto.MESSAGE, - number=16, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl = proto.Field( - proto.MESSAGE, - number=17, - oneof='expiration', - message=duration_pb2.Duration, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - type_ = proto.Field( - proto.ENUM, - number=3, - enum=Type, - ) - primary_product_id = proto.Field( - proto.STRING, - number=4, - ) - collection_member_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - gtin = proto.Field( - proto.STRING, - number=6, - ) - categories = proto.RepeatedField( - proto.STRING, - number=7, - ) - title = proto.Field( - proto.STRING, - number=8, - ) - brands = proto.RepeatedField( - proto.STRING, - number=9, - ) - description = proto.Field( - proto.STRING, - number=10, - ) - language_code = proto.Field( - proto.STRING, - number=11, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=12, - message=common.CustomAttribute, - ) - tags = proto.RepeatedField( - proto.STRING, - number=13, - ) - price_info = proto.Field( - proto.MESSAGE, - number=14, - message=common.PriceInfo, - ) - rating = proto.Field( - proto.MESSAGE, - number=15, - message=common.Rating, - ) - available_time = proto.Field( - proto.MESSAGE, - number=18, - message=timestamp_pb2.Timestamp, - ) - availability = proto.Field( - proto.ENUM, - number=19, - enum=Availability, - ) - available_quantity = proto.Field( - proto.MESSAGE, - number=20, - message=wrappers_pb2.Int32Value, - ) - fulfillment_info = proto.RepeatedField( - proto.MESSAGE, - number=21, - message=common.FulfillmentInfo, - ) - uri = proto.Field( - proto.STRING, - number=22, - ) - images = proto.RepeatedField( - proto.MESSAGE, - number=23, - message=common.Image, - ) - audience = proto.Field( - proto.MESSAGE, - number=24, - message=common.Audience, - ) - color_info = proto.Field( - proto.MESSAGE, - number=25, - message=common.ColorInfo, - ) - sizes = proto.RepeatedField( - proto.STRING, - number=26, - ) - materials = proto.RepeatedField( - proto.STRING, - number=27, - ) - patterns = proto.RepeatedField( - proto.STRING, - number=28, - ) - conditions = proto.RepeatedField( - proto.STRING, - number=29, - ) - promotions = proto.RepeatedField( - proto.MESSAGE, - number=34, - message=promotion.Promotion, - ) - publish_time = proto.Field( - proto.MESSAGE, - number=33, - message=timestamp_pb2.Timestamp, - ) - retrievable_fields = proto.Field( - proto.MESSAGE, - number=30, - message=field_mask_pb2.FieldMask, - ) - variants = proto.RepeatedField( - proto.MESSAGE, - number=31, - message='Product', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py deleted file mode 100644 index ce4d5c3e..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py +++ /dev/null @@ -1,858 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'CreateProductRequest', - 'GetProductRequest', - 'UpdateProductRequest', - 'DeleteProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'SetInventoryRequest', - 'SetInventoryMetadata', - 'SetInventoryResponse', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesResponse', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesResponse', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesResponse', - }, -) - - -class CreateProductRequest(proto.Message): - r"""Request message for [CreateProduct][] method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - product (google.cloud.retail_v2.types.Product): - Required. The [Product][google.cloud.retail.v2.Product] to - create. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2.Product], which will become - the final component of the - [Product.name][google.cloud.retail.v2.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2.Product]s with the same - [parent][google.cloud.retail.v2.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - product_id = proto.Field( - proto.STRING, - number=3, - ) - - -class GetProductRequest(proto.Message): - r"""Request message for [GetProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested [Product][google.cloud.retail.v2.Product] - does not exist, a NOT_FOUND error is returned. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateProductRequest(proto.Message): - r"""Request message for [UpdateProduct][] method. - - Attributes: - product (google.cloud.retail_v2.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to update - does not exist and - [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Product][google.cloud.retail.v2.Product] to update. The - immutable and output only fields are NOT supported. If not - set, all supported fields (the fields that are neither - immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - The attribute key can be updated by setting the mask path as - "attributes.${key_name}". If a key name is present in the - mask but not in the patching product from the request, this - key will be deleted after the update. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, a - new [Product][google.cloud.retail.v2.Product] will be - created. In this situation, ``update_mask`` is ignored. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteProductRequest(proto.Message): - r"""Request message for [DeleteProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to delete - does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2.Product] to delete can - neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] with more than one - [variants][google.cloud.retail.v2.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2.Product] will be deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProductsRequest(proto.Message): - r"""Request message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - - Attributes: - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list products - under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2.Product]s under this - branch, regardless of whether or not this branch exists, a - PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of [Product][google.cloud.retail.v2.Product]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 - [ListProductsResponse.next_page_token][google.cloud.retail.v2.ListProductsResponse.next_page_token], - received from a previous - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - filter (str): - A filter to apply on the list results. Supported features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2.ListProductsRequest.filter] - is unset. - - List - [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s sharing the - same - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]. For example: - ``primary_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2.Product]s bundled - in a - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product]. For example: - ``collection_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2.Product]s with a - partibular type. For example: ``type = "PRIMARY"`` - ``type = "VARIANT"`` ``type = "COLLECTION"`` - - If the field is unrecognizable, an INVALID_ARGUMENT error is - returned. - - If the specified - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] or - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product] does not exist, a - NOT_FOUND error is returned. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields of [Product][google.cloud.retail.v2.Product] to - return in the responses. If not set or empty, the following - fields are returned: - - - [Product.name][google.cloud.retail.v2.Product.name] - - [Product.id][google.cloud.retail.v2.Product.id] - - [Product.title][google.cloud.retail.v2.Product.title] - - [Product.uri][google.cloud.retail.v2.Product.uri] - - [Product.images][google.cloud.retail.v2.Product.images] - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.brands][google.cloud.retail.v2.Product.brands] - - If "*" is provided, all fields are returned. - [Product.name][google.cloud.retail.v2.Product.name] is - always returned no matter what mask is set. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class ListProductsResponse(proto.Message): - r"""Response message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - - Attributes: - products (Sequence[google.cloud.retail_v2.types.Product]): - The [Product][google.cloud.retail.v2.Product]s. - next_page_token (str): - A token that can be sent as - [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class SetInventoryRequest(proto.Message): - r"""Request message for [SetInventory][] method. - - Attributes: - inventory (google.cloud.retail_v2.types.Product): - Required. The inventory information to update. The allowable - fields to update are: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product] named in - [Product.name][google.cloud.retail.v2.Product.name], - regardless of whether or not it exists, a PERMISSION_DENIED - error is returned. - - If the [Product][google.cloud.retail.v2.Product] to update - does not have existing inventory information, the provided - inventory information will be inserted. - - If the [Product][google.cloud.retail.v2.Product] to update - has existing inventory information, the provided inventory - information will be merged while respecting the last update - time for each inventory field, using the provided or default - value for - [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of fulfillment - types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear in - [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types have - empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following inventory - fields: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - - If a full overwrite of inventory information while ignoring - timestamps is needed, [UpdateProduct][] should be invoked - instead. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the request is issued, used to - prevent out-of-order updates on inventory fields - with the last update time recorded. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] with name - [Product.name][google.cloud.retail.v2.Product.name] is not - found, the inventory update will still be processed and - retained for at most 1 day until the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - inventory = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - set_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - set_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=4, - ) - - -class SetInventoryMetadata(proto.Message): - r"""Metadata related to the progress of the SetInventory operation. - Currently empty because there is no meaningful metadata populated - from the [SetInventory][] method. - - """ - - -class SetInventoryResponse(proto.Message): - r"""Response of the SetInventoryRequest. Currently empty because there - is no meaningful response populated from the [SetInventory][] - method. - - """ - - -class AddFulfillmentPlacesRequest(proto.Message): - r"""Request message for - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery" to be added for this - [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type]. - Duplicate IDs will be automatically ignored. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If the total number of place IDs exceeds 2000 for this - [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type] - after adding, then the update will be rejected. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, the - fulfillment information will still be processed and retained - for at most 1 day and processed once the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - add_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class AddFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the AddFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - """ - - -class AddFulfillmentPlacesResponse(proto.Message): - r"""Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - """ - - -class AddLocalInventoriesRequest(proto.Message): - r"""Request message for - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - local_inventories (Sequence[google.cloud.retail_v2.types.LocalInventory]): - Required. A list of inventory information at - difference places. Each place is identified by - its place ID. At most 3000 inventories are - allowed per request. - add_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided list of - [LocalInventory][google.cloud.retail.v2.LocalInventory] to - update. The field is updated to the provided value. - - If a field is set while the place does not have a previous - local inventory, the local inventory at that store is - created. - - If a field is set while the value of that field is not - provided, the original field value, if it exists, is - deleted. - - If the mask is not set or set with empty paths, all - inventory fields will be updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory updates are - issued. Used to prevent out-of-order updates on - local inventory fields. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, the - local inventory will still be processed and retained for at - most 1 day and processed once the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - local_inventories = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.LocalInventory, - ) - add_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - add_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=6, - ) - - -class AddLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the AddLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - """ - - -class AddLocalInventoriesResponse(proto.Message): - r"""Response of the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - API. Currently empty because there is no meaningful response - populated from the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - """ - - -class RemoveLocalInventoriesRequest(proto.Message): - r"""Request message for [RemoveLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - place_ids (Sequence[str]): - Required. A list of place IDs to have their - inventory deleted. At most 3000 place IDs are - allowed per request. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory deletions are - issued. Used to prevent out-of-order updates and - deletions on local inventory fields. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, the - local inventory removal request will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class RemoveLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesResponse(proto.Message): - r"""Response of the [RemoveLocalInventories][] API. Currently empty - because there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - - -class RemoveFulfillmentPlacesRequest(proto.Message): - r"""Request message for [RemoveFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][google.cloud.retail.v2.FulfillmentInfo.type]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery", to be removed for this - [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type]. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, the - fulfillment information will still be processed and retained - for at most 1 day and processed once the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class RemoveFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveFulfillmentPlaces][] method. - - """ - - -class RemoveFulfillmentPlacesResponse(proto.Message): - r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty - because there is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py deleted file mode 100644 index e8d80a4e..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'Promotion', - }, -) - - -class Promotion(proto.Message): - r"""Promotion information. - - Attributes: - promotion_id (str): - ID of the promotion. For example, "free gift". - - The value must be a UTF-8 encoded string with a length limit - of 128 characters, and match the pattern: - ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or - ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is - returned. - - Google Merchant Center property - `promotion `__. - """ - - promotion_id = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py deleted file mode 100644 index b8159aa6..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py +++ /dev/null @@ -1,107 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - }, -) - - -class PurgeMetadata(proto.Message): - r"""Metadata related to the progress of the Purge operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - """ - - -class PurgeUserEventsRequest(proto.Message): - r"""Request message for PurgeUserEvents method. - - Attributes: - parent (str): - Required. The resource name of the catalog under which the - events are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}`` - filter (str): - Required. The filter string to specify the events to be - deleted with a length limit of 5,000 characters. Empty - string filter is not allowed. The eligible fields for - filtering are: - - - ``eventType``: Double quoted - [UserEvent.event_type][google.cloud.retail.v2.UserEvent.event_type] - string. - - ``eventTime``: in ISO 8601 "zulu" format. - - ``visitorId``: Double quoted string. Specifying this will - delete all events associated with a visitor. - - ``userId``: Double quoted string. Specifying this will - delete all events associated with a user. - - Examples: - - - Deleting all events in a time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - - Deleting specific eventType in time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` - - Deleting all events for a specific visitor: - ``visitorId = "visitor1024"`` - - The filtering fields are assumed to have an implicit AND. - force (bool): - Actually perform the purge. If ``force`` is set to false, - the method will return the expected purge count without - deleting any user events. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeUserEventsResponse(proto.Message): - r"""Response of the PurgeUserEventsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purged_events_count (int): - The total count of events purged as a result - of the operation. - """ - - purged_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py deleted file mode 100644 index e6274278..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py +++ /dev/null @@ -1,1150 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'SearchRequest', - 'SearchResponse', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - - Attributes: - placement (str): - Required. The resource name of the search engine placement, - such as - ``projects/*/locations/global/catalogs/default_catalog/placements/default_search``. - This field is used to identify the serving configuration - name and the set of models that will be used to make the - search. - branch (str): - The branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - - Use "default_branch" as the branch ID or leave this field - empty, to search products under the default branch. - query (str): - Raw search query. - - If this field is empty, the request is considered a category - browsing request and returned results are based on - [filter][google.cloud.retail.v2.SearchRequest.filter] and - [page_categories][google.cloud.retail.v2.SearchRequest.page_categories]. - visitor_id (str): - Required. A unique identifier for tracking visitors. For - example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - This should be the same identifier as - [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id]. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2.types.UserInfo): - User information. - page_size (int): - Maximum number of [Product][google.cloud.retail.v2.Product]s - to return. If unspecified, defaults to a reasonable value. - The maximum allowed value is 120. Values above 120 will be - coerced to 120. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [SearchResponse.next_page_token][google.cloud.retail.v2.SearchResponse.next_page_token], - received from a previous - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - offset (int): - A 0-indexed integer that specifies the current offset (that - is, starting result location, amongst the - [Product][google.cloud.retail.v2.Product]s deemed by the API - as relevant) in search results. This field is only - considered if - [page_token][google.cloud.retail.v2.SearchRequest.page_token] - is unset. - - If this field is negative, an INVALID_ARGUMENT is returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. Filter expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - canonical_filter (str): - The default filter that is applied when a user performs a - search without checking any filters on the search page. - - The filter applied to every search request when quality - improvement such as query expansion is needed. For example, - if a query does not have enough results, an expanded query - with - [SearchRequest.canonical_filter][google.cloud.retail.v2.SearchRequest.canonical_filter] - will be returned as a supplement of the original query. This - field is strongly recommended to achieve high search - quality. - - See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] - for more details about filter syntax. - order_by (str): - The order in which products are returned. Products can be - ordered by a field in an - [Product][google.cloud.retail.v2.Product] object. Leave it - unset if ordered by relevance. OrderBy expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - facet_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.FacetSpec]): - Facet specifications for faceted search. If empty, no facets - are returned. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - dynamic_facet_spec (google.cloud.retail_v2.types.SearchRequest.DynamicFacetSpec): - Deprecated. Refer to - https://cloud.google.com/retail/docs/configs#dynamic - to enable dynamic facets. Do not set this field. - The specification for dynamically generated - facets. Notice that only textual facets can be - dynamically generated. - boost_spec (google.cloud.retail_v2.types.SearchRequest.BoostSpec): - Boost specification to boost certain products. See more - details at this `user - guide `__. - - Notice that if both [ServingConfig.boost_control_ids][] and - [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] - are set, the boost conditions from both places are - evaluated. If a search request matches multiple boost - conditions, the final boost score is equal to the sum of the - boost scores from all matched boost conditions. - query_expansion_spec (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec): - The query expansion specification that specifies the - conditions under which query expansion will occur. See more - details at this `user - guide `__. - variant_rollup_keys (Sequence[str]): - The keys to fetch and rollup the matching - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s attributes, - [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo] or - [LocalInventory][google.cloud.retail.v2.LocalInventory]s - attributes. The attributes from all the matching - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s or - [LocalInventory][google.cloud.retail.v2.LocalInventory]s are - merged and de-duplicated. Notice that rollup attributes will - lead to extra query latency. Maximum number of keys is 30. - - For - [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], a - fulfillment type and a fulfillment ID must be provided in - the format of "fulfillmentType.fulfillmentId". E.g., in - "pickupInStore.store123", "pickupInStore" is fulfillment - type and "store123" is the store ID. - - Supported keys are: - - - colorFamilies - - price - - originalPrice - - discount - - variantId - - inventory(place_id,price) - - inventory(place_id,original_price) - - inventory(place_id,attributes.key), where key is any key - in the - [Product.local_inventories.attributes][google.cloud.retail.v2.LocalInventory.attributes] - map. - - attributes.key, where key is any key in the - [Product.attributes][google.cloud.retail.v2.Product.attributes] - map. - - pickupInStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "pickup-in-store". - - shipToStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "ship-to-store". - - sameDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "same-day-delivery". - - nextDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "next-day-delivery". - - customFulfillment1.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-1". - - customFulfillment2.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-2". - - customFulfillment3.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-3". - - customFulfillment4.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-4". - - customFulfillment5.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-5". - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. Required for - category navigation queries to achieve good search quality. - The format should be the same as - [UserEvent.page_categories][google.cloud.retail.v2.UserEvent.page_categories]; - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - search_mode (google.cloud.retail_v2.types.SearchRequest.SearchMode): - The search mode of the search request. If not - specified, a single search request triggers both - product search and faceted search. - personalization_spec (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec): - The specification for personalization. - labels (Mapping[str, str]): - The labels applied to a resource must meet the following - requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - spell_correction_spec (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec): - The spell correction specification that - specifies the mode under which spell correction - will take effect. - - This field is a member of `oneof`_ ``_spell_correction_spec``. - """ - class SearchMode(proto.Enum): - r"""The search mode of each search request.""" - SEARCH_MODE_UNSPECIFIED = 0 - PRODUCT_SEARCH_ONLY = 1 - FACETED_SEARCH_ONLY = 2 - - class FacetSpec(proto.Message): - r"""A facet specification to perform faceted search. - - Attributes: - facet_key (google.cloud.retail_v2.types.SearchRequest.FacetSpec.FacetKey): - Required. The facet key specification. - limit (int): - Maximum of facet values that should be returned for this - facet. If unspecified, defaults to 20. The maximum allowed - value is 300. Values above 300 will be coerced to 300. - - If this field is negative, an INVALID_ARGUMENT is returned. - excluded_filter_keys (Sequence[str]): - List of keys to exclude when faceting. - - By default, - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - is not excluded from the filter unless it is listed in this - field. - - Listing a facet key in this field allows its values to - appear as facet results, even when they are filtered out of - search results. Using this field does not affect what search - results are returned. - - For example, suppose there are 100 products with the color - facet "Red" and 200 products with the color facet "Blue". A - query containing the filter "colorFamilies:ANY("Red")" and - having "colorFamilies" as - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - would by default return only "Red" products in the search - results, and also return "Red" with count 100 as the only - color facet. Although there are also blue products - available, "Blue" would not be shown as an available facet - value. - - If "colorFamilies" is listed in "excludedFilterKeys", then - the query returns the facet values "Red" with count 100 and - "Blue" with count 200, because the "colorFamilies" key is - now excluded from the filter. Because this field doesn't - affect search results, the search results are still - correctly filtered to return only "Red" products. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - enable_dynamic_position (bool): - Enables dynamic position for this facet. If set to true, the - position of this facet among all facets in the response is - determined by Google Retail Search. It will be ordered - together with dynamic facets if dynamic facets is enabled. - If set to false, the position of this facet in the response - will be the same as in the request, and it will be ranked - before the facets with dynamic position enable and all - dynamic facets. - - For example, you may always want to have rating facet - returned in the response, but it's not necessarily to always - display the rating facet at the top. In that case, you can - set enable_dynamic_position to true so that the position of - rating facet in response will be determined by Google Retail - Search. - - Another example, assuming you have the following facets in - the request: - - - "rating", enable_dynamic_position = true - - - "price", enable_dynamic_position = false - - - "brands", enable_dynamic_position = false - - And also you have a dynamic facets enable, which will - generate a facet 'gender'. Then the final order of the - facets in the response can be ("price", "brands", "rating", - "gender") or ("price", "brands", "gender", "rating") depends - on how Google Retail Search orders "gender" and "rating" - facets. However, notice that "price" and "brands" will - always be ranked at 1st and 2nd position since their - enable_dynamic_position are false. - """ - - class FacetKey(proto.Message): - r"""Specifies how a facet is computed. - - Attributes: - key (str): - Required. Supported textual and numerical facet keys in - [Product][google.cloud.retail.v2.Product] object, over which - the facet values are computed. Facet key is case-sensitive. - - Allowed facet keys when - [FacetKey.query][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.query] - is not specified: - - - textual_field = - - - "brands" - - "categories" - - "genders" - - "ageGroups" - - "availability" - - "colorFamilies" - - "colors" - - "sizes" - - "materials" - - "patterns" - - "conditions" - - "attributes.key" - - "pickupInStore" - - "shipToStore" - - "sameDayDelivery" - - "nextDayDelivery" - - "customFulfillment1" - - "customFulfillment2" - - "customFulfillment3" - - "customFulfillment4" - - "customFulfillment5" - - "inventory(place_id,attributes.key)" - - - numerical_field = - - - "price" - - "discount" - - "rating" - - "ratingCount" - - "attributes.key" - - "inventory(place_id,price)" - - "inventory(place_id,original_price)" - - "inventory(place_id,attributes.key)". - intervals (Sequence[google.cloud.retail_v2.types.Interval]): - Set only if values should be bucketized into - intervals. Must be set for facets with numerical - values. Must not be set for facet with text - values. Maximum number of intervals is 30. - restricted_values (Sequence[str]): - Only get facet for the given restricted values. For example, - when using "pickupInStore" as key and set restricted values - to ["store123", "store456"], only facets for "store123" and - "store456" are returned. Only supported on predefined - textual fields, custom textual attributes and fulfillments. - Maximum is 20. - - Must be set for the fulfillment facet keys: - - - pickupInStore - - - shipToStore - - - sameDayDelivery - - - nextDayDelivery - - - customFulfillment1 - - - customFulfillment2 - - - customFulfillment3 - - - customFulfillment4 - - - customFulfillment5 - prefixes (Sequence[str]): - Only get facet values that start with the - given string prefix. For example, suppose - "categories" has three values "Women > Shoe", - "Women > Dress" and "Men > Shoe". If set - "prefixes" to "Women", the "categories" facet - will give only "Women > Shoe" and "Women > - Dress". Only supported on textual fields. - Maximum is 10. - contains (Sequence[str]): - Only get facet values that contains the given - strings. For example, suppose "categories" has - three values "Women > Shoe", "Women > Dress" and - "Men > Shoe". If set "contains" to "Shoe", the - "categories" facet will give only "Women > Shoe" - and "Men > Shoe". Only supported on textual - fields. Maximum is 10. - order_by (str): - The order in which [Facet.values][] are returned. - - Allowed values are: - - - "count desc", which means order by - [Facet.FacetValue.count][] descending. - - - "value desc", which means order by - [Facet.FacetValue.value][] descending. Only applies to - textual facets. - - If not set, textual values are sorted in `natural - order `__; - numerical intervals are sorted in the order given by - [FacetSpec.FacetKey.intervals][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.intervals]; - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - are sorted in the order given by - [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.restricted_values]. - query (str): - The query that is used to compute facet for the given facet - key. When provided, it will override the default behavior of - facet computation. The query syntax is the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] - for detail syntax and limitations. Notice that there is no - limitation on - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - when query is specified. - - In the response, [FacetValue.value][] will be always "1" and - [FacetValue.count][] will be the number of results that - matches the query. - - For example, you can set a customized facet for - "shipToStore", where - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - is "customizedShipToStore", and - [FacetKey.query][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.query] - is "availability: ANY("IN_STOCK") AND shipToStore: - ANY("123")". Then the facet will count the products that are - both in stock and ship to store "123". - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - intervals = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Interval, - ) - restricted_values = proto.RepeatedField( - proto.STRING, - number=3, - ) - prefixes = proto.RepeatedField( - proto.STRING, - number=8, - ) - contains = proto.RepeatedField( - proto.STRING, - number=9, - ) - order_by = proto.Field( - proto.STRING, - number=4, - ) - query = proto.Field( - proto.STRING, - number=5, - ) - - facet_key = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.FacetSpec.FacetKey', - ) - limit = proto.Field( - proto.INT32, - number=2, - ) - excluded_filter_keys = proto.RepeatedField( - proto.STRING, - number=3, - ) - enable_dynamic_position = proto.Field( - proto.BOOL, - number=4, - ) - - class DynamicFacetSpec(proto.Message): - r"""The specifications of dynamically generated facets. - - Attributes: - mode (google.cloud.retail_v2.types.SearchRequest.DynamicFacetSpec.Mode): - Mode of the DynamicFacet feature. Defaults to - [Mode.DISABLED][google.cloud.retail.v2.SearchRequest.DynamicFacetSpec.Mode.DISABLED] - if it's unset. - """ - class Mode(proto.Enum): - r"""Enum to control DynamicFacet mode""" - MODE_UNSPECIFIED = 0 - DISABLED = 1 - ENABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.DynamicFacetSpec.Mode', - ) - - class BoostSpec(proto.Message): - r"""Boost specification to boost certain items. - - Attributes: - condition_boost_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - Condition boost specifications. If a product - matches multiple conditions in the - specifictions, boost scores from these - specifications are all applied and combined in a - non-linear way. Maximum number of specifications - is 20. - skip_boost_spec_validation (bool): - Whether to skip boostspec validation. If this field is set - to true, invalid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] - will be ignored and valid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] - will still be applied. - - This field is a member of `oneof`_ ``_skip_boost_spec_validation``. - """ - - class ConditionBoostSpec(proto.Message): - r"""Boost applies to products which match a condition. - - Attributes: - condition (str): - An expression which specifies a boost condition. The syntax - and supported fields are the same as a filter expression. - See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": - - - (id: ANY("product_1", "product_2")) AND - (colorFamilies: ANY("Red","Blue")) - boost (float): - Strength of the condition boost, which should be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - """ - - condition = proto.Field( - proto.STRING, - number=1, - ) - boost = proto.Field( - proto.FLOAT, - number=2, - ) - - condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - skip_boost_spec_validation = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - - class QueryExpansionSpec(proto.Message): - r"""Specification to determine under which conditions query - expansion should occur. - - Attributes: - condition (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec.Condition): - The condition under which query expansion should occur. - Default to - [Condition.DISABLED][google.cloud.retail.v2.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - pin_unexpanded_results (bool): - Whether to pin unexpanded results. If this - field is set to true, unexpanded products are - always at the top of the search results, - followed by the expanded results. - """ - class Condition(proto.Enum): - r"""Enum describing under which condition query expansion should - occur. - """ - CONDITION_UNSPECIFIED = 0 - DISABLED = 1 - AUTO = 3 - - condition = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.QueryExpansionSpec.Condition', - ) - pin_unexpanded_results = proto.Field( - proto.BOOL, - number=2, - ) - - class PersonalizationSpec(proto.Message): - r"""The specification for personalization. - - Attributes: - mode (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec.Mode): - Defaults to - [Mode.AUTO][google.cloud.retail.v2.SearchRequest.PersonalizationSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""The personalization mode of each search request.""" - MODE_UNSPECIFIED = 0 - AUTO = 1 - DISABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.PersonalizationSpec.Mode', - ) - - class SpellCorrectionSpec(proto.Message): - r"""The specification for query spell correction. - - Attributes: - mode (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec.Mode): - The mode under which spell correction should take effect to - replace the original search query. Default to - [Mode.AUTO][google.cloud.retail.v2.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""Enum describing under which mode spell correction should - occur. - """ - MODE_UNSPECIFIED = 0 - SUGGESTION_ONLY = 1 - AUTO = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.SpellCorrectionSpec.Mode', - ) - - placement = proto.Field( - proto.STRING, - number=1, - ) - branch = proto.Field( - proto.STRING, - number=2, - ) - query = proto.Field( - proto.STRING, - number=3, - ) - visitor_id = proto.Field( - proto.STRING, - number=4, - ) - user_info = proto.Field( - proto.MESSAGE, - number=5, - message=common.UserInfo, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - offset = proto.Field( - proto.INT32, - number=9, - ) - filter = proto.Field( - proto.STRING, - number=10, - ) - canonical_filter = proto.Field( - proto.STRING, - number=28, - ) - order_by = proto.Field( - proto.STRING, - number=11, - ) - facet_specs = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=FacetSpec, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=21, - message=DynamicFacetSpec, - ) - boost_spec = proto.Field( - proto.MESSAGE, - number=13, - message=BoostSpec, - ) - query_expansion_spec = proto.Field( - proto.MESSAGE, - number=14, - message=QueryExpansionSpec, - ) - variant_rollup_keys = proto.RepeatedField( - proto.STRING, - number=17, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=23, - ) - search_mode = proto.Field( - proto.ENUM, - number=31, - enum=SearchMode, - ) - personalization_spec = proto.Field( - proto.MESSAGE, - number=32, - message=PersonalizationSpec, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=34, - ) - spell_correction_spec = proto.Field( - proto.MESSAGE, - number=35, - optional=True, - message=SpellCorrectionSpec, - ) - - -class SearchResponse(proto.Message): - r"""Response message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - - Attributes: - results (Sequence[google.cloud.retail_v2.types.SearchResponse.SearchResult]): - A list of matched items. The order represents - the ranking. - facets (Sequence[google.cloud.retail_v2.types.SearchResponse.Facet]): - Results of facets requested by user. - total_size (int): - The estimated total count of matched items irrespective of - pagination. The count of - [results][google.cloud.retail.v2.SearchResponse.results] - returned by pagination may be less than the - [total_size][google.cloud.retail.v2.SearchResponse.total_size] - that matches. - corrected_query (str): - Contains the spell corrected query, if found. If the spell - correction type is AUTOMATIC, then the search results are - based on corrected_query. Otherwise the original query will - be used for search. - attribution_token (str): - A unique search token. This should be included in the - [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting - from this search, which enables accurate attribution of - search model performance. - next_page_token (str): - A token that can be sent as - [SearchRequest.page_token][google.cloud.retail.v2.SearchRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - query_expansion_info (google.cloud.retail_v2.types.SearchResponse.QueryExpansionInfo): - Query expansion information for the returned - results. - redirect_uri (str): - The URI of a customer-defined redirect page. If redirect - action is triggered, no search is performed, and only - [redirect_uri][google.cloud.retail.v2.SearchResponse.redirect_uri] - and - [attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] - are set in the response. - applied_controls (Sequence[str]): - The fully qualified resource name of applied - `controls `__. - invalid_condition_boost_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - The invalid - [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] - that are not applied during serving. - """ - - class SearchResult(proto.Message): - r"""Represents the search results. - - Attributes: - id (str): - [Product.id][google.cloud.retail.v2.Product.id] of the - searched [Product][google.cloud.retail.v2.Product]. - product (google.cloud.retail_v2.types.Product): - The product data snippet in the search response. Only - [Product.name][google.cloud.retail.v2.Product.name] is - guaranteed to be populated. - - [Product.variants][google.cloud.retail.v2.Product.variants] - contains the product variants that match the search query. - If there are multiple product variants matching the query, - top 5 most relevant product variants are returned and - ordered by relevancy. - - If relevancy can be deternmined, use - [matching_variant_fields][google.cloud.retail.v2.SearchResponse.SearchResult.matching_variant_fields] - to look up matched product variants fields. If relevancy - cannot be determined, e.g. when searching "shoe" all - products in a shoe product can be a match, 5 product - variants are returned but order is meaningless. - matching_variant_count (int): - The count of matched - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s. - matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): - If a [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] matches the search - query, this map indicates which - [Product][google.cloud.retail.v2.Product] fields are - matched. The key is the - [Product.name][google.cloud.retail.v2.Product.name], the - value is a field mask of the matched - [Product][google.cloud.retail.v2.Product] fields. If matched - attributes cannot be determined, this map will be empty. - - For example, a key "sku1" with field mask - "products.color_info" indicates there is a match between - "sku1" [ColorInfo][google.cloud.retail.v2.ColorInfo] and the - query. - variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): - The rollup matching - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] attributes. The - key is one of the - [SearchRequest.variant_rollup_keys][google.cloud.retail.v2.SearchRequest.variant_rollup_keys]. - The values are the merged and de-duplicated - [Product][google.cloud.retail.v2.Product] attributes. Notice - that the rollup values are respect filter. For example, when - filtering by "colorFamilies:ANY("red")" and rollup - "colorFamilies", only "red" is returned. - - For textual and numerical attributes, the rollup values is a - list of string or double values with type - [google.protobuf.ListValue][google.protobuf.ListValue]. For - example, if there are two variants with colors "red" and - "blue", the rollup values are - - :: - - { key: "colorFamilies" - value { - list_value { - values { string_value: "red" } - values { string_value: "blue" } - } - } - } - - For - [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], - the rollup values is a double value with type - [google.protobuf.Value][google.protobuf.Value]. For example, - ``{key: "pickupInStore.store1" value { number_value: 10 }}`` - means a there are 10 variants in this product are available - in the store "store1". - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - matching_variant_count = proto.Field( - proto.INT32, - number=3, - ) - matching_variant_fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - variant_rollup_values = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - - class Facet(proto.Message): - r"""A facet result. - - Attributes: - key (str): - The key for this facet. E.g., "colorFamilies" - or "price" or "attributes.attr1". - values (Sequence[google.cloud.retail_v2.types.SearchResponse.Facet.FacetValue]): - The facet values for this field. - dynamic_facet (bool): - Whether the facet is dynamically generated. - """ - - class FacetValue(proto.Message): - r"""A facet value which contains value names and their count. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Text value of a facet, such as "Black" for - facet "colorFamilies". - - This field is a member of `oneof`_ ``facet_value``. - interval (google.cloud.retail_v2.types.Interval): - Interval value for a facet, such as [10, 20) for facet - "price". - - This field is a member of `oneof`_ ``facet_value``. - count (int): - Number of items that have this facet value. - """ - - value = proto.Field( - proto.STRING, - number=1, - oneof='facet_value', - ) - interval = proto.Field( - proto.MESSAGE, - number=2, - oneof='facet_value', - message=common.Interval, - ) - count = proto.Field( - proto.INT64, - number=3, - ) - - key = proto.Field( - proto.STRING, - number=1, - ) - values = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SearchResponse.Facet.FacetValue', - ) - dynamic_facet = proto.Field( - proto.BOOL, - number=3, - ) - - class QueryExpansionInfo(proto.Message): - r"""Information describing query expansion including whether - expansion has occurred. - - Attributes: - expanded_query (bool): - Bool describing whether query expansion has - occurred. - pinned_result_count (int): - Number of pinned results. This field will only be set when - expansion happens and - [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] - is set to true. - """ - - expanded_query = proto.Field( - proto.BOOL, - number=1, - ) - pinned_result_count = proto.Field( - proto.INT64, - number=2, - ) - - @property - def raw_page(self): - return self - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=SearchResult, - ) - facets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Facet, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - corrected_query = proto.Field( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - next_page_token = proto.Field( - proto.STRING, - number=6, - ) - query_expansion_info = proto.Field( - proto.MESSAGE, - number=7, - message=QueryExpansionInfo, - ) - redirect_uri = proto.Field( - proto.STRING, - number=10, - ) - applied_controls = proto.RepeatedField( - proto.STRING, - number=12, - ) - invalid_condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py deleted file mode 100644 index 0d6b6823..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py +++ /dev/null @@ -1,508 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import product as gcr_product -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'UserEvent', - 'ProductDetail', - 'CompletionDetail', - 'PurchaseTransaction', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information Retail API needs - to know about how end users interact with customers' website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - - ``add-to-cart``: Products being added to cart. - - ``category-page-view``: Special pages such as sale or - promotion pages viewed. - - ``detail-page-view``: Products detail page viewed. - - ``home-page-view``: Homepage viewed. - - ``promotion-offered``: Promotion is offered to a user. - - ``promotion-not-offered``: Promotion is not offered to a - user. - - ``purchase-complete``: User finishing a purchase. - - ``search``: Product search. - - ``shopping-cart-page-view``: User viewing a shopping - cart. - visitor_id (str): - Required. A unique identifier for tracking visitors. - - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor log in/out of the website. - - Don't set the field to the same fixed ID for different - users. This mixes the event history of those users together, - which results in degraded model quality. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - The field should not contain PII or user-data. We recommend - to use Google Analytics `Client - ID `__ - for this field. - session_id (str): - A unique identifier for tracking a visitor session with a - length limit of 128 bytes. A session is an aggregation of an - end user behavior in a time span. - - A general guideline to populate the sesion_id: - - 1. If user has no activity for 30 min, a new session_id - should be assigned. - 2. The session_id should be unique across users, suggest use - uuid or add visitor_id as prefix. - event_time (google.protobuf.timestamp_pb2.Timestamp): - Only required for - [UserEventService.ImportUserEvents][google.cloud.retail.v2.UserEventService.ImportUserEvents] - method. Timestamp of when the user event happened. - experiment_ids (Sequence[str]): - A list of identifiers for the independent - experiment groups this user event belongs to. - This is used to distinguish between user events - associated with different experiment setups - (e.g. using Retail API, using different - recommendation models). - attribution_token (str): - Highly recommended for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]. - This field enables accurate attribution of recommendation - model performance. - - The value must be a valid - [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] - for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]. - The value must be a valid - [SearchResponse.attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] - for user events that are the result of - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - - This token enables us to accurately attribute page view or - purchase back to the event and the particular predict - response containing this clicked/purchased product. If user - clicks on product K in the recommendation results, pass - [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] - as a URL parameter to product K's page. When recording - events on product K's page, log the - [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] - to this field. - product_details (Sequence[google.cloud.retail_v2.types.ProductDetail]): - The main product details related to the event. - - This field is optional except for the following event types: - - - ``add-to-cart`` - - ``detail-page-view`` - - ``purchase-complete`` - - In a ``search`` event, this field represents the products - returned to the end user on the current page (the end user - may have not finished browsing the whole page yet). When a - new page is returned to the end user, after - pagination/filtering/ordering even for the same query, a new - ``search`` event with different - [product_details][google.cloud.retail.v2.UserEvent.product_details] - is desired. The end user may have not finished browsing the - whole page yet. - completion_detail (google.cloud.retail_v2.types.CompletionDetail): - The main auto-completion details related to the event. - - This field should be set for ``search`` event when - autocomplete function is enabled and the user clicks a - suggestion for search. - attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): - Extra user event features to include in the recommendation - model. - - If you provide custom attributes for ingested user events, - also include them in the user events that you associate with - prediction requests. Custom attribute formatting must be - consistent between imported events and events provided with - prediction requests. This lets the Retail API use those - custom attributes when training models and serving - predictions, which helps improve recommendation quality. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - The key must be a UTF-8 encoded string with a length - limit of 5,000 characters. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a UTF-8 - encoded string with a length limit of 256 characters. - - For number attributes, at most 400 values are allowed. - - For product recommendations, an example of extra user - information is traffic_channel, which is how a user arrives - at the site. Users can arrive at the site by coming to the - site directly, coming through Google search, or in other - ways. - cart_id (str): - The ID or name of the associated shopping cart. This ID is - used to associate multiple items added or present in the - cart before purchase. - - This can only be set for ``add-to-cart``, - ``purchase-complete``, or ``shopping-cart-page-view`` - events. - purchase_transaction (google.cloud.retail_v2.types.PurchaseTransaction): - A transaction represents the entire purchase transaction. - - Required for ``purchase-complete`` events. Other event types - should not set this field. Otherwise, an INVALID_ARGUMENT - error is returned. - search_query (str): - The user's search query. - - See - [SearchRequest.query][google.cloud.retail.v2.SearchRequest.query] - for definition. - - The value must be a UTF-8 encoded string with a length limit - of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - At least one of - [search_query][google.cloud.retail.v2.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. - - See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - order_by (str): - The order in which products are returned. - - See - [SearchRequest.order_by][google.cloud.retail.v2.SearchRequest.order_by] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - offset (int): - An integer that specifies the current offset for pagination - (the 0-indexed starting location, amongst the products - deemed by the API as relevant). - - See - [SearchRequest.offset][google.cloud.retail.v2.SearchRequest.offset] - for definition. - - If this field is negative, an INVALID_ARGUMENT is returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - - Required for ``category-page-view`` events. At least one of - [search_query][google.cloud.retail.v2.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2.types.UserInfo): - User information. - uri (str): - Complete URL (window.location.href) of the - user's current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. Maximum length - 5,000 characters. - referrer_uri (str): - The referrer URL of the current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. - page_view_id (str): - A unique ID of a web page view. - - This should be kept the same for all user events triggered - from the same pageview. For example, an item detail page - view could trigger multiple events as the user is browsing - the page. The ``pageViewId`` property should be kept the - same for all these events so that they can be grouped - together properly. - - When using the client side event reporting with JavaScript - pixel and Google Tag Manager, this value is filled in - automatically. - """ - - event_type = proto.Field( - proto.STRING, - number=1, - ) - visitor_id = proto.Field( - proto.STRING, - number=2, - ) - session_id = proto.Field( - proto.STRING, - number=21, - ) - event_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - experiment_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - product_details = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='ProductDetail', - ) - completion_detail = proto.Field( - proto.MESSAGE, - number=22, - message='CompletionDetail', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=common.CustomAttribute, - ) - cart_id = proto.Field( - proto.STRING, - number=8, - ) - purchase_transaction = proto.Field( - proto.MESSAGE, - number=9, - message='PurchaseTransaction', - ) - search_query = proto.Field( - proto.STRING, - number=10, - ) - filter = proto.Field( - proto.STRING, - number=16, - ) - order_by = proto.Field( - proto.STRING, - number=17, - ) - offset = proto.Field( - proto.INT32, - number=18, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=11, - ) - user_info = proto.Field( - proto.MESSAGE, - number=12, - message=common.UserInfo, - ) - uri = proto.Field( - proto.STRING, - number=13, - ) - referrer_uri = proto.Field( - proto.STRING, - number=14, - ) - page_view_id = proto.Field( - proto.STRING, - number=15, - ) - - -class ProductDetail(proto.Message): - r"""Detailed product information associated with a user event. - - Attributes: - product (google.cloud.retail_v2.types.Product): - Required. [Product][google.cloud.retail.v2.Product] - information. - - Required field(s): - - - [Product.id][google.cloud.retail.v2.Product.id] - - Optional override field(s): - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - If any supported optional fields are provided, we will treat - them as a full override when looking up product information - from the catalog. Thus, it is important to ensure that the - overriding fields are accurate and complete. - - All other product fields are ignored and instead populated - via catalog lookup after event ingestion. - quantity (google.protobuf.wrappers_pb2.Int32Value): - Quantity of the product associated with the user event. - - For example, this field will be 2 if two products are added - to the shopping cart for ``purchase-complete`` event. - Required for ``add-to-cart`` and ``purchase-complete`` event - types. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - quantity = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -class CompletionDetail(proto.Message): - r"""Detailed completion information including completion - attribution token and clicked completion info. - - Attributes: - completion_attribution_token (str): - Completion attribution token in - [CompleteQueryResponse.attribution_token][google.cloud.retail.v2.CompleteQueryResponse.attribution_token]. - selected_suggestion (str): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2.CompleteQueryResponse.CompletionResult.suggestion]. - selected_position (int): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2.CompleteQueryResponse.CompletionResult.suggestion] - position, starting from 0. - """ - - completion_attribution_token = proto.Field( - proto.STRING, - number=1, - ) - selected_suggestion = proto.Field( - proto.STRING, - number=2, - ) - selected_position = proto.Field( - proto.INT32, - number=3, - ) - - -class PurchaseTransaction(proto.Message): - r"""A transaction represents the entire purchase transaction. - - Attributes: - id (str): - The transaction ID with a length limit of 128 - characters. - revenue (float): - Required. Total non-zero revenue or grand - total associated with the transaction. This - value include shipping, tax, or other - adjustments to total revenue that you want to - include as part of your revenue calculations. - tax (float): - All the taxes associated with the - transaction. - cost (float): - All the costs associated with the products. These can be - manufacturing costs, shipping expenses not borne by the end - user, or any other costs, such that: - - - Profit = - [revenue][google.cloud.retail.v2.PurchaseTransaction.revenue] - - [tax][google.cloud.retail.v2.PurchaseTransaction.tax] - - [cost][google.cloud.retail.v2.PurchaseTransaction.cost] - currency_code (str): - Required. Currency code. Use three-character - ISO-4217 code. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - revenue = proto.Field( - proto.FLOAT, - number=2, - ) - tax = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - currency_code = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py deleted file mode 100644 index fcfc46d7..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import user_event as gcr_user_event - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'WriteUserEventRequest', - 'CollectUserEventRequest', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'RejoinUserEventsMetadata', - }, -) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (google.cloud.retail_v2.types.UserEvent): - Required. User event to write. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (str): - Required. URL encoded UserEvent proto with a - length limit of 2,000,000 characters. - uri (str): - The URL including cgi-parameters but - excluding the hash fragment with a length limit - of 5,000 characters. This is often more useful - than the referer URL, because many browsers only - send the domain for 3rd party requests. - ets (int): - The event timestamp in milliseconds. This - prevents browser caching of otherwise identical - get requests. The name is abbreviated to reduce - the payload bytes. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.STRING, - number=2, - ) - uri = proto.Field( - proto.STRING, - number=3, - ) - ets = proto.Field( - proto.INT64, - number=4, - ) - - -class RejoinUserEventsRequest(proto.Message): - r"""Request message for RejoinUserEvents method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event_rejoin_scope (google.cloud.retail_v2.types.RejoinUserEventsRequest.UserEventRejoinScope): - The type of the user event rejoin to define the scope and - range of the user events to be rejoined with the latest - product catalog. Defaults to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not - set, or set to an invalid integer value. - """ - class UserEventRejoinScope(proto.Enum): - r"""The scope of user events to be rejoined with the latest product - catalog. If the rejoining aims at reducing number of unjoined - events, set UserEventRejoinScope to UNJOINED_EVENTS. If the - rejoining aims at correcting product catalog information in joined - events, set UserEventRejoinScope to JOINED_EVENTS. If all events - needs to be rejoined, set UserEventRejoinScope to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. - """ - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 - JOINED_EVENTS = 1 - UNJOINED_EVENTS = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event_rejoin_scope = proto.Field( - proto.ENUM, - number=2, - enum=UserEventRejoinScope, - ) - - -class RejoinUserEventsResponse(proto.Message): - r"""Response message for RejoinUserEvents method. - - Attributes: - rejoined_user_events_count (int): - Number of user events that were joined with - latest product catalog. - """ - - rejoined_user_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -class RejoinUserEventsMetadata(proto.Message): - r"""Metadata for RejoinUserEvents method. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py deleted file mode 100644 index e7ab4118..00000000 --- a/owl-bot-staging/v2/noxfile.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.6", - "3.7", - "3.8", - "3.9", - "3.10", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==19.10b0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.9" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/retail_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py deleted file mode 100644 index fb30eae6..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_GetDefaultBranch_async] -from google.cloud import retail_v2 - - -async def sample_get_default_branch(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py deleted file mode 100644 index 0af0ece9..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_GetDefaultBranch_sync] -from google.cloud import retail_v2 - - -def sample_get_default_branch(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py deleted file mode 100644 index 2a0930de..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_ListCatalogs_async] -from google.cloud import retail_v2 - - -async def sample_list_catalogs(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py deleted file mode 100644 index 2671a121..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_ListCatalogs_sync] -from google.cloud import retail_v2 - - -def sample_list_catalogs(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py deleted file mode 100644 index f85e3ed8..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_SetDefaultBranch_async] -from google.cloud import retail_v2 - - -async def sample_set_default_branch(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - -# [END retail_v2_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py deleted file mode 100644 index 34371062..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_SetDefaultBranch_sync] -from google.cloud import retail_v2 - - -def sample_set_default_branch(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - -# [END retail_v2_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py deleted file mode 100644 index 2a2b3dde..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_UpdateCatalog_async] -from google.cloud import retail_v2 - - -async def sample_update_catalog(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py deleted file mode 100644 index bf721cba..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_UpdateCatalog_sync] -from google.cloud import retail_v2 - - -def sample_update_catalog(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py deleted file mode 100644 index c72ecfdf..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CompletionService_CompleteQuery_async] -from google.cloud import retail_v2 - - -async def sample_complete_query(): - # Create a client - client = retail_v2.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py deleted file mode 100644 index 30b10016..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CompletionService_CompleteQuery_sync] -from google.cloud import retail_v2 - - -def sample_complete_query(): - # Create a client - client = retail_v2.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py deleted file mode 100644 index 75f45f91..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CompletionService_ImportCompletionData_async] -from google.cloud import retail_v2 - - -async def sample_import_completion_data(): - # Create a client - client = retail_v2.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py deleted file mode 100644 index cc31057e..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CompletionService_ImportCompletionData_sync] -from google.cloud import retail_v2 - - -def sample_import_completion_data(): - # Create a client - client = retail_v2.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py deleted file mode 100644 index f46819c5..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_PredictionService_Predict_async] -from google.cloud import retail_v2 - - -async def sample_predict(): - # Create a client - client = retail_v2.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py deleted file mode 100644 index ad37063f..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_PredictionService_Predict_sync] -from google.cloud import retail_v2 - - -def sample_predict(): - # Create a client - client = retail_v2.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py deleted file mode 100644 index ceea2869..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_AddFulfillmentPlaces_async] -from google.cloud import retail_v2 - - -async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py deleted file mode 100644 index 1739ec91..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_AddFulfillmentPlaces_sync] -from google.cloud import retail_v2 - - -def sample_add_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py deleted file mode 100644 index 6155d5ce..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_AddLocalInventories_async] -from google.cloud import retail_v2 - - -async def sample_add_local_inventories(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py deleted file mode 100644 index b57dce2f..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_AddLocalInventories_sync] -from google.cloud import retail_v2 - - -def sample_add_local_inventories(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py deleted file mode 100644 index fe1cb991..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_CreateProduct_async] -from google.cloud import retail_v2 - - -async def sample_create_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py deleted file mode 100644 index 9cc154d9..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_CreateProduct_sync] -from google.cloud import retail_v2 - - -def sample_create_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py deleted file mode 100644 index 33318da7..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_DeleteProduct_async] -from google.cloud import retail_v2 - - -async def sample_delete_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - -# [END retail_v2_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py deleted file mode 100644 index 797690c6..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_DeleteProduct_sync] -from google.cloud import retail_v2 - - -def sample_delete_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - -# [END retail_v2_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py deleted file mode 100644 index 32ba279d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_GetProduct_async] -from google.cloud import retail_v2 - - -async def sample_get_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py deleted file mode 100644 index 62805768..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_GetProduct_sync] -from google.cloud import retail_v2 - - -def sample_get_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py deleted file mode 100644 index 390f0977..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_ImportProducts_async] -from google.cloud import retail_v2 - - -async def sample_import_products(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py deleted file mode 100644 index fcd8c82f..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_ImportProducts_sync] -from google.cloud import retail_v2 - - -def sample_import_products(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py deleted file mode 100644 index 5e85f948..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_ListProducts_async] -from google.cloud import retail_v2 - - -async def sample_list_products(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py deleted file mode 100644 index 30f7fd1f..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_ListProducts_sync] -from google.cloud import retail_v2 - - -def sample_list_products(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py deleted file mode 100644 index 08172bf4..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async] -from google.cloud import retail_v2 - - -async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py deleted file mode 100644 index 37f86ba9..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync] -from google.cloud import retail_v2 - - -def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py deleted file mode 100644 index 762dab6d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_RemoveLocalInventories_async] -from google.cloud import retail_v2 - - -async def sample_remove_local_inventories(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py deleted file mode 100644 index 7aa52d5d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_RemoveLocalInventories_sync] -from google.cloud import retail_v2 - - -def sample_remove_local_inventories(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py deleted file mode 100644 index 62a24100..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_SetInventory_async] -from google.cloud import retail_v2 - - -async def sample_set_inventory(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2.Product() - inventory.title = "title_value" - - request = retail_v2.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py deleted file mode 100644 index aa5a0539..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_SetInventory_sync] -from google.cloud import retail_v2 - - -def sample_set_inventory(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2.Product() - inventory.title = "title_value" - - request = retail_v2.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py deleted file mode 100644 index 9ea76295..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_UpdateProduct_async] -from google.cloud import retail_v2 - - -async def sample_update_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py deleted file mode 100644 index 866c7e7c..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_UpdateProduct_sync] -from google.cloud import retail_v2 - - -def sample_update_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py deleted file mode 100644 index ddebd9e8..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_SearchService_Search_async] -from google.cloud import retail_v2 - - -async def sample_search(): - # Create a client - client = retail_v2.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py deleted file mode 100644 index fc20bb3d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_SearchService_Search_sync] -from google.cloud import retail_v2 - - -def sample_search(): - # Create a client - client = retail_v2.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py deleted file mode 100644 index b8bb6a81..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_CollectUserEvent_async] -from google.cloud import retail_v2 - - -async def sample_collect_user_event(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py deleted file mode 100644 index 10b302e3..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_CollectUserEvent_sync] -from google.cloud import retail_v2 - - -def sample_collect_user_event(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py deleted file mode 100644 index 55ad399a..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_ImportUserEvents_async] -from google.cloud import retail_v2 - - -async def sample_import_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py deleted file mode 100644 index 835edec6..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_ImportUserEvents_sync] -from google.cloud import retail_v2 - - -def sample_import_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py deleted file mode 100644 index 1da1d39d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_PurgeUserEvents_async] -from google.cloud import retail_v2 - - -async def sample_purge_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py deleted file mode 100644 index 48814171..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_PurgeUserEvents_sync] -from google.cloud import retail_v2 - - -def sample_purge_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py deleted file mode 100644 index a2617cfe..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_RejoinUserEvents_async] -from google.cloud import retail_v2 - - -async def sample_rejoin_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py deleted file mode 100644 index eb8ed62c..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_RejoinUserEvents_sync] -from google.cloud import retail_v2 - - -def sample_rejoin_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py deleted file mode 100644 index 82afc25a..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_WriteUserEvent_async] -from google.cloud import retail_v2 - - -async def sample_write_user_event(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py deleted file mode 100644 index 62336b25..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_WriteUserEvent_sync] -from google.cloud import retail_v2 - - -def sample_write_user_event(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json deleted file mode 100644 index c6a55bd4..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json +++ /dev/null @@ -1,3826 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.retail.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-cloud-retail" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2_generated_catalog_service_get_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_GetDefaultBranch_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_get_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2_generated_catalog_service_get_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_GetDefaultBranch_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_get_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ListCatalogsRequest" - }, - { - "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.retail_v2.services.catalog_service.pagers.ListCatalogsAsyncPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2_generated_catalog_service_list_catalogs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_ListCatalogs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_list_catalogs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ListCatalogsRequest" - }, - { - "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.retail_v2.services.catalog_service.pagers.ListCatalogsPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2_generated_catalog_service_list_catalogs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_ListCatalogs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_list_catalogs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2_generated_catalog_service_set_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_SetDefaultBranch_async", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_set_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2_generated_catalog_service_set_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_SetDefaultBranch_sync", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_set_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2.types.Catalog" - }, - { - "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.retail_v2.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2_generated_catalog_service_update_catalog_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_UpdateCatalog_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_update_catalog_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2.types.Catalog" - }, - { - "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.retail_v2.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2_generated_catalog_service_update_catalog_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_UpdateCatalog_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_update_catalog_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2_generated_completion_service_complete_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CompletionService_CompleteQuery_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_completion_service_complete_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2.CompletionServiceClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2_generated_completion_service_complete_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CompletionService_CompleteQuery_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_completion_service_complete_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2_generated_completion_service_import_completion_data_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CompletionService_ImportCompletionData_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_completion_service_import_completion_data_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2.CompletionServiceClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2_generated_completion_service_import_completion_data_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CompletionService_ImportCompletionData_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_completion_service_import_completion_data_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.PredictionServiceAsyncClient", - "shortName": "PredictionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.PredictionServiceAsyncClient.predict", - "method": { - "fullName": "google.cloud.retail.v2.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2_generated_prediction_service_predict_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_PredictionService_Predict_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_prediction_service_predict_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.PredictionServiceClient", - "shortName": "PredictionServiceClient" - }, - "fullName": "google.cloud.retail_v2.PredictionServiceClient.predict", - "method": { - "fullName": "google.cloud.retail.v2.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2_generated_prediction_service_predict_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_PredictionService_Predict_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_prediction_service_predict_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2_generated_product_service_add_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_AddFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_add_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2_generated_product_service_add_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_AddFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_add_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2_generated_product_service_add_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_AddLocalInventories_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_add_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2_generated_product_service_add_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_AddLocalInventories_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_add_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "name": "product_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.retail_v2.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2_generated_product_service_create_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_CreateProduct_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_create_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "name": "product_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.retail_v2.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2_generated_product_service_create_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_CreateProduct_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_create_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2_generated_product_service_delete_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_DeleteProduct_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_delete_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2_generated_product_service_delete_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_DeleteProduct_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_delete_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.GetProductRequest" - }, - { - "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.retail_v2.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2_generated_product_service_get_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_GetProduct_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_get_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.GetProductRequest" - }, - { - "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.retail_v2.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2_generated_product_service_get_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_GetProduct_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_get_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2_generated_product_service_import_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_ImportProducts_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_import_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2_generated_product_service_import_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_ImportProducts_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_import_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ListProductsRequest" - }, - { - "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.retail_v2.services.product_service.pagers.ListProductsAsyncPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2_generated_product_service_list_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_ListProducts_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_list_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ListProductsRequest" - }, - { - "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.retail_v2.services.product_service.pagers.ListProductsPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2_generated_product_service_list_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_ListProducts_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_list_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2_generated_product_service_remove_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_remove_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2_generated_product_service_remove_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_remove_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2_generated_product_service_remove_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_RemoveLocalInventories_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_remove_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2_generated_product_service_remove_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_RemoveLocalInventories_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_remove_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2_generated_product_service_set_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_SetInventory_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_set_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2_generated_product_service_set_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_SetInventory_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_set_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "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.retail_v2.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2_generated_product_service_update_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_UpdateProduct_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_update_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "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.retail_v2.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2_generated_product_service_update_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_UpdateProduct_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_update_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.SearchServiceAsyncClient.search", - "method": { - "fullName": "google.cloud.retail.v2.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2_generated_search_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_SearchService_Search_async", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_search_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.SearchServiceClient", - "shortName": "SearchServiceClient" - }, - "fullName": "google.cloud.retail_v2.SearchServiceClient.search", - "method": { - "fullName": "google.cloud.retail.v2.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.services.search_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2_generated_search_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_SearchService_Search_sync", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_search_service_search_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2_generated_user_event_service_collect_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_CollectUserEvent_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_collect_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2_generated_user_event_service_collect_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_CollectUserEvent_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_collect_user_event_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2_generated_user_event_service_import_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_ImportUserEvents_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_import_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2_generated_user_event_service_import_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_ImportUserEvents_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_import_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2_generated_user_event_service_purge_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_PurgeUserEvents_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_purge_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2_generated_user_event_service_purge_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_PurgeUserEvents_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_purge_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2_generated_user_event_service_rejoin_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_RejoinUserEvents_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_rejoin_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2_generated_user_event_service_rejoin_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_RejoinUserEvents_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_rejoin_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2_generated_user_event_service_write_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_WriteUserEvent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_write_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2_generated_user_event_service_write_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_WriteUserEvent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_write_user_event_sync.py" - } - ] -} diff --git a/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py deleted file mode 100644 index 9ed9d278..00000000 --- a/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py +++ /dev/null @@ -1,199 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class retailCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), - 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), - 'create_product': ('parent', 'product', 'product_id', ), - 'delete_product': ('name', ), - 'get_default_branch': ('catalog', ), - 'get_product': ('name', ), - 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), - 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), - 'import_user_events': ('parent', 'input_config', 'errors_config', ), - 'list_catalogs': ('parent', 'page_size', 'page_token', ), - 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', ), - 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), - 'purge_user_events': ('parent', 'filter', 'force', ), - 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), - 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), - 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), - 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', 'labels', 'spell_correction_spec', ), - 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), - 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), - 'update_catalog': ('catalog', 'update_mask', ), - 'update_product': ('product', 'update_mask', 'allow_missing', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=retailCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the retail client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2/setup.py b/owl-bot-staging/v2/setup.py deleted file mode 100644 index 1103510b..00000000 --- a/owl-bot-staging/v2/setup.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-retail', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-retail", - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 2.8.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'googleapis-common-protos >= 1.55.0, <2.0.0dev', - 'proto-plus >= 1.19.7', - ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py deleted file mode 100644 index 845e18b6..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py +++ /dev/null @@ -1,2318 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.catalog_service import CatalogServiceAsyncClient -from google.cloud.retail_v2.services.catalog_service import CatalogServiceClient -from google.cloud.retail_v2.services.catalog_service import pagers -from google.cloud.retail_v2.services.catalog_service import transports -from google.cloud.retail_v2.types import catalog -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CatalogServiceClient._get_default_mtls_endpoint(None) is None - assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CatalogServiceGrpcTransport, "grpc"), - (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_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", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_catalog_service_client_get_transport_class(): - transport = CatalogServiceClient.get_transport_class() - available_transports = [ - transports.CatalogServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CatalogServiceClient.get_transport_class("grpc") - assert transport == transports.CatalogServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CatalogServiceClient, CatalogServiceAsyncClient -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_catalog_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ListCatalogsRequest, - dict, -]) -def test_list_catalogs(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalogs), - '__call__') as call: - client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - -@pytest.mark.asyncio -async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_catalogs_async_from_dict(): - await test_list_catalogs_async(request_type=dict) - - -def test_list_catalogs_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = catalog_service.ListCatalogsResponse() - client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_catalogs( - 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_catalogs_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_catalogs_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_catalogs( - 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_catalogs_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - - -def test_list_catalogs_pager(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_catalogs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, catalog.Catalog) - for i in results) -def test_list_catalogs_pages(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = list(client.list_catalogs(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_catalogs_async_pager(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_catalogs(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, catalog.Catalog) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_catalogs_async_pages(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCatalogRequest, - dict, -]) -def test_update_catalog(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - ) - response = client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_catalog_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalog), - '__call__') as call: - client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - -@pytest.mark.asyncio -async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_catalog_async_from_dict(): - await test_update_catalog_async(request_type=dict) - - -def test_update_catalog_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = gcr_catalog.Catalog() - client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_catalog_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -def test_update_catalog_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_catalog_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.SetDefaultBranchRequest, - dict, -]) -def test_set_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_set_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_set_default_branch_async_from_dict(): - await test_set_default_branch_async(request_type=dict) - - -def test_set_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = None - client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_set_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_set_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetDefaultBranchRequest, - dict, -]) -def test_get_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - ) - response = client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -def test_get_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_default_branch), - '__call__') as call: - client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - )) - response = await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -@pytest.mark.asyncio -async def test_get_default_branch_async_from_dict(): - await test_get_default_branch_async(request_type=dict) - - -def test_get_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = catalog_service.GetDefaultBranchResponse() - client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_get_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_get_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CatalogServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.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 = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CatalogServiceGrpcTransport, - ) - -def test_catalog_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_catalog_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_catalogs', - 'update_catalog', - 'set_default_branch', - 'get_default_branch', - ) - 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_catalog_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.retail_v2.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport( - 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_catalog_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.retail_v2.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport() - adc.assert_called_once() - - -def test_catalog_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) - CatalogServiceClient() - 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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -def test_catalog_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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - transports.CatalogServiceRestTransport, - ], -) -def test_catalog_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.CatalogServiceGrpcTransport, grpc_helpers), - (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_catalog_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_no_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_with_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_catalog_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcTransport( - 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_catalog_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcAsyncIOTransport( - 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_branch_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = CatalogServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = CatalogServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_branch_path(path) - assert expected == actual - -def test_catalog_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - } - path = CatalogServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CatalogServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = CatalogServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = CatalogServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = CatalogServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CatalogServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = CatalogServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = CatalogServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = CatalogServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = CatalogServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CatalogServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py deleted file mode 100644 index f33a4bad..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py +++ /dev/null @@ -1,1502 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.completion_service import CompletionServiceAsyncClient -from google.cloud.retail_v2.services.completion_service import CompletionServiceClient -from google.cloud.retail_v2.services.completion_service import transports -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CompletionServiceClient._get_default_mtls_endpoint(None) is None - assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CompletionServiceGrpcTransport, "grpc"), - (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_completion_service_client_get_transport_class(): - transport = CompletionServiceClient.get_transport_class() - available_transports = [ - transports.CompletionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CompletionServiceClient.get_transport_class("grpc") - assert transport == transports.CompletionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CompletionServiceClient, CompletionServiceAsyncClient -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_completion_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CompletionServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - ) - response = client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - -@pytest.mark.asyncio -async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - )) - response = await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -@pytest.mark.asyncio -async def test_complete_query_async_from_dict(): - await test_complete_query_async(request_type=dict) - - -def test_complete_query_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = completion_service.CompleteQueryResponse() - client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_complete_query_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) - await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportCompletionDataRequest, - dict, -]) -def test_import_completion_data(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_completion_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - -@pytest.mark.asyncio -async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_completion_data_async_from_dict(): - await test_import_completion_data_async(request_type=dict) - - -def test_import_completion_data_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # 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_completion_data_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CompletionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CompletionServiceGrpcTransport, - ) - -def test_completion_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_completion_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'complete_query', - 'import_completion_data', - ) - 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_completion_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_completion_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport() - adc.assert_called_once() - - -def test_completion_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CompletionServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, - ], -) -def test_completion_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionServiceGrpcTransport, grpc_helpers), - (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_completion_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_no_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_with_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_completion_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_completion_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_completion_service_grpc_lro_client(): - client = CompletionServiceClient( - 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_completion_service_grpc_lro_async_client(): - client = CompletionServiceAsyncClient( - 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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CompletionServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CompletionServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CompletionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CompletionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = CompletionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CompletionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CompletionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CompletionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = CompletionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CompletionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CompletionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CompletionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CompletionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py deleted file mode 100644 index fdbb2eeb..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py +++ /dev/null @@ -1,1330 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.prediction_service import PredictionServiceAsyncClient -from google.cloud.retail_v2.services.prediction_service import PredictionServiceClient -from google.cloud.retail_v2.services.prediction_service import transports -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import prediction_service -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import promotion -from google.cloud.retail_v2.types import user_event -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PredictionServiceClient._get_default_mtls_endpoint(None) is None - assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PredictionServiceGrpcTransport, "grpc"), - (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_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", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_prediction_service_client_get_transport_class(): - transport = PredictionServiceClient.get_transport_class() - available_transports = [ - transports.PredictionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = PredictionServiceClient.get_transport_class("grpc") - assert transport == transports.PredictionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - PredictionServiceClient, PredictionServiceAsyncClient -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_prediction_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - prediction_service.PredictRequest, - dict, -]) -def test_predict(request_type, transport: str = 'grpc'): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - response = client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - -@pytest.mark.asyncio -async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - )) - response = await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -@pytest.mark.asyncio -async def test_predict_async_from_dict(): - await test_predict_async(request_type=dict) - - -def test_predict_field_headers(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = prediction_service.PredictResponse() - client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_predict_field_headers_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) - await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PredictionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PredictionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.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 = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, - ) - -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'predict', - ) - 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport( - 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport() - adc.assert_called_once() - - -def test_prediction_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) - PredictionServiceClient() - 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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -def test_prediction_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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - transports.PredictionServiceRestTransport, - ], -) -def test_prediction_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.PredictionServiceGrpcTransport, grpc_helpers), - (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_prediction_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_no_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_with_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_prediction_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcTransport( - 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_prediction_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcAsyncIOTransport( - 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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_product_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - product = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - "branch": "winkle", - "product": "nautilus", - } - path = PredictionServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PredictionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = PredictionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = PredictionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = PredictionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PredictionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = PredictionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = PredictionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = PredictionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = PredictionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PredictionServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py deleted file mode 100644 index 6bb6b078..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py +++ /dev/null @@ -1,4136 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.product_service import ProductServiceAsyncClient -from google.cloud.retail_v2.services.product_service import ProductServiceClient -from google.cloud.retail_v2.services.product_service import pagers -from google.cloud.retail_v2.services.product_service import transports -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.cloud.retail_v2.types import promotion -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ProductServiceClient._get_default_mtls_endpoint(None) is None - assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ProductServiceGrpcTransport, "grpc"), - (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_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", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_product_service_client_get_transport_class(): - transport = ProductServiceClient.get_transport_class() - available_transports = [ - transports.ProductServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ProductServiceClient.get_transport_class("grpc") - assert transport == transports.ProductServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_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(ProductServiceClient, '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(ProductServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ProductServiceClient, ProductServiceAsyncClient -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_product_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.CreateProductRequest, - dict, -]) -def test_create_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_create_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - -@pytest.mark.asyncio -async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_create_product_async_from_dict(): - await test_create_product_async(request_type=dict) - - -def test_create_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - - -def test_create_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - -@pytest.mark.asyncio -async def test_create_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.GetProductRequest, - dict, -]) -def test_get_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_get_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - -@pytest.mark.asyncio -async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_get_product_async_from_dict(): - await test_get_product_async(request_type=dict) - - -def test_get_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = product.Product() - client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.GetProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.GetProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.ListProductsRequest, - dict, -]) -def test_list_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - -@pytest.mark.asyncio -async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_products_async_from_dict(): - await test_list_products_async(request_type=dict) - - -def test_list_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = product_service.ListProductsResponse() - client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_products( - 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_products_flattened_error(): - client = ProductServiceClient( - credentials=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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_products_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_products( - 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_products_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - - -def test_list_products_pager(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_products(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, product.Product) - for i in results) -def test_list_products_pages(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = list(client.list_products(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_products_async_pager(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_products(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, product.Product) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_products_async_pages(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_products(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - product_service.UpdateProductRequest, - dict, -]) -def test_update_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_update_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - -@pytest.mark.asyncio -async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_update_product_async_from_dict(): - await test_update_product_async(request_type=dict) - - -def test_update_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -def test_update_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.DeleteProductRequest, - dict, -]) -def test_delete_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - -@pytest.mark.asyncio -async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_product_async_from_dict(): - await test_delete_product_async(request_type=dict) - - -def test_delete_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = None - client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportProductsRequest, - dict, -]) -def test_import_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - -@pytest.mark.asyncio -async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__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_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_products_async_from_dict(): - await test_import_products_async(request_type=dict) - - -def test_import_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - product_service.SetInventoryRequest, - dict, -]) -def test_set_inventory(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_inventory_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - -@pytest.mark.asyncio -async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_inventory_async_from_dict(): - await test_set_inventory_async(request_type=dict) - - -def test_set_inventory_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_inventory_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -def test_set_inventory_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_set_inventory_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_set_inventory_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_inventory_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddFulfillmentPlacesRequest, - dict, -]) -def test_add_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async_from_dict(): - await test_add_fulfillment_places_async(request_type=dict) - - -def test_add_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveFulfillmentPlacesRequest, - dict, -]) -def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async_from_dict(): - await test_remove_fulfillment_places_async(request_type=dict) - - -def test_remove_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddLocalInventoriesRequest, - dict, -]) -def test_add_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_local_inventories_async_from_dict(): - await test_add_local_inventories_async(request_type=dict) - - -def test_add_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveLocalInventoriesRequest, - dict, -]) -def test_remove_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_local_inventories_async_from_dict(): - await test_remove_local_inventories_async(request_type=dict) - - -def test_remove_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProductServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ProductServiceClient.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 = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProductServiceGrpcTransport, - ) - -def test_product_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_product_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.product_service.transports.ProductServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_product', - 'get_product', - 'list_products', - 'update_product', - 'delete_product', - 'import_products', - 'set_inventory', - 'add_fulfillment_places', - 'remove_fulfillment_places', - 'add_local_inventories', - 'remove_local_inventories', - ) - 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_product_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.retail_v2.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport( - 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_product_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.retail_v2.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport() - adc.assert_called_once() - - -def test_product_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) - ProductServiceClient() - 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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - ], -) -def test_product_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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - transports.ProductServiceRestTransport, - ], -) -def test_product_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.ProductServiceGrpcTransport, grpc_helpers), - (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_product_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_no_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_with_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_product_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcTransport( - 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_product_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcAsyncIOTransport( - 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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_product_service_grpc_lro_client(): - client = ProductServiceClient( - 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_product_service_grpc_lro_async_client(): - client = ProductServiceAsyncClient( - 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" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = ProductServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = ProductServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = ProductServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = ProductServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProductServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ProductServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProductServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ProductServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProductServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ProductServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ProductServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ProductServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ProductServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ProductServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ProductServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py deleted file mode 100644 index c9858027..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py +++ /dev/null @@ -1,1547 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.search_service import SearchServiceAsyncClient -from google.cloud.retail_v2.services.search_service import SearchServiceClient -from google.cloud.retail_v2.services.search_service import pagers -from google.cloud.retail_v2.services.search_service import transports -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import search_service -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SearchServiceClient._get_default_mtls_endpoint(None) is None - assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SearchServiceGrpcTransport, "grpc"), - (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_search_service_client_get_transport_class(): - transport = SearchServiceClient.get_transport_class() - available_transports = [ - transports.SearchServiceGrpcTransport, - ] - assert transport in available_transports - - transport = SearchServiceClient.get_transport_class("grpc") - assert transport == transports.SearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SearchServiceClient, SearchServiceAsyncClient -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SearchServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - search_service.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - - -def test_search_field_headers(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = search_service.SearchResponse() - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_field_headers_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_search_pager(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('placement', ''), - )), - ) - pager = client.search(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_async_pager(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, - ) - -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_search_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_search_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport() - adc.assert_called_once() - - -def test_search_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SearchServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - transports.SearchServiceRestTransport, - ], -) -def test_search_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SearchServiceGrpcTransport, grpc_helpers), - (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_search_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_no_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_with_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_branch_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = SearchServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = SearchServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = SearchServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = SearchServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py deleted file mode 100644 index 4dc04e51..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py +++ /dev/null @@ -1,2039 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.retail_v2.services.user_event_service import UserEventServiceClient -from google.cloud.retail_v2.services.user_event_service import transports -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import promotion -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, UserEventServiceAsyncClient -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - ) - response = client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = user_event.UserEvent() - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) - await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeUserEventsRequest, - dict, -]) -def test_purge_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - -@pytest.mark.asyncio -async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_user_events_async_from_dict(): - await test_purge_user_events_async(request_type=dict) - - -def test_purge_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_purge_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.RejoinUserEventsRequest, - dict, -]) -def test_rejoin_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_rejoin_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - -@pytest.mark.asyncio -async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_rejoin_user_events_async_from_dict(): - await test_rejoin_user_events_async(request_type=dict) - - -def test_rejoin_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_rejoin_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'purge_user_events', - 'import_user_events', - 'rejoin_user_events', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_user_event_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_user_event_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -def test_user_event_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - UserEventServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, - ], -) -def test_user_event_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_no_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_with_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = UserEventServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = UserEventServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_product_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - product = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - "branch": "whelk", - "product": "octopus", - } - path = UserEventServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/.coveragerc b/owl-bot-staging/v2alpha/.coveragerc deleted file mode 100644 index a8b114f0..00000000 --- a/owl-bot-staging/v2alpha/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/retail/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2alpha/.flake8 b/owl-bot-staging/v2alpha/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v2alpha/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2alpha/MANIFEST.in b/owl-bot-staging/v2alpha/MANIFEST.in deleted file mode 100644 index 3ee710cc..00000000 --- a/owl-bot-staging/v2alpha/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/retail *.py -recursive-include google/cloud/retail_v2alpha *.py diff --git a/owl-bot-staging/v2alpha/README.rst b/owl-bot-staging/v2alpha/README.rst deleted file mode 100644 index cb039760..00000000 --- a/owl-bot-staging/v2alpha/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Retail API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Retail API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2alpha/docs/conf.py b/owl-bot-staging/v2alpha/docs/conf.py deleted file mode 100644 index 5be9eb4b..00000000 --- a/owl-bot-staging/v2alpha/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-retail documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-retail" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-retail-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-retail.tex", - u"google-cloud-retail Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-retail", - u"Google Cloud Retail Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-retail", - u"google-cloud-retail Documentation", - author, - "google-cloud-retail", - "GAPIC library for Google Cloud Retail API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2alpha/docs/index.rst b/owl-bot-staging/v2alpha/docs/index.rst deleted file mode 100644 index dc0a2096..00000000 --- a/owl-bot-staging/v2alpha/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - retail_v2alpha/services - retail_v2alpha/types diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst deleted file mode 100644 index 745d0cf4..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CatalogService --------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.catalog_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.catalog_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst deleted file mode 100644 index 3a276433..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CompletionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2alpha.services.completion_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst deleted file mode 100644 index 36aaf9b6..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ControlService --------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.control_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.control_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst deleted file mode 100644 index b659cf98..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -PredictionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2alpha.services.prediction_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst deleted file mode 100644 index acbb336e..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ProductService --------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.product_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.product_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst deleted file mode 100644 index ad4c486d..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SearchService -------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst deleted file mode 100644 index edeb8cfc..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst +++ /dev/null @@ -1,13 +0,0 @@ -Services for Google Cloud Retail v2alpha API -============================================ -.. toctree:: - :maxdepth: 2 - - catalog_service - completion_service - control_service - prediction_service - product_service - search_service - serving_config_service - user_event_service diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst deleted file mode 100644 index c1516860..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ServingConfigService --------------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.serving_config_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.serving_config_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst deleted file mode 100644 index c1445ad6..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Retail v2alpha API -========================================= - -.. automodule:: google.cloud.retail_v2alpha.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst deleted file mode 100644 index 8c56485c..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.user_event_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py deleted file mode 100644 index a17a283b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py +++ /dev/null @@ -1,281 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.retail_v2alpha.services.catalog_service.client import CatalogServiceClient -from google.cloud.retail_v2alpha.services.catalog_service.async_client import CatalogServiceAsyncClient -from google.cloud.retail_v2alpha.services.completion_service.client import CompletionServiceClient -from google.cloud.retail_v2alpha.services.completion_service.async_client import CompletionServiceAsyncClient -from google.cloud.retail_v2alpha.services.control_service.client import ControlServiceClient -from google.cloud.retail_v2alpha.services.control_service.async_client import ControlServiceAsyncClient -from google.cloud.retail_v2alpha.services.prediction_service.client import PredictionServiceClient -from google.cloud.retail_v2alpha.services.prediction_service.async_client import PredictionServiceAsyncClient -from google.cloud.retail_v2alpha.services.product_service.client import ProductServiceClient -from google.cloud.retail_v2alpha.services.product_service.async_client import ProductServiceAsyncClient -from google.cloud.retail_v2alpha.services.search_service.client import SearchServiceClient -from google.cloud.retail_v2alpha.services.search_service.async_client import SearchServiceAsyncClient -from google.cloud.retail_v2alpha.services.serving_config_service.client import ServingConfigServiceClient -from google.cloud.retail_v2alpha.services.serving_config_service.async_client import ServingConfigServiceAsyncClient -from google.cloud.retail_v2alpha.services.user_event_service.client import UserEventServiceClient -from google.cloud.retail_v2alpha.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.retail_v2alpha.types.catalog import AttributesConfig -from google.cloud.retail_v2alpha.types.catalog import Catalog -from google.cloud.retail_v2alpha.types.catalog import CatalogAttribute -from google.cloud.retail_v2alpha.types.catalog import CompletionConfig -from google.cloud.retail_v2alpha.types.catalog import MerchantCenterLink -from google.cloud.retail_v2alpha.types.catalog import MerchantCenterLinkingConfig -from google.cloud.retail_v2alpha.types.catalog import ProductLevelConfig -from google.cloud.retail_v2alpha.types.catalog_service import AddCatalogAttributeRequest -from google.cloud.retail_v2alpha.types.catalog_service import GetAttributesConfigRequest -from google.cloud.retail_v2alpha.types.catalog_service import GetCompletionConfigRequest -from google.cloud.retail_v2alpha.types.catalog_service import GetDefaultBranchRequest -from google.cloud.retail_v2alpha.types.catalog_service import GetDefaultBranchResponse -from google.cloud.retail_v2alpha.types.catalog_service import ListCatalogsRequest -from google.cloud.retail_v2alpha.types.catalog_service import ListCatalogsResponse -from google.cloud.retail_v2alpha.types.catalog_service import RemoveCatalogAttributeRequest -from google.cloud.retail_v2alpha.types.catalog_service import ReplaceCatalogAttributeRequest -from google.cloud.retail_v2alpha.types.catalog_service import SetDefaultBranchRequest -from google.cloud.retail_v2alpha.types.catalog_service import UpdateAttributesConfigRequest -from google.cloud.retail_v2alpha.types.catalog_service import UpdateCatalogRequest -from google.cloud.retail_v2alpha.types.catalog_service import UpdateCompletionConfigRequest -from google.cloud.retail_v2alpha.types.common import Audience -from google.cloud.retail_v2alpha.types.common import ColorInfo -from google.cloud.retail_v2alpha.types.common import Condition -from google.cloud.retail_v2alpha.types.common import CustomAttribute -from google.cloud.retail_v2alpha.types.common import FulfillmentInfo -from google.cloud.retail_v2alpha.types.common import Image -from google.cloud.retail_v2alpha.types.common import Interval -from google.cloud.retail_v2alpha.types.common import LocalInventory -from google.cloud.retail_v2alpha.types.common import PriceInfo -from google.cloud.retail_v2alpha.types.common import Rating -from google.cloud.retail_v2alpha.types.common import Rule -from google.cloud.retail_v2alpha.types.common import UserInfo -from google.cloud.retail_v2alpha.types.common import AttributeConfigLevel -from google.cloud.retail_v2alpha.types.common import SearchSolutionUseCase -from google.cloud.retail_v2alpha.types.common import SolutionType -from google.cloud.retail_v2alpha.types.completion_service import CompleteQueryRequest -from google.cloud.retail_v2alpha.types.completion_service import CompleteQueryResponse -from google.cloud.retail_v2alpha.types.control import Control -from google.cloud.retail_v2alpha.types.control_service import CreateControlRequest -from google.cloud.retail_v2alpha.types.control_service import DeleteControlRequest -from google.cloud.retail_v2alpha.types.control_service import GetControlRequest -from google.cloud.retail_v2alpha.types.control_service import ListControlsRequest -from google.cloud.retail_v2alpha.types.control_service import ListControlsResponse -from google.cloud.retail_v2alpha.types.control_service import UpdateControlRequest -from google.cloud.retail_v2alpha.types.export_config import ExportErrorsConfig -from google.cloud.retail_v2alpha.types.export_config import ExportMetadata -from google.cloud.retail_v2alpha.types.export_config import ExportProductsResponse -from google.cloud.retail_v2alpha.types.export_config import ExportUserEventsResponse -from google.cloud.retail_v2alpha.types.import_config import BigQuerySource -from google.cloud.retail_v2alpha.types.import_config import CompletionDataInputConfig -from google.cloud.retail_v2alpha.types.import_config import GcsSource -from google.cloud.retail_v2alpha.types.import_config import ImportCompletionDataRequest -from google.cloud.retail_v2alpha.types.import_config import ImportCompletionDataResponse -from google.cloud.retail_v2alpha.types.import_config import ImportErrorsConfig -from google.cloud.retail_v2alpha.types.import_config import ImportMetadata -from google.cloud.retail_v2alpha.types.import_config import ImportProductsRequest -from google.cloud.retail_v2alpha.types.import_config import ImportProductsResponse -from google.cloud.retail_v2alpha.types.import_config import ImportUserEventsRequest -from google.cloud.retail_v2alpha.types.import_config import ImportUserEventsResponse -from google.cloud.retail_v2alpha.types.import_config import ProductInlineSource -from google.cloud.retail_v2alpha.types.import_config import ProductInputConfig -from google.cloud.retail_v2alpha.types.import_config import UserEventImportSummary -from google.cloud.retail_v2alpha.types.import_config import UserEventInlineSource -from google.cloud.retail_v2alpha.types.import_config import UserEventInputConfig -from google.cloud.retail_v2alpha.types.prediction_service import PredictRequest -from google.cloud.retail_v2alpha.types.prediction_service import PredictResponse -from google.cloud.retail_v2alpha.types.product import Product -from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesMetadata -from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesRequest -from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesResponse -from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesMetadata -from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesRequest -from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesResponse -from google.cloud.retail_v2alpha.types.product_service import CreateProductRequest -from google.cloud.retail_v2alpha.types.product_service import DeleteProductRequest -from google.cloud.retail_v2alpha.types.product_service import GetProductRequest -from google.cloud.retail_v2alpha.types.product_service import ListProductsRequest -from google.cloud.retail_v2alpha.types.product_service import ListProductsResponse -from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesMetadata -from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesRequest -from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesResponse -from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesMetadata -from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesRequest -from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesResponse -from google.cloud.retail_v2alpha.types.product_service import SetInventoryMetadata -from google.cloud.retail_v2alpha.types.product_service import SetInventoryRequest -from google.cloud.retail_v2alpha.types.product_service import SetInventoryResponse -from google.cloud.retail_v2alpha.types.product_service import UpdateProductRequest -from google.cloud.retail_v2alpha.types.promotion import Promotion -from google.cloud.retail_v2alpha.types.purge_config import PurgeMetadata -from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsMetadata -from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsRequest -from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsResponse -from google.cloud.retail_v2alpha.types.purge_config import PurgeUserEventsRequest -from google.cloud.retail_v2alpha.types.purge_config import PurgeUserEventsResponse -from google.cloud.retail_v2alpha.types.search_service import SearchRequest -from google.cloud.retail_v2alpha.types.search_service import SearchResponse -from google.cloud.retail_v2alpha.types.serving_config import ServingConfig -from google.cloud.retail_v2alpha.types.serving_config_service import AddControlRequest -from google.cloud.retail_v2alpha.types.serving_config_service import CreateServingConfigRequest -from google.cloud.retail_v2alpha.types.serving_config_service import DeleteServingConfigRequest -from google.cloud.retail_v2alpha.types.serving_config_service import GetServingConfigRequest -from google.cloud.retail_v2alpha.types.serving_config_service import ListServingConfigsRequest -from google.cloud.retail_v2alpha.types.serving_config_service import ListServingConfigsResponse -from google.cloud.retail_v2alpha.types.serving_config_service import RemoveControlRequest -from google.cloud.retail_v2alpha.types.serving_config_service import UpdateServingConfigRequest -from google.cloud.retail_v2alpha.types.user_event import CompletionDetail -from google.cloud.retail_v2alpha.types.user_event import ProductDetail -from google.cloud.retail_v2alpha.types.user_event import PurchaseTransaction -from google.cloud.retail_v2alpha.types.user_event import UserEvent -from google.cloud.retail_v2alpha.types.user_event_service import CollectUserEventRequest -from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsMetadata -from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsRequest -from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsResponse -from google.cloud.retail_v2alpha.types.user_event_service import WriteUserEventRequest - -__all__ = ('CatalogServiceClient', - 'CatalogServiceAsyncClient', - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', - 'ControlServiceClient', - 'ControlServiceAsyncClient', - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', - 'ProductServiceClient', - 'ProductServiceAsyncClient', - 'SearchServiceClient', - 'SearchServiceAsyncClient', - 'ServingConfigServiceClient', - 'ServingConfigServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'AttributesConfig', - 'Catalog', - 'CatalogAttribute', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'ProductLevelConfig', - 'AddCatalogAttributeRequest', - 'GetAttributesConfigRequest', - 'GetCompletionConfigRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - 'SetDefaultBranchRequest', - 'UpdateAttributesConfigRequest', - 'UpdateCatalogRequest', - 'UpdateCompletionConfigRequest', - 'Audience', - 'ColorInfo', - 'Condition', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'Rule', - 'UserInfo', - 'AttributeConfigLevel', - 'SearchSolutionUseCase', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Control', - 'CreateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - 'UpdateControlRequest', - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeProductsMetadata', - 'PurgeProductsRequest', - 'PurgeProductsResponse', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'ServingConfig', - 'AddControlRequest', - 'CreateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'RemoveControlRequest', - 'UpdateServingConfigRequest', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail/py.typed b/owl-bot-staging/v2alpha/google/cloud/retail/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py deleted file mode 100644 index e515a173..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py +++ /dev/null @@ -1,282 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.catalog_service import CatalogServiceClient -from .services.catalog_service import CatalogServiceAsyncClient -from .services.completion_service import CompletionServiceClient -from .services.completion_service import CompletionServiceAsyncClient -from .services.control_service import ControlServiceClient -from .services.control_service import ControlServiceAsyncClient -from .services.prediction_service import PredictionServiceClient -from .services.prediction_service import PredictionServiceAsyncClient -from .services.product_service import ProductServiceClient -from .services.product_service import ProductServiceAsyncClient -from .services.search_service import SearchServiceClient -from .services.search_service import SearchServiceAsyncClient -from .services.serving_config_service import ServingConfigServiceClient -from .services.serving_config_service import ServingConfigServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.catalog import AttributesConfig -from .types.catalog import Catalog -from .types.catalog import CatalogAttribute -from .types.catalog import CompletionConfig -from .types.catalog import MerchantCenterLink -from .types.catalog import MerchantCenterLinkingConfig -from .types.catalog import ProductLevelConfig -from .types.catalog_service import AddCatalogAttributeRequest -from .types.catalog_service import GetAttributesConfigRequest -from .types.catalog_service import GetCompletionConfigRequest -from .types.catalog_service import GetDefaultBranchRequest -from .types.catalog_service import GetDefaultBranchResponse -from .types.catalog_service import ListCatalogsRequest -from .types.catalog_service import ListCatalogsResponse -from .types.catalog_service import RemoveCatalogAttributeRequest -from .types.catalog_service import ReplaceCatalogAttributeRequest -from .types.catalog_service import SetDefaultBranchRequest -from .types.catalog_service import UpdateAttributesConfigRequest -from .types.catalog_service import UpdateCatalogRequest -from .types.catalog_service import UpdateCompletionConfigRequest -from .types.common import Audience -from .types.common import ColorInfo -from .types.common import Condition -from .types.common import CustomAttribute -from .types.common import FulfillmentInfo -from .types.common import Image -from .types.common import Interval -from .types.common import LocalInventory -from .types.common import PriceInfo -from .types.common import Rating -from .types.common import Rule -from .types.common import UserInfo -from .types.common import AttributeConfigLevel -from .types.common import SearchSolutionUseCase -from .types.common import SolutionType -from .types.completion_service import CompleteQueryRequest -from .types.completion_service import CompleteQueryResponse -from .types.control import Control -from .types.control_service import CreateControlRequest -from .types.control_service import DeleteControlRequest -from .types.control_service import GetControlRequest -from .types.control_service import ListControlsRequest -from .types.control_service import ListControlsResponse -from .types.control_service import UpdateControlRequest -from .types.export_config import ExportErrorsConfig -from .types.export_config import ExportMetadata -from .types.export_config import ExportProductsResponse -from .types.export_config import ExportUserEventsResponse -from .types.import_config import BigQuerySource -from .types.import_config import CompletionDataInputConfig -from .types.import_config import GcsSource -from .types.import_config import ImportCompletionDataRequest -from .types.import_config import ImportCompletionDataResponse -from .types.import_config import ImportErrorsConfig -from .types.import_config import ImportMetadata -from .types.import_config import ImportProductsRequest -from .types.import_config import ImportProductsResponse -from .types.import_config import ImportUserEventsRequest -from .types.import_config import ImportUserEventsResponse -from .types.import_config import ProductInlineSource -from .types.import_config import ProductInputConfig -from .types.import_config import UserEventImportSummary -from .types.import_config import UserEventInlineSource -from .types.import_config import UserEventInputConfig -from .types.prediction_service import PredictRequest -from .types.prediction_service import PredictResponse -from .types.product import Product -from .types.product_service import AddFulfillmentPlacesMetadata -from .types.product_service import AddFulfillmentPlacesRequest -from .types.product_service import AddFulfillmentPlacesResponse -from .types.product_service import AddLocalInventoriesMetadata -from .types.product_service import AddLocalInventoriesRequest -from .types.product_service import AddLocalInventoriesResponse -from .types.product_service import CreateProductRequest -from .types.product_service import DeleteProductRequest -from .types.product_service import GetProductRequest -from .types.product_service import ListProductsRequest -from .types.product_service import ListProductsResponse -from .types.product_service import RemoveFulfillmentPlacesMetadata -from .types.product_service import RemoveFulfillmentPlacesRequest -from .types.product_service import RemoveFulfillmentPlacesResponse -from .types.product_service import RemoveLocalInventoriesMetadata -from .types.product_service import RemoveLocalInventoriesRequest -from .types.product_service import RemoveLocalInventoriesResponse -from .types.product_service import SetInventoryMetadata -from .types.product_service import SetInventoryRequest -from .types.product_service import SetInventoryResponse -from .types.product_service import UpdateProductRequest -from .types.promotion import Promotion -from .types.purge_config import PurgeMetadata -from .types.purge_config import PurgeProductsMetadata -from .types.purge_config import PurgeProductsRequest -from .types.purge_config import PurgeProductsResponse -from .types.purge_config import PurgeUserEventsRequest -from .types.purge_config import PurgeUserEventsResponse -from .types.search_service import SearchRequest -from .types.search_service import SearchResponse -from .types.serving_config import ServingConfig -from .types.serving_config_service import AddControlRequest -from .types.serving_config_service import CreateServingConfigRequest -from .types.serving_config_service import DeleteServingConfigRequest -from .types.serving_config_service import GetServingConfigRequest -from .types.serving_config_service import ListServingConfigsRequest -from .types.serving_config_service import ListServingConfigsResponse -from .types.serving_config_service import RemoveControlRequest -from .types.serving_config_service import UpdateServingConfigRequest -from .types.user_event import CompletionDetail -from .types.user_event import ProductDetail -from .types.user_event import PurchaseTransaction -from .types.user_event import UserEvent -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import RejoinUserEventsMetadata -from .types.user_event_service import RejoinUserEventsRequest -from .types.user_event_service import RejoinUserEventsResponse -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CatalogServiceAsyncClient', - 'CompletionServiceAsyncClient', - 'ControlServiceAsyncClient', - 'PredictionServiceAsyncClient', - 'ProductServiceAsyncClient', - 'SearchServiceAsyncClient', - 'ServingConfigServiceAsyncClient', - 'UserEventServiceAsyncClient', -'AddCatalogAttributeRequest', -'AddControlRequest', -'AddFulfillmentPlacesMetadata', -'AddFulfillmentPlacesRequest', -'AddFulfillmentPlacesResponse', -'AddLocalInventoriesMetadata', -'AddLocalInventoriesRequest', -'AddLocalInventoriesResponse', -'AttributeConfigLevel', -'AttributesConfig', -'Audience', -'BigQuerySource', -'Catalog', -'CatalogAttribute', -'CatalogServiceClient', -'CollectUserEventRequest', -'ColorInfo', -'CompleteQueryRequest', -'CompleteQueryResponse', -'CompletionConfig', -'CompletionDataInputConfig', -'CompletionDetail', -'CompletionServiceClient', -'Condition', -'Control', -'ControlServiceClient', -'CreateControlRequest', -'CreateProductRequest', -'CreateServingConfigRequest', -'CustomAttribute', -'DeleteControlRequest', -'DeleteProductRequest', -'DeleteServingConfigRequest', -'ExportErrorsConfig', -'ExportMetadata', -'ExportProductsResponse', -'ExportUserEventsResponse', -'FulfillmentInfo', -'GcsSource', -'GetAttributesConfigRequest', -'GetCompletionConfigRequest', -'GetControlRequest', -'GetDefaultBranchRequest', -'GetDefaultBranchResponse', -'GetProductRequest', -'GetServingConfigRequest', -'Image', -'ImportCompletionDataRequest', -'ImportCompletionDataResponse', -'ImportErrorsConfig', -'ImportMetadata', -'ImportProductsRequest', -'ImportProductsResponse', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'Interval', -'ListCatalogsRequest', -'ListCatalogsResponse', -'ListControlsRequest', -'ListControlsResponse', -'ListProductsRequest', -'ListProductsResponse', -'ListServingConfigsRequest', -'ListServingConfigsResponse', -'LocalInventory', -'MerchantCenterLink', -'MerchantCenterLinkingConfig', -'PredictRequest', -'PredictResponse', -'PredictionServiceClient', -'PriceInfo', -'Product', -'ProductDetail', -'ProductInlineSource', -'ProductInputConfig', -'ProductLevelConfig', -'ProductServiceClient', -'Promotion', -'PurchaseTransaction', -'PurgeMetadata', -'PurgeProductsMetadata', -'PurgeProductsRequest', -'PurgeProductsResponse', -'PurgeUserEventsRequest', -'PurgeUserEventsResponse', -'Rating', -'RejoinUserEventsMetadata', -'RejoinUserEventsRequest', -'RejoinUserEventsResponse', -'RemoveCatalogAttributeRequest', -'RemoveControlRequest', -'RemoveFulfillmentPlacesMetadata', -'RemoveFulfillmentPlacesRequest', -'RemoveFulfillmentPlacesResponse', -'RemoveLocalInventoriesMetadata', -'RemoveLocalInventoriesRequest', -'RemoveLocalInventoriesResponse', -'ReplaceCatalogAttributeRequest', -'Rule', -'SearchRequest', -'SearchResponse', -'SearchServiceClient', -'SearchSolutionUseCase', -'ServingConfig', -'ServingConfigServiceClient', -'SetDefaultBranchRequest', -'SetInventoryMetadata', -'SetInventoryRequest', -'SetInventoryResponse', -'SolutionType', -'UpdateAttributesConfigRequest', -'UpdateCatalogRequest', -'UpdateCompletionConfigRequest', -'UpdateControlRequest', -'UpdateProductRequest', -'UpdateServingConfigRequest', -'UserEvent', -'UserEventImportSummary', -'UserEventInlineSource', -'UserEventInputConfig', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json deleted file mode 100644 index 543e36d6..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json +++ /dev/null @@ -1,561 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.retail_v2alpha", - "protoPackage": "google.cloud.retail.v2alpha", - "schema": "1.0", - "services": { - "CatalogService": { - "clients": { - "grpc": { - "libraryClient": "CatalogServiceClient", - "rpcs": { - "AddCatalogAttribute": { - "methods": [ - "add_catalog_attribute" - ] - }, - "GetAttributesConfig": { - "methods": [ - "get_attributes_config" - ] - }, - "GetCompletionConfig": { - "methods": [ - "get_completion_config" - ] - }, - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "RemoveCatalogAttribute": { - "methods": [ - "remove_catalog_attribute" - ] - }, - "ReplaceCatalogAttribute": { - "methods": [ - "replace_catalog_attribute" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateAttributesConfig": { - "methods": [ - "update_attributes_config" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - }, - "UpdateCompletionConfig": { - "methods": [ - "update_completion_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CatalogServiceAsyncClient", - "rpcs": { - "AddCatalogAttribute": { - "methods": [ - "add_catalog_attribute" - ] - }, - "GetAttributesConfig": { - "methods": [ - "get_attributes_config" - ] - }, - "GetCompletionConfig": { - "methods": [ - "get_completion_config" - ] - }, - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "RemoveCatalogAttribute": { - "methods": [ - "remove_catalog_attribute" - ] - }, - "ReplaceCatalogAttribute": { - "methods": [ - "replace_catalog_attribute" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateAttributesConfig": { - "methods": [ - "update_attributes_config" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - }, - "UpdateCompletionConfig": { - "methods": [ - "update_completion_config" - ] - } - } - } - } - }, - "CompletionService": { - "clients": { - "grpc": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CompletionServiceAsyncClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - } - } - }, - "ControlService": { - "clients": { - "grpc": { - "libraryClient": "ControlServiceClient", - "rpcs": { - "CreateControl": { - "methods": [ - "create_control" - ] - }, - "DeleteControl": { - "methods": [ - "delete_control" - ] - }, - "GetControl": { - "methods": [ - "get_control" - ] - }, - "ListControls": { - "methods": [ - "list_controls" - ] - }, - "UpdateControl": { - "methods": [ - "update_control" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ControlServiceAsyncClient", - "rpcs": { - "CreateControl": { - "methods": [ - "create_control" - ] - }, - "DeleteControl": { - "methods": [ - "delete_control" - ] - }, - "GetControl": { - "methods": [ - "get_control" - ] - }, - "ListControls": { - "methods": [ - "list_controls" - ] - }, - "UpdateControl": { - "methods": [ - "update_control" - ] - } - } - } - } - }, - "PredictionService": { - "clients": { - "grpc": { - "libraryClient": "PredictionServiceClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PredictionServiceAsyncClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - } - } - }, - "ProductService": { - "clients": { - "grpc": { - "libraryClient": "ProductServiceClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "PurgeProducts": { - "methods": [ - "purge_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProductServiceAsyncClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "PurgeProducts": { - "methods": [ - "purge_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - } - } - }, - "SearchService": { - "clients": { - "grpc": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SearchServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - }, - "ServingConfigService": { - "clients": { - "grpc": { - "libraryClient": "ServingConfigServiceClient", - "rpcs": { - "AddControl": { - "methods": [ - "add_control" - ] - }, - "CreateServingConfig": { - "methods": [ - "create_serving_config" - ] - }, - "DeleteServingConfig": { - "methods": [ - "delete_serving_config" - ] - }, - "GetServingConfig": { - "methods": [ - "get_serving_config" - ] - }, - "ListServingConfigs": { - "methods": [ - "list_serving_configs" - ] - }, - "RemoveControl": { - "methods": [ - "remove_control" - ] - }, - "UpdateServingConfig": { - "methods": [ - "update_serving_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ServingConfigServiceAsyncClient", - "rpcs": { - "AddControl": { - "methods": [ - "add_control" - ] - }, - "CreateServingConfig": { - "methods": [ - "create_serving_config" - ] - }, - "DeleteServingConfig": { - "methods": [ - "delete_serving_config" - ] - }, - "GetServingConfig": { - "methods": [ - "get_serving_config" - ] - }, - "ListServingConfigs": { - "methods": [ - "list_serving_configs" - ] - }, - "RemoveControl": { - "methods": [ - "remove_control" - ] - }, - "UpdateServingConfig": { - "methods": [ - "update_serving_config" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py deleted file mode 100644 index d276b897..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CatalogServiceClient -from .async_client import CatalogServiceAsyncClient - -__all__ = ( - 'CatalogServiceClient', - 'CatalogServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py deleted file mode 100644 index e828ae6f..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py +++ /dev/null @@ -1,1352 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.catalog_service import pagers -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport -from .client import CatalogServiceClient - - -class CatalogServiceAsyncClient: - """Service for managing catalog configuration.""" - - _client: CatalogServiceClient - - DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT - - attributes_config_path = staticmethod(CatalogServiceClient.attributes_config_path) - parse_attributes_config_path = staticmethod(CatalogServiceClient.parse_attributes_config_path) - branch_path = staticmethod(CatalogServiceClient.branch_path) - parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) - catalog_path = staticmethod(CatalogServiceClient.catalog_path) - parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) - completion_config_path = staticmethod(CatalogServiceClient.completion_config_path) - parse_completion_config_path = staticmethod(CatalogServiceClient.parse_completion_config_path) - common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CatalogServiceClient.common_project_path) - parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) - common_location_path = staticmethod(CatalogServiceClient.common_location_path) - parse_common_location_path = staticmethod(CatalogServiceClient.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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CatalogServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsAsyncPager: - r"""Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_list_catalogs(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - parent (:class:`str`): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2alpha.Catalog]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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsAsyncPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.ListCatalogsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_catalogs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCatalogsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_catalog(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2alpha.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2alpha.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] - method. - catalog (:class:`google.cloud.retail_v2alpha.types.Catalog`): - Required. The - [Catalog][google.cloud.retail.v2alpha.Catalog] to - update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2alpha.Catalog], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Catalog][google.cloud.retail.v2alpha.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2alpha.Catalog] to - update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCatalogRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_catalog, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_set_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (:class:`str`): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.SetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (:class:`str`): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # 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_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_completion_config(self, - request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Gets a - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] - method. - name (:class:`str`): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - - 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.retail_v2alpha.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetCompletionConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_completion_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_completion_config(self, - request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, - *, - completion_config: catalog.CompletionConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Updates the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - completion_config = retail_v2alpha.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2alpha.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = await client.update_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] - method. - completion_config (:class:`google.cloud.retail_v2alpha.types.CompletionConfig`): - Required. The - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``completion_config`` 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 - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([completion_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCompletionConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if completion_config is not None: - request.completion_config = completion_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_completion_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("completion_config.name", request.completion_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_attributes_config(self, - request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Gets an - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] - method. - name (:class:`str`): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - - 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.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetAttributesConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_attributes_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_attributes_config(self, - request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, - *, - attributes_config: catalog.AttributesConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Updates the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - attributes_config = retail_v2alpha.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2alpha.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = await client.update_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] - method. - attributes_config (:class:`google.cloud.retail_v2alpha.types.AttributesConfig`): - Required. The - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. - - This corresponds to the ``attributes_config`` 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 - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([attributes_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateAttributesConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attributes_config is not None: - request.attributes_config = attributes_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_attributes_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config.name", request.attributes_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def add_catalog_attribute(self, - request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Adds the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_add_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.AddCatalogAttributeRequest(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.add_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def remove_catalog_attribute(self, - request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Removes the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = await client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.RemoveCatalogAttributeRequest(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.remove_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def replace_catalog_attribute(self, - request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Replaces the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.ReplaceCatalogAttributeRequest(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.replace_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py deleted file mode 100644 index 85a7d228..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py +++ /dev/null @@ -1,1582 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.catalog_service import pagers -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CatalogServiceGrpcTransport -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -class CatalogServiceClientMeta(type): - """Metaclass for the CatalogService 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[CatalogServiceTransport]] - _transport_registry["grpc"] = CatalogServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CatalogServiceTransport]: - """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): - """Service for managing catalog configuration.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CatalogServiceClient: 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: - CatalogServiceClient: 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) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def attributes_config_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified attributes_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_attributes_config_path(path: str) -> Dict[str,str]: - """Parses a attributes_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/attributesConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def completion_config_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified completion_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_completion_config_path(path: str) -> Dict[str,str]: - """Parses a completion_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/completionConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CatalogServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CatalogServiceTransport): - # transport is a CatalogServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsPager: - r"""Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_list_catalogs(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2alpha.Catalog]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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ListCatalogsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ListCatalogsRequest): - request = catalog_service.ListCatalogsRequest(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_catalogs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCatalogsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_catalog(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2alpha.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2alpha.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] - method. - catalog (google.cloud.retail_v2alpha.types.Catalog): - Required. The - [Catalog][google.cloud.retail.v2alpha.Catalog] to - update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2alpha.Catalog], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Catalog][google.cloud.retail.v2alpha.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2alpha.Catalog] to - update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCatalogRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCatalogRequest): - request = catalog_service.UpdateCatalogRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - 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_catalog] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_set_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.SetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.SetDefaultBranchRequest): - request = catalog_service.SetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetDefaultBranchRequest): - request = catalog_service.GetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_completion_config(self, - request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Gets a - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] - method. - name (str): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - - 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.retail_v2alpha.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetCompletionConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetCompletionConfigRequest): - request = catalog_service.GetCompletionConfigRequest(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_completion_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_completion_config(self, - request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, - *, - completion_config: catalog.CompletionConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Updates the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - completion_config = retail_v2alpha.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2alpha.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = client.update_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] - method. - completion_config (google.cloud.retail_v2alpha.types.CompletionConfig): - Required. The - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``completion_config`` 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 - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([completion_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCompletionConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCompletionConfigRequest): - request = catalog_service.UpdateCompletionConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if completion_config is not None: - request.completion_config = completion_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_completion_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("completion_config.name", request.completion_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_attributes_config(self, - request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Gets an - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] - method. - name (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - - 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.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetAttributesConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetAttributesConfigRequest): - request = catalog_service.GetAttributesConfigRequest(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_attributes_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_attributes_config(self, - request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, - *, - attributes_config: catalog.AttributesConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Updates the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - attributes_config = retail_v2alpha.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2alpha.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = client.update_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] - method. - attributes_config (google.cloud.retail_v2alpha.types.AttributesConfig): - Required. The - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. - - This corresponds to the ``attributes_config`` 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 - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([attributes_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateAttributesConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateAttributesConfigRequest): - request = catalog_service.UpdateAttributesConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attributes_config is not None: - request.attributes_config = attributes_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_attributes_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config.name", request.attributes_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def add_catalog_attribute(self, - request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Adds the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_add_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.AddCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.AddCatalogAttributeRequest): - request = catalog_service.AddCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def remove_catalog_attribute(self, - request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Removes the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.RemoveCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.RemoveCatalogAttributeRequest): - request = catalog_service.RemoveCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def replace_catalog_attribute(self, - request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Replaces the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ReplaceCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ReplaceCatalogAttributeRequest): - request = catalog_service.ReplaceCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.replace_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py deleted file mode 100644 index f78d4bfa..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog_service - - -class ListCatalogsPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` - 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[..., catalog_service.ListCatalogsResponse], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2alpha.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - for page in self.pages: - yield from page.catalogs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCatalogsAsyncPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` - 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[catalog_service.ListCatalogsResponse]], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2alpha.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - async def async_generator(): - async for page in self.pages: - for response in page.catalogs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py deleted file mode 100644 index 0cffa336..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CatalogServiceTransport -from .grpc import CatalogServiceGrpcTransport -from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] -_transport_registry['grpc'] = CatalogServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport - -__all__ = ( - 'CatalogServiceTransport', - 'CatalogServiceGrpcTransport', - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py deleted file mode 100644 index 8a244fb4..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py +++ /dev/null @@ -1,297 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CatalogServiceTransport(abc.ABC): - """Abstract transport class for CatalogService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_catalogs: gapic_v1.method.wrap_method( - self.list_catalogs, - default_timeout=None, - client_info=client_info, - ), - self.update_catalog: gapic_v1.method.wrap_method( - self.update_catalog, - default_timeout=None, - client_info=client_info, - ), - self.set_default_branch: gapic_v1.method.wrap_method( - self.set_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_default_branch: gapic_v1.method.wrap_method( - self.get_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_completion_config: gapic_v1.method.wrap_method( - self.get_completion_config, - default_timeout=None, - client_info=client_info, - ), - self.update_completion_config: gapic_v1.method.wrap_method( - self.update_completion_config, - default_timeout=None, - client_info=client_info, - ), - self.get_attributes_config: gapic_v1.method.wrap_method( - self.get_attributes_config, - default_timeout=None, - client_info=client_info, - ), - self.update_attributes_config: gapic_v1.method.wrap_method( - self.update_attributes_config, - default_timeout=None, - client_info=client_info, - ), - self.add_catalog_attribute: gapic_v1.method.wrap_method( - self.add_catalog_attribute, - default_timeout=None, - client_info=client_info, - ), - self.remove_catalog_attribute: gapic_v1.method.wrap_method( - self.remove_catalog_attribute, - default_timeout=None, - client_info=client_info, - ), - self.replace_catalog_attribute: gapic_v1.method.wrap_method( - self.replace_catalog_attribute, - 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Union[ - catalog_service.ListCatalogsResponse, - Awaitable[catalog_service.ListCatalogsResponse] - ]]: - raise NotImplementedError() - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Union[ - gcr_catalog.Catalog, - Awaitable[gcr_catalog.Catalog] - ]]: - raise NotImplementedError() - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Union[ - catalog_service.GetDefaultBranchResponse, - Awaitable[catalog_service.GetDefaultBranchResponse] - ]]: - raise NotImplementedError() - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - Union[ - catalog.CompletionConfig, - Awaitable[catalog.CompletionConfig] - ]]: - raise NotImplementedError() - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - Union[ - catalog.CompletionConfig, - Awaitable[catalog.CompletionConfig] - ]]: - raise NotImplementedError() - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CatalogServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py deleted file mode 100644 index 4ebe0ff0..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py +++ /dev/null @@ -1,600 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO - - -class CatalogServiceGrpcTransport(CatalogServiceTransport): - """gRPC backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - catalog_service.ListCatalogsResponse]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - ~.ListCatalogsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - gcr_catalog.Catalog]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - ~.Catalog]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - empty_pb2.Empty]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - ~.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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - catalog_service.GetDefaultBranchResponse]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - ~.GetDefaultBranchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - catalog.CompletionConfig]: - r"""Return a callable for the get completion config method over gRPC. - - Gets a - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. - - Returns: - Callable[[~.GetCompletionConfigRequest], - ~.CompletionConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetCompletionConfig', - request_serializer=catalog_service.GetCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['get_completion_config'] - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - catalog.CompletionConfig]: - r"""Return a callable for the update completion config method over gRPC. - - Updates the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. - - Returns: - Callable[[~.UpdateCompletionConfigRequest], - ~.CompletionConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateCompletionConfig', - request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['update_completion_config'] - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - catalog.AttributesConfig]: - r"""Return a callable for the get attributes config method over gRPC. - - Gets an - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - Returns: - Callable[[~.GetAttributesConfigRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetAttributesConfig', - request_serializer=catalog_service.GetAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['get_attributes_config'] - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - catalog.AttributesConfig]: - r"""Return a callable for the update attributes config method over gRPC. - - Updates the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - Returns: - Callable[[~.UpdateAttributesConfigRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateAttributesConfig', - request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['update_attributes_config'] - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the add catalog attribute method over gRPC. - - Adds the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.AddCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_catalog_attribute' not in self._stubs: - self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/AddCatalogAttribute', - request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['add_catalog_attribute'] - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the remove catalog attribute method over gRPC. - - Removes the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.RemoveCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_catalog_attribute' not in self._stubs: - self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/RemoveCatalogAttribute', - request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['remove_catalog_attribute'] - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the replace catalog attribute method over gRPC. - - Replaces the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.ReplaceCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_catalog_attribute' not in self._stubs: - self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/ReplaceCatalogAttribute', - request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['replace_catalog_attribute'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CatalogServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py deleted file mode 100644 index 15eacf16..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,599 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CatalogServiceGrpcTransport - - -class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): - """gRPC AsyncIO backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Awaitable[catalog_service.ListCatalogsResponse]]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - Awaitable[~.ListCatalogsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Awaitable[gcr_catalog.Catalog]]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - Awaitable[~.Catalog]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - 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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Awaitable[catalog_service.GetDefaultBranchResponse]]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - Awaitable[~.GetDefaultBranchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - Awaitable[catalog.CompletionConfig]]: - r"""Return a callable for the get completion config method over gRPC. - - Gets a - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. - - Returns: - Callable[[~.GetCompletionConfigRequest], - Awaitable[~.CompletionConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetCompletionConfig', - request_serializer=catalog_service.GetCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['get_completion_config'] - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - Awaitable[catalog.CompletionConfig]]: - r"""Return a callable for the update completion config method over gRPC. - - Updates the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. - - Returns: - Callable[[~.UpdateCompletionConfigRequest], - Awaitable[~.CompletionConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateCompletionConfig', - request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['update_completion_config'] - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the get attributes config method over gRPC. - - Gets an - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - Returns: - Callable[[~.GetAttributesConfigRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetAttributesConfig', - request_serializer=catalog_service.GetAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['get_attributes_config'] - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the update attributes config method over gRPC. - - Updates the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - Returns: - Callable[[~.UpdateAttributesConfigRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateAttributesConfig', - request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['update_attributes_config'] - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the add catalog attribute method over gRPC. - - Adds the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.AddCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_catalog_attribute' not in self._stubs: - self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/AddCatalogAttribute', - request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['add_catalog_attribute'] - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the remove catalog attribute method over gRPC. - - Removes the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.RemoveCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_catalog_attribute' not in self._stubs: - self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/RemoveCatalogAttribute', - request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['remove_catalog_attribute'] - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the replace catalog attribute method over gRPC. - - Replaces the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.ReplaceCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_catalog_attribute' not in self._stubs: - self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/ReplaceCatalogAttribute', - request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['replace_catalog_attribute'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py deleted file mode 100644 index b8af95bd..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CompletionServiceClient -from .async_client import CompletionServiceAsyncClient - -__all__ = ( - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py deleted file mode 100644 index 74888568..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py +++ /dev/null @@ -1,391 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .client import CompletionServiceClient - - -class CompletionServiceAsyncClient: - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: CompletionServiceClient - - DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(CompletionServiceClient.catalog_path) - parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) - common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CompletionServiceClient.common_project_path) - parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) - common_location_path = staticmethod(CompletionServiceClient.common_location_path) - parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CompletionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_complete_query(): - # Create a client - client = retail_v2alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.complete_query, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_import_completion_data(): - # Create a client - client = retail_v2alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2alpha.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. - 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. - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_completion_data, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py deleted file mode 100644 index 6e783e95..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py +++ /dev/null @@ -1,593 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CompletionServiceGrpcTransport -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -class CompletionServiceClientMeta(type): - """Metaclass for the CompletionService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] - _transport_registry["grpc"] = CompletionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CompletionServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class CompletionServiceClient(metaclass=CompletionServiceClientMeta): - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CompletionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CompletionServiceTransport): - # transport is a CompletionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_complete_query(): - # Create a client - client = retail_v2alpha.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a completion_service.CompleteQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, completion_service.CompleteQueryRequest): - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_import_completion_data(): - # Create a client - client = retail_v2alpha.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2alpha.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. - 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. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportCompletionDataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportCompletionDataRequest): - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_completion_data] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py deleted file mode 100644 index a0c9542f..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CompletionServiceTransport -from .grpc import CompletionServiceGrpcTransport -from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] -_transport_registry['grpc'] = CompletionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport - -__all__ = ( - 'CompletionServiceTransport', - 'CompletionServiceGrpcTransport', - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py deleted file mode 100644 index 2e16e808..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py +++ /dev/null @@ -1,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CompletionServiceTransport(abc.ABC): - """Abstract transport class for CompletionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.complete_query: gapic_v1.method.wrap_method( - self.complete_query, - default_timeout=None, - client_info=client_info, - ), - self.import_completion_data: gapic_v1.method.wrap_method( - self.import_completion_data, - 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Union[ - completion_service.CompleteQueryResponse, - Awaitable[completion_service.CompleteQueryResponse] - ]]: - raise NotImplementedError() - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CompletionServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py deleted file mode 100644 index dd953c63..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py +++ /dev/null @@ -1,325 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO - - -class CompletionServiceGrpcTransport(CompletionServiceTransport): - """gRPC backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - ~.CompleteQueryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - operations_pb2.Operation]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CompletionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py deleted file mode 100644 index 726b0e6e..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,324 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CompletionServiceGrpcTransport - - -class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): - """gRPC AsyncIO backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Awaitable[completion_service.CompleteQueryResponse]]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - Awaitable[~.CompleteQueryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - 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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py deleted file mode 100644 index e9a7be2f..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ControlServiceClient -from .async_client import ControlServiceAsyncClient - -__all__ = ( - 'ControlServiceClient', - 'ControlServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py deleted file mode 100644 index e32d838b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py +++ /dev/null @@ -1,744 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.control_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.cloud.retail_v2alpha.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport -from .client import ControlServiceClient - - -class ControlServiceAsyncClient: - """Service for modifying Control.""" - - _client: ControlServiceClient - - DEFAULT_ENDPOINT = ControlServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ControlServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(ControlServiceClient.catalog_path) - parse_catalog_path = staticmethod(ControlServiceClient.parse_catalog_path) - control_path = staticmethod(ControlServiceClient.control_path) - parse_control_path = staticmethod(ControlServiceClient.parse_control_path) - common_billing_account_path = staticmethod(ControlServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ControlServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ControlServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ControlServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ControlServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ControlServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ControlServiceClient.common_project_path) - parse_common_project_path = staticmethod(ControlServiceClient.parse_common_project_path) - common_location_path = staticmethod(ControlServiceClient.common_location_path) - parse_common_location_path = staticmethod(ControlServiceClient.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: - ControlServiceAsyncClient: The constructed client. - """ - return ControlServiceClient.from_service_account_info.__func__(ControlServiceAsyncClient, 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: - ControlServiceAsyncClient: The constructed client. - """ - return ControlServiceClient.from_service_account_file.__func__(ControlServiceAsyncClient, 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 variabel 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 ControlServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ControlServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ControlServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ControlServiceClient).get_transport_class, type(ControlServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ControlServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the control service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ControlServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ControlServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_control(self, - request: Union[control_service.CreateControlRequest, dict] = None, - *, - parent: str = None, - control: gcr_control.Control = None, - control_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Creates a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_create_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = await client.create_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateControlRequest, dict]): - The request object. Request for CreateControl method. - parent (:class:`str`): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control (:class:`google.cloud.retail_v2alpha.types.Control`): - Required. The Control to create. - This corresponds to the ``control`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control_id (:class:`str`): - Required. The ID to use for the Control, which will - become the final component of the Control's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``control_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.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, control, control_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.CreateControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if control is not None: - request.control = control - if control_id is not None: - request.control_id = control_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_control(self, - request: Union[control_service.DeleteControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_delete_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteControlRequest( - name="name_value", - ) - - # Make the request - await client.delete_control(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteControlRequest, dict]): - The request object. Request for DeleteControl method. - name (:class:`str`): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.DeleteControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_control(self, - request: Union[control_service.UpdateControlRequest, dict] = None, - *, - control: gcr_control.Control = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Updates a Control. - - [Control][google.cloud.retail.v2alpha.Control] cannot be set to - a different oneof field, if so an INVALID_ARGUMENT is returned. - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.UpdateControlRequest( - control=control, - ) - - # Make the request - response = await client.update_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateControlRequest, dict]): - The request object. Request for UpdateControl method. - control (:class:`google.cloud.retail_v2alpha.types.Control`): - Required. The Control to update. - This corresponds to the ``control`` 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 - [Control][google.cloud.retail.v2alpha.Control] to - update. The following are NOT supported: - - - [Control.name][google.cloud.retail.v2alpha.Control.name] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([control, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.UpdateControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if control is not None: - request.control = control - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("control.name", request.control.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_control(self, - request: Union[control_service.GetControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> control.Control: - r"""Gets a Control. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetControlRequest( - name="name_value", - ) - - # Make the request - response = await client.get_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetControlRequest, dict]): - The request object. Request for GetControl method. - name (:class:`str`): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.GetControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_controls(self, - request: Union[control_service.ListControlsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListControlsAsyncPager: - r"""Lists all Controls linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_list_controls(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListControlsRequest, dict]): - The request object. Request for ListControls method. - parent (:class:`str`): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.control_service.pagers.ListControlsAsyncPager: - Response for ListControls method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.ListControlsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_controls, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListControlsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ControlServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py deleted file mode 100644 index 0981fa86..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py +++ /dev/null @@ -1,953 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.control_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.cloud.retail_v2alpha.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ControlServiceGrpcTransport -from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport - - -class ControlServiceClientMeta(type): - """Metaclass for the ControlService 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[ControlServiceTransport]] - _transport_registry["grpc"] = ControlServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ControlServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ControlServiceTransport]: - """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 ControlServiceClient(metaclass=ControlServiceClientMeta): - """Service for modifying Control.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ControlServiceClient: 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: - ControlServiceClient: 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) -> ControlServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ControlServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def control_path(project: str,location: str,catalog: str,control: str,) -> str: - """Returns a fully-qualified control string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) - - @staticmethod - def parse_control_path(path: str) -> Dict[str,str]: - """Parses a control path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/controls/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ControlServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the control service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ControlServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ControlServiceTransport): - # transport is a ControlServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_control(self, - request: Union[control_service.CreateControlRequest, dict] = None, - *, - parent: str = None, - control: gcr_control.Control = None, - control_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Creates a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_create_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = client.create_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateControlRequest, dict]): - The request object. Request for CreateControl method. - parent (str): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control (google.cloud.retail_v2alpha.types.Control): - Required. The Control to create. - This corresponds to the ``control`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control_id (str): - Required. The ID to use for the Control, which will - become the final component of the Control's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``control_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.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, control, control_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.CreateControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.CreateControlRequest): - request = control_service.CreateControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if control is not None: - request.control = control - if control_id is not None: - request.control_id = control_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_control(self, - request: Union[control_service.DeleteControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_delete_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteControlRequest( - name="name_value", - ) - - # Make the request - client.delete_control(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteControlRequest, dict]): - The request object. Request for DeleteControl method. - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.DeleteControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.DeleteControlRequest): - request = control_service.DeleteControlRequest(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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_control(self, - request: Union[control_service.UpdateControlRequest, dict] = None, - *, - control: gcr_control.Control = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Updates a Control. - - [Control][google.cloud.retail.v2alpha.Control] cannot be set to - a different oneof field, if so an INVALID_ARGUMENT is returned. - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.UpdateControlRequest( - control=control, - ) - - # Make the request - response = client.update_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateControlRequest, dict]): - The request object. Request for UpdateControl method. - control (google.cloud.retail_v2alpha.types.Control): - Required. The Control to update. - This corresponds to the ``control`` 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 - [Control][google.cloud.retail.v2alpha.Control] to - update. The following are NOT supported: - - - [Control.name][google.cloud.retail.v2alpha.Control.name] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([control, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.UpdateControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.UpdateControlRequest): - request = control_service.UpdateControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if control is not None: - request.control = control - 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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("control.name", request.control.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_control(self, - request: Union[control_service.GetControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> control.Control: - r"""Gets a Control. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetControlRequest( - name="name_value", - ) - - # Make the request - response = client.get_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetControlRequest, dict]): - The request object. Request for GetControl method. - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.GetControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.GetControlRequest): - request = control_service.GetControlRequest(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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_controls(self, - request: Union[control_service.ListControlsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListControlsPager: - r"""Lists all Controls linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_list_controls(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListControlsRequest, dict]): - The request object. Request for ListControls method. - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.control_service.pagers.ListControlsPager: - Response for ListControls method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.ListControlsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.ListControlsRequest): - request = control_service.ListControlsRequest(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_controls] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListControlsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ControlServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py deleted file mode 100644 index d1c28748..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control_service - - -class ListControlsPager: - """A pager for iterating through ``list_controls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``controls`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListControls`` requests and continue to iterate - through the ``controls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` - 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[..., control_service.ListControlsResponse], - request: control_service.ListControlsRequest, - response: control_service.ListControlsResponse, - *, - 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.retail_v2alpha.types.ListControlsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListControlsResponse): - 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 = control_service.ListControlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[control_service.ListControlsResponse]: - 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[control.Control]: - for page in self.pages: - yield from page.controls - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListControlsAsyncPager: - """A pager for iterating through ``list_controls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``controls`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListControls`` requests and continue to iterate - through the ``controls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` - 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[control_service.ListControlsResponse]], - request: control_service.ListControlsRequest, - response: control_service.ListControlsResponse, - *, - 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.retail_v2alpha.types.ListControlsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListControlsResponse): - 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 = control_service.ListControlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[control_service.ListControlsResponse]: - 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[control.Control]: - async def async_generator(): - async for page in self.pages: - for response in page.controls: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py deleted file mode 100644 index 3622876b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ControlServiceTransport -from .grpc import ControlServiceGrpcTransport -from .grpc_asyncio import ControlServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ControlServiceTransport]] -_transport_registry['grpc'] = ControlServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ControlServiceGrpcAsyncIOTransport - -__all__ = ( - 'ControlServiceTransport', - 'ControlServiceGrpcTransport', - 'ControlServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py deleted file mode 100644 index ef91c3df..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py +++ /dev/null @@ -1,213 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ControlServiceTransport(abc.ABC): - """Abstract transport class for ControlService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_control: gapic_v1.method.wrap_method( - self.create_control, - default_timeout=None, - client_info=client_info, - ), - self.delete_control: gapic_v1.method.wrap_method( - self.delete_control, - default_timeout=None, - client_info=client_info, - ), - self.update_control: gapic_v1.method.wrap_method( - self.update_control, - default_timeout=None, - client_info=client_info, - ), - self.get_control: gapic_v1.method.wrap_method( - self.get_control, - default_timeout=None, - client_info=client_info, - ), - self.list_controls: gapic_v1.method.wrap_method( - self.list_controls, - 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 create_control(self) -> Callable[ - [control_service.CreateControlRequest], - Union[ - gcr_control.Control, - Awaitable[gcr_control.Control] - ]]: - raise NotImplementedError() - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - Union[ - gcr_control.Control, - Awaitable[gcr_control.Control] - ]]: - raise NotImplementedError() - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - Union[ - control.Control, - Awaitable[control.Control] - ]]: - raise NotImplementedError() - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - Union[ - control_service.ListControlsResponse, - Awaitable[control_service.ListControlsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ControlServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py deleted file mode 100644 index 121caf7d..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py +++ /dev/null @@ -1,382 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO - - -class ControlServiceGrpcTransport(ControlServiceTransport): - """gRPC backend transport for ControlService. - - Service for modifying Control. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_control(self) -> Callable[ - [control_service.CreateControlRequest], - gcr_control.Control]: - r"""Return a callable for the create control method over gRPC. - - Creates a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['create_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/CreateControl', - request_serializer=control_service.CreateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['create_control'] - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete control method over gRPC. - - Deletes a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteControlRequest], - ~.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_control' not in self._stubs: - self._stubs['delete_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/DeleteControl', - request_serializer=control_service.DeleteControlRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_control'] - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - gcr_control.Control]: - r"""Return a callable for the update control method over gRPC. - - Updates a Control. - - [Control][google.cloud.retail.v2alpha.Control] cannot be set to - a different oneof field, if so an INVALID_ARGUMENT is returned. - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.UpdateControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['update_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/UpdateControl', - request_serializer=control_service.UpdateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['update_control'] - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - control.Control]: - r"""Return a callable for the get control method over gRPC. - - Gets a Control. - - Returns: - Callable[[~.GetControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['get_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/GetControl', - request_serializer=control_service.GetControlRequest.serialize, - response_deserializer=control.Control.deserialize, - ) - return self._stubs['get_control'] - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - control_service.ListControlsResponse]: - r"""Return a callable for the list controls method over gRPC. - - Lists all Controls linked to this catalog. - - Returns: - Callable[[~.ListControlsRequest], - ~.ListControlsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_controls' not in self._stubs: - self._stubs['list_controls'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/ListControls', - request_serializer=control_service.ListControlsRequest.serialize, - response_deserializer=control_service.ListControlsResponse.deserialize, - ) - return self._stubs['list_controls'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ControlServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py deleted file mode 100644 index 9703924c..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,381 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ControlServiceGrpcTransport - - -class ControlServiceGrpcAsyncIOTransport(ControlServiceTransport): - """gRPC AsyncIO backend transport for ControlService. - - Service for modifying Control. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_control(self) -> Callable[ - [control_service.CreateControlRequest], - Awaitable[gcr_control.Control]]: - r"""Return a callable for the create control method over gRPC. - - Creates a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['create_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/CreateControl', - request_serializer=control_service.CreateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['create_control'] - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete control method over gRPC. - - Deletes a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteControlRequest], - 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_control' not in self._stubs: - self._stubs['delete_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/DeleteControl', - request_serializer=control_service.DeleteControlRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_control'] - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - Awaitable[gcr_control.Control]]: - r"""Return a callable for the update control method over gRPC. - - Updates a Control. - - [Control][google.cloud.retail.v2alpha.Control] cannot be set to - a different oneof field, if so an INVALID_ARGUMENT is returned. - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.UpdateControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['update_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/UpdateControl', - request_serializer=control_service.UpdateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['update_control'] - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - Awaitable[control.Control]]: - r"""Return a callable for the get control method over gRPC. - - Gets a Control. - - Returns: - Callable[[~.GetControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['get_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/GetControl', - request_serializer=control_service.GetControlRequest.serialize, - response_deserializer=control.Control.deserialize, - ) - return self._stubs['get_control'] - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - Awaitable[control_service.ListControlsResponse]]: - r"""Return a callable for the list controls method over gRPC. - - Lists all Controls linked to this catalog. - - Returns: - Callable[[~.ListControlsRequest], - Awaitable[~.ListControlsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_controls' not in self._stubs: - self._stubs['list_controls'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/ListControls', - request_serializer=control_service.ListControlsRequest.serialize, - response_deserializer=control_service.ListControlsResponse.deserialize, - ) - return self._stubs['list_controls'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ControlServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py deleted file mode 100644 index 7c079c80..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import PredictionServiceClient -from .async_client import PredictionServiceAsyncClient - -__all__ = ( - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py deleted file mode 100644 index b9255f77..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py +++ /dev/null @@ -1,279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport -from .client import PredictionServiceClient - - -class PredictionServiceAsyncClient: - """Service for making recommendation prediction.""" - - _client: PredictionServiceClient - - DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT - - product_path = staticmethod(PredictionServiceClient.product_path) - parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) - common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(PredictionServiceClient.common_project_path) - parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) - common_location_path = staticmethod(PredictionServiceClient.common_location_path) - parse_common_location_path = staticmethod(PredictionServiceClient.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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PredictionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_predict(): - # Create a client - client = retail_v2alpha.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - request = prediction_service.PredictRequest(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.predict, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py deleted file mode 100644 index 1cb0e419..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py +++ /dev/null @@ -1,480 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PredictionServiceGrpcTransport -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -class PredictionServiceClientMeta(type): - """Metaclass for the PredictionService 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[PredictionServiceTransport]] - _transport_registry["grpc"] = PredictionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PredictionServiceTransport]: - """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): - """Service for making recommendation prediction.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PredictionServiceClient: 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: - PredictionServiceClient: 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) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, PredictionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, PredictionServiceTransport): - # transport is a PredictionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_predict(): - # Create a client - client = retail_v2alpha.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a prediction_service.PredictRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_service.PredictRequest): - request = prediction_service.PredictRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.predict] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py deleted file mode 100644 index bb65c664..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PredictionServiceTransport -from .grpc import PredictionServiceGrpcTransport -from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] -_transport_registry['grpc'] = PredictionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport - -__all__ = ( - 'PredictionServiceTransport', - 'PredictionServiceGrpcTransport', - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py deleted file mode 100644 index a5424c9e..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PredictionServiceTransport(abc.ABC): - """Abstract transport class for PredictionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.predict: gapic_v1.method.wrap_method( - self.predict, - 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - Union[ - prediction_service.PredictResponse, - Awaitable[prediction_service.PredictResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PredictionServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py deleted file mode 100644 index 0e227d35..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py +++ /dev/null @@ -1,264 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO - - -class PredictionServiceGrpcTransport(PredictionServiceTransport): - """gRPC backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - prediction_service.PredictResponse]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - ~.PredictResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PredictionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py deleted file mode 100644 index 26a9ecfc..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import PredictionServiceGrpcTransport - - -class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): - """gRPC AsyncIO backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def predict(self) -> Callable[ - [prediction_service.PredictRequest], - Awaitable[prediction_service.PredictResponse]]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - Awaitable[~.PredictResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py deleted file mode 100644 index 0fa6330a..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ProductServiceClient -from .async_client import ProductServiceAsyncClient - -__all__ = ( - 'ProductServiceClient', - 'ProductServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py deleted file mode 100644 index 2933dcb8..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py +++ /dev/null @@ -1,1804 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.services.product_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import purge_config -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport -from .client import ProductServiceClient - - -class ProductServiceAsyncClient: - """Service for ingesting [Product][google.cloud.retail.v2alpha.Product] - information of the customer's website. - """ - - _client: ProductServiceClient - - DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(ProductServiceClient.branch_path) - parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) - product_path = staticmethod(ProductServiceClient.product_path) - parse_product_path = staticmethod(ProductServiceClient.parse_product_path) - common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProductServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProductServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ProductServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) - common_location_path = staticmethod(ProductServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProductServiceClient.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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ProductServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ProductServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_create_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (:class:`str`): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (:class:`google.cloud.retail_v2alpha.types.Product`): - Required. The - [Product][google.cloud.retail.v2alpha.Product] to - create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (:class:`str`): - Required. The ID to use for the - [Product][google.cloud.retail.v2alpha.Product], which - will become the final component of the - [Product.name][google.cloud.retail.v2alpha.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This field must be unique among all - [Product][google.cloud.retail.v2alpha.Product]s with the - same - [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.CreateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the requested - [Product][google.cloud.retail.v2alpha.Product] 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.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.GetProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsAsyncPager: - r"""Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_list_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - parent (:class:`str`): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2alpha.Product]s under - this branch, regardless of whether or not this branch - exists, a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.product_service.pagers.ListProductsAsyncPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.ListProductsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_products, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProductsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (:class:`google.cloud.retail_v2alpha.types.Product`): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2alpha.Product] to - update. The immutable and output only fields are NOT - supported. If not set, all supported fields (the fields - that are neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.UpdateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_delete_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2alpha.Product] to - delete can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product] member - nor a - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] with more - than one - [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2alpha.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.DeleteProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def purge_products(self, - request: Union[purge_config.PurgeProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Permanently deletes all selected - [Product][google.cloud.retail.v2alpha.Product]s under a branch. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed offline. Depending on the - number of [Product][google.cloud.retail.v2alpha.Product]s, this - operation could take hours to complete. Before the operation - completes, some [Product][google.cloud.retail.v2alpha.Product]s - may still be returned by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Depending on the number of - [Product][google.cloud.retail.v2alpha.Product]s, this operation - could take hours to complete. To get a sample of - [Product][google.cloud.retail.v2alpha.Product]s that would be - deleted, set - [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] - to false. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_purge_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeProductsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PurgeProductsRequest, dict]): - The request object. Request message for PurgeProducts - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.PurgeProductsResponse` Response of the PurgeProductsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_products, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeProductsResponse, - metadata_type=purge_config.PurgeProductsMetadata, - ) - - # Done; return the response. - return response - - async def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2alpha.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2alpha.Product]s to be - successfully updated. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_import_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2alpha.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2alpha.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_set_inventory(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2alpha.Product() - inventory.title = "title_value" - - request = retail_v2alpha.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (:class:`google.cloud.retail_v2alpha.types.Product`): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product] named in - [Product.name][google.cloud.retail.v2alpha.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2alpha.Product] to - update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.SetInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_inventory, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - async def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [AddFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_add_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [AddLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_remove_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py deleted file mode 100644 index 6206989b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py +++ /dev/null @@ -1,2008 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.services.product_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import purge_config -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProductServiceGrpcTransport -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -class ProductServiceClientMeta(type): - """Metaclass for the ProductService 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[ProductServiceTransport]] - _transport_registry["grpc"] = ProductServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ProductServiceTransport]: - """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 ProductServiceClient(metaclass=ProductServiceClientMeta): - """Service for ingesting [Product][google.cloud.retail.v2alpha.Product] - information of the customer's website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProductServiceClient: 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: - ProductServiceClient: 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) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProductServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ProductServiceTransport): - # transport is a ProductServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_create_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (google.cloud.retail_v2alpha.types.Product): - Required. The - [Product][google.cloud.retail.v2alpha.Product] to - create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2alpha.Product], which - will become the final component of the - [Product.name][google.cloud.retail.v2alpha.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This field must be unique among all - [Product][google.cloud.retail.v2alpha.Product]s with the - same - [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.CreateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.CreateProductRequest): - request = product_service.CreateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the requested - [Product][google.cloud.retail.v2alpha.Product] 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.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.GetProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.GetProductRequest): - request = product_service.GetProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsPager: - r"""Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_list_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2alpha.Product]s under - this branch, regardless of whether or not this branch - exists, a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.product_service.pagers.ListProductsPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.ListProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.ListProductsRequest): - request = product_service.ListProductsRequest(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_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProductsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (google.cloud.retail_v2alpha.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2alpha.Product] to - update. The immutable and output only fields are NOT - supported. If not set, all supported fields (the fields - that are neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.UpdateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.UpdateProductRequest): - request = product_service.UpdateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - 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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_delete_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2alpha.Product] to - delete can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product] member - nor a - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] with more - than one - [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2alpha.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.DeleteProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.DeleteProductRequest): - request = product_service.DeleteProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def purge_products(self, - request: Union[purge_config.PurgeProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Permanently deletes all selected - [Product][google.cloud.retail.v2alpha.Product]s under a branch. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed offline. Depending on the - number of [Product][google.cloud.retail.v2alpha.Product]s, this - operation could take hours to complete. Before the operation - completes, some [Product][google.cloud.retail.v2alpha.Product]s - may still be returned by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Depending on the number of - [Product][google.cloud.retail.v2alpha.Product]s, this operation - could take hours to complete. To get a sample of - [Product][google.cloud.retail.v2alpha.Product]s that would be - deleted, set - [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] - to false. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_purge_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeProductsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PurgeProductsRequest, dict]): - The request object. Request message for PurgeProducts - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.PurgeProductsResponse` Response of the PurgeProductsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeProductsRequest): - request = purge_config.PurgeProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeProductsResponse, - metadata_type=purge_config.PurgeProductsMetadata, - ) - - # Done; return the response. - return response - - def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2alpha.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2alpha.Product]s to be - successfully updated. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_import_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2alpha.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportProductsRequest): - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2alpha.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_set_inventory(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2alpha.Product() - inventory.title = "title_value" - - request = retail_v2alpha.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (google.cloud.retail_v2alpha.types.Product): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product] named in - [Product.name][google.cloud.retail.v2alpha.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2alpha.Product] to - update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.SetInventoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.SetInventoryRequest): - request = product_service.SetInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_add_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [AddFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddFulfillmentPlacesRequest): - request = product_service.AddFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): - request = product_service.RemoveFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_add_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [AddLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddLocalInventoriesRequest): - request = product_service.AddLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_remove_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveLocalInventoriesRequest): - request = product_service.RemoveLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py deleted file mode 100644 index 5e235009..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product_service - - -class ListProductsPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` - 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[..., product_service.ListProductsResponse], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2alpha.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[product_service.ListProductsResponse]: - 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[product.Product]: - for page in self.pages: - yield from page.products - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProductsAsyncPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` - 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[product_service.ListProductsResponse]], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2alpha.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: - 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[product.Product]: - async def async_generator(): - async for page in self.pages: - for response in page.products: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py deleted file mode 100644 index db824dec..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ProductServiceTransport -from .grpc import ProductServiceGrpcTransport -from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] -_transport_registry['grpc'] = ProductServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport - -__all__ = ( - 'ProductServiceTransport', - 'ProductServiceGrpcTransport', - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py deleted file mode 100644 index fe69ccf2..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py +++ /dev/null @@ -1,327 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import purge_config -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ProductServiceTransport(abc.ABC): - """Abstract transport class for ProductService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_product: gapic_v1.method.wrap_method( - self.create_product, - default_timeout=None, - client_info=client_info, - ), - self.get_product: gapic_v1.method.wrap_method( - self.get_product, - default_timeout=None, - client_info=client_info, - ), - self.list_products: gapic_v1.method.wrap_method( - self.list_products, - default_timeout=None, - client_info=client_info, - ), - self.update_product: gapic_v1.method.wrap_method( - self.update_product, - default_timeout=None, - client_info=client_info, - ), - self.delete_product: gapic_v1.method.wrap_method( - self.delete_product, - default_timeout=None, - client_info=client_info, - ), - self.purge_products: gapic_v1.method.wrap_method( - self.purge_products, - default_timeout=None, - client_info=client_info, - ), - self.import_products: gapic_v1.method.wrap_method( - self.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.set_inventory: gapic_v1.method.wrap_method( - self.set_inventory, - default_timeout=None, - client_info=client_info, - ), - self.add_fulfillment_places: gapic_v1.method.wrap_method( - self.add_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.remove_fulfillment_places: gapic_v1.method.wrap_method( - self.remove_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.add_local_inventories: gapic_v1.method.wrap_method( - self.add_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.remove_local_inventories: gapic_v1.method.wrap_method( - self.remove_local_inventories, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Union[ - product.Product, - Awaitable[product.Product] - ]]: - raise NotImplementedError() - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Union[ - product_service.ListProductsResponse, - Awaitable[product_service.ListProductsResponse] - ]]: - raise NotImplementedError() - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def purge_products(self) -> Callable[ - [purge_config.PurgeProductsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ProductServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py deleted file mode 100644 index 72a1777c..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py +++ /dev/null @@ -1,726 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import purge_config -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO - - -class ProductServiceGrpcTransport(ProductServiceTransport): - """gRPC backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2alpha.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - gcr_product.Product]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.CreateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - product.Product]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.GetProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - product_service.ListProductsResponse]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - ~.ListProductsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - gcr_product.Product]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - ~.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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def purge_products(self) -> Callable[ - [purge_config.PurgeProductsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge products method over gRPC. - - Permanently deletes all selected - [Product][google.cloud.retail.v2alpha.Product]s under a branch. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed offline. Depending on the - number of [Product][google.cloud.retail.v2alpha.Product]s, this - operation could take hours to complete. Before the operation - completes, some [Product][google.cloud.retail.v2alpha.Product]s - may still be returned by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Depending on the number of - [Product][google.cloud.retail.v2alpha.Product]s, this operation - could take hours to complete. To get a sample of - [Product][google.cloud.retail.v2alpha.Product]s that would be - deleted, set - [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] - to false. - - Returns: - Callable[[~.PurgeProductsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_products' not in self._stubs: - self._stubs['purge_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/PurgeProducts', - request_serializer=purge_config.PurgeProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_products'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2alpha.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2alpha.Product]s to be - successfully updated. - - Returns: - Callable[[~.ImportProductsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - operations_pb2.Operation]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2alpha.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProductServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py deleted file mode 100644 index f130d491..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,725 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import purge_config -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ProductServiceGrpcTransport - - -class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): - """gRPC AsyncIO backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2alpha.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.CreateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Awaitable[product.Product]]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.GetProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Awaitable[product_service.ListProductsResponse]]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - Awaitable[~.ListProductsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - 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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def purge_products(self) -> Callable[ - [purge_config.PurgeProductsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge products method over gRPC. - - Permanently deletes all selected - [Product][google.cloud.retail.v2alpha.Product]s under a branch. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed offline. Depending on the - number of [Product][google.cloud.retail.v2alpha.Product]s, this - operation could take hours to complete. Before the operation - completes, some [Product][google.cloud.retail.v2alpha.Product]s - may still be returned by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Depending on the number of - [Product][google.cloud.retail.v2alpha.Product]s, this operation - could take hours to complete. To get a sample of - [Product][google.cloud.retail.v2alpha.Product]s that would be - deleted, set - [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] - to false. - - Returns: - Callable[[~.PurgeProductsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_products' not in self._stubs: - self._stubs['purge_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/PurgeProducts', - request_serializer=purge_config.PurgeProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_products'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2alpha.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2alpha.Product]s to be - successfully updated. - - Returns: - Callable[[~.ImportProductsRequest], - 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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2alpha.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - 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 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - 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 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - 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 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - 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 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py deleted file mode 100644 index 2f63fc22..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SearchServiceClient -from .async_client import SearchServiceAsyncClient - -__all__ = ( - 'SearchServiceClient', - 'SearchServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py deleted file mode 100644 index d39b3203..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.search_service import pagers -from google.cloud.retail_v2alpha.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .client import SearchServiceClient - - -class SearchServiceAsyncClient: - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: SearchServiceClient - - DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(SearchServiceClient.branch_path) - parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) - product_path = staticmethod(SearchServiceClient.product_path) - parse_product_path = staticmethod(SearchServiceClient.parse_product_path) - common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(SearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SearchServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAsyncPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_search(): - # Create a client - client = retail_v2alpha.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.search_service.pagers.SearchAsyncPager: - Response message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py deleted file mode 100644 index 4786889b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py +++ /dev/null @@ -1,513 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.search_service import pagers -from google.cloud.retail_v2alpha.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SearchServiceGrpcTransport -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -class SearchServiceClientMeta(type): - """Metaclass for the SearchService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] - _transport_registry["grpc"] = SearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SearchServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SearchServiceClient(metaclass=SearchServiceClientMeta): - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SearchServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SearchServiceTransport): - # transport is a SearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_search(): - # Create a client - client = retail_v2alpha.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.search_service.pagers.SearchPager: - Response message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a search_service.SearchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, search_service.SearchRequest): - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py deleted file mode 100644 index 7487beee..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import search_service - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., search_service.SearchResponse], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2alpha.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[search_service.SearchResponse]], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2alpha.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py deleted file mode 100644 index 7917cd1d..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SearchServiceTransport -from .grpc import SearchServiceGrpcTransport -from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] -_transport_registry['grpc'] = SearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport - -__all__ = ( - 'SearchServiceTransport', - 'SearchServiceGrpcTransport', - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py deleted file mode 100644 index f986834a..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import search_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class SearchServiceTransport(abc.ABC): - """Abstract transport class for SearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search: gapic_v1.method.wrap_method( - self.search, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Union[ - search_service.SearchResponse, - Awaitable[search_service.SearchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SearchServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py deleted file mode 100644 index 04e76b79..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py +++ /dev/null @@ -1,270 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO - - -class SearchServiceGrpcTransport(SearchServiceTransport): - """gRPC backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py deleted file mode 100644 index 26b52d69..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SearchServiceGrpcTransport - - -class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): - """gRPC AsyncIO backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Awaitable[search_service.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py deleted file mode 100644 index d1a0a023..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ServingConfigServiceClient -from .async_client import ServingConfigServiceAsyncClient - -__all__ = ( - 'ServingConfigServiceClient', - 'ServingConfigServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py deleted file mode 100644 index 4f047853..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py +++ /dev/null @@ -1,954 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.serving_config_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport -from .client import ServingConfigServiceClient - - -class ServingConfigServiceAsyncClient: - """Service for modifying ServingConfig.""" - - _client: ServingConfigServiceClient - - DEFAULT_ENDPOINT = ServingConfigServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ServingConfigServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(ServingConfigServiceClient.catalog_path) - parse_catalog_path = staticmethod(ServingConfigServiceClient.parse_catalog_path) - serving_config_path = staticmethod(ServingConfigServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(ServingConfigServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(ServingConfigServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ServingConfigServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ServingConfigServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ServingConfigServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ServingConfigServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ServingConfigServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ServingConfigServiceClient.common_project_path) - parse_common_project_path = staticmethod(ServingConfigServiceClient.parse_common_project_path) - common_location_path = staticmethod(ServingConfigServiceClient.common_location_path) - parse_common_location_path = staticmethod(ServingConfigServiceClient.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: - ServingConfigServiceAsyncClient: The constructed client. - """ - return ServingConfigServiceClient.from_service_account_info.__func__(ServingConfigServiceAsyncClient, 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: - ServingConfigServiceAsyncClient: The constructed client. - """ - return ServingConfigServiceClient.from_service_account_file.__func__(ServingConfigServiceAsyncClient, 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 variabel 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 ServingConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ServingConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ServingConfigServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ServingConfigServiceClient).get_transport_class, type(ServingConfigServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ServingConfigServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the serving config service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ServingConfigServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ServingConfigServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_serving_config(self, - request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, - *, - parent: str = None, - serving_config: gcr_serving_config.ServingConfig = None, - serving_config_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_create_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = await client.create_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateServingConfigRequest, dict]): - The request object. Request for CreateServingConfig - method. - parent (:class:`str`): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config (:class:`google.cloud.retail_v2alpha.types.ServingConfig`): - Required. The ServingConfig to - create. - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config_id (:class:`str`): - Required. The ID to use for the ServingConfig, which - will become the final component of the ServingConfig's - resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``serving_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, serving_config, serving_config_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.CreateServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if serving_config is not None: - request.serving_config = serving_config - if serving_config_id is not None: - request.serving_config_id = serving_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_serving_config(self, - request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_delete_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_serving_config(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteServingConfigRequest, dict]): - The request object. Request for DeleteServingConfig - method. - name (:class:`str`): - Required. The resource name of the ServingConfig to - delete. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.DeleteServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_serving_config(self, - request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, - *, - serving_config: gcr_serving_config.ServingConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Updates a ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = await client.update_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateServingConfigRequest, dict]): - The request object. Request for UpdateServingConfig - method. - serving_config (:class:`google.cloud.retail_v2alpha.types.ServingConfig`): - Required. The ServingConfig to - update. - - This corresponds to the ``serving_config`` 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 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.UpdateServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config.name", request.serving_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_serving_config(self, - request: Union[serving_config_service.GetServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> serving_config.ServingConfig: - r"""Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetServingConfigRequest, dict]): - The request object. Request for GetServingConfig method. - name (:class:`str`): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.GetServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_serving_configs(self, - request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServingConfigsAsyncPager: - r"""Lists all ServingConfigs linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_list_serving_configs(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListServingConfigsRequest, dict]): - The request object. Request for ListServingConfigs - method. - parent (:class:`str`): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsAsyncPager: - Response for ListServingConfigs - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.ListServingConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_serving_configs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListServingConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def add_control(self, - request: Union[serving_config_service.AddControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_add_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.add_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddControlRequest, dict]): - The request object. Request for AddControl method. - serving_config (:class:`str`): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.AddControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def remove_control(self, - request: Union[serving_config_service.RemoveControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_remove_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.remove_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveControlRequest, dict]): - The request object. Request for RemoveControl method. - serving_config (:class:`str`): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.RemoveControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServingConfigServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py deleted file mode 100644 index d9d8e276..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py +++ /dev/null @@ -1,1163 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.serving_config_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ServingConfigServiceGrpcTransport -from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport - - -class ServingConfigServiceClientMeta(type): - """Metaclass for the ServingConfigService 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[ServingConfigServiceTransport]] - _transport_registry["grpc"] = ServingConfigServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ServingConfigServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ServingConfigServiceTransport]: - """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 ServingConfigServiceClient(metaclass=ServingConfigServiceClientMeta): - """Service for modifying ServingConfig.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServingConfigServiceClient: 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: - ServingConfigServiceClient: 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) -> ServingConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ServingConfigServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,catalog: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ServingConfigServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the serving config service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ServingConfigServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ServingConfigServiceTransport): - # transport is a ServingConfigServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_serving_config(self, - request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, - *, - parent: str = None, - serving_config: gcr_serving_config.ServingConfig = None, - serving_config_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_create_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = client.create_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateServingConfigRequest, dict]): - The request object. Request for CreateServingConfig - method. - parent (str): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config (google.cloud.retail_v2alpha.types.ServingConfig): - Required. The ServingConfig to - create. - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config_id (str): - Required. The ID to use for the ServingConfig, which - will become the final component of the ServingConfig's - resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``serving_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, serving_config, serving_config_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.CreateServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.CreateServingConfigRequest): - request = serving_config_service.CreateServingConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if serving_config is not None: - request.serving_config = serving_config - if serving_config_id is not None: - request.serving_config_id = serving_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_serving_config(self, - request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_delete_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_serving_config(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteServingConfigRequest, dict]): - The request object. Request for DeleteServingConfig - method. - name (str): - Required. The resource name of the ServingConfig to - delete. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.DeleteServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.DeleteServingConfigRequest): - request = serving_config_service.DeleteServingConfigRequest(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_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_serving_config(self, - request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, - *, - serving_config: gcr_serving_config.ServingConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Updates a ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = client.update_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateServingConfigRequest, dict]): - The request object. Request for UpdateServingConfig - method. - serving_config (google.cloud.retail_v2alpha.types.ServingConfig): - Required. The ServingConfig to - update. - - This corresponds to the ``serving_config`` 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 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.UpdateServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.UpdateServingConfigRequest): - request = serving_config_service.UpdateServingConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config.name", request.serving_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_serving_config(self, - request: Union[serving_config_service.GetServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> serving_config.ServingConfig: - r"""Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetServingConfigRequest, dict]): - The request object. Request for GetServingConfig method. - name (str): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.GetServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.GetServingConfigRequest): - request = serving_config_service.GetServingConfigRequest(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_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_serving_configs(self, - request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServingConfigsPager: - r"""Lists all ServingConfigs linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_list_serving_configs(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListServingConfigsRequest, dict]): - The request object. Request for ListServingConfigs - method. - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsPager: - Response for ListServingConfigs - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.ListServingConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.ListServingConfigsRequest): - request = serving_config_service.ListServingConfigsRequest(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_serving_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListServingConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def add_control(self, - request: Union[serving_config_service.AddControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_add_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.add_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddControlRequest, dict]): - The request object. Request for AddControl method. - serving_config (str): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.AddControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.AddControlRequest): - request = serving_config_service.AddControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def remove_control(self, - request: Union[serving_config_service.RemoveControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_remove_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.remove_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveControlRequest, dict]): - The request object. Request for RemoveControl method. - serving_config (str): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.RemoveControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.RemoveControlRequest): - request = serving_config_service.RemoveControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServingConfigServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py deleted file mode 100644 index 8c4975b7..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config_service - - -class ListServingConfigsPager: - """A pager for iterating through ``list_serving_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``serving_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServingConfigs`` requests and continue to iterate - through the ``serving_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` - 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[..., serving_config_service.ListServingConfigsResponse], - request: serving_config_service.ListServingConfigsRequest, - response: serving_config_service.ListServingConfigsResponse, - *, - 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.retail_v2alpha.types.ListServingConfigsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListServingConfigsResponse): - 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 = serving_config_service.ListServingConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[serving_config_service.ListServingConfigsResponse]: - 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[serving_config.ServingConfig]: - for page in self.pages: - yield from page.serving_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServingConfigsAsyncPager: - """A pager for iterating through ``list_serving_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``serving_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServingConfigs`` requests and continue to iterate - through the ``serving_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` - 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[serving_config_service.ListServingConfigsResponse]], - request: serving_config_service.ListServingConfigsRequest, - response: serving_config_service.ListServingConfigsResponse, - *, - 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.retail_v2alpha.types.ListServingConfigsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListServingConfigsResponse): - 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 = serving_config_service.ListServingConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[serving_config_service.ListServingConfigsResponse]: - 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[serving_config.ServingConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.serving_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py deleted file mode 100644 index 3726ac83..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ServingConfigServiceTransport -from .grpc import ServingConfigServiceGrpcTransport -from .grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ServingConfigServiceTransport]] -_transport_registry['grpc'] = ServingConfigServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ServingConfigServiceGrpcAsyncIOTransport - -__all__ = ( - 'ServingConfigServiceTransport', - 'ServingConfigServiceGrpcTransport', - 'ServingConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py deleted file mode 100644 index 94052dd6..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ServingConfigServiceTransport(abc.ABC): - """Abstract transport class for ServingConfigService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_serving_config: gapic_v1.method.wrap_method( - self.create_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_serving_config: gapic_v1.method.wrap_method( - self.delete_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.update_serving_config: gapic_v1.method.wrap_method( - self.update_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.get_serving_config: gapic_v1.method.wrap_method( - self.get_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.list_serving_configs: gapic_v1.method.wrap_method( - self.list_serving_configs, - default_timeout=None, - client_info=client_info, - ), - self.add_control: gapic_v1.method.wrap_method( - self.add_control, - default_timeout=None, - client_info=client_info, - ), - self.remove_control: gapic_v1.method.wrap_method( - self.remove_control, - 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 create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - Union[ - serving_config.ServingConfig, - Awaitable[serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - Union[ - serving_config_service.ListServingConfigsResponse, - Awaitable[serving_config_service.ListServingConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ServingConfigServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py deleted file mode 100644 index 0acec25b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py +++ /dev/null @@ -1,440 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO - - -class ServingConfigServiceGrpcTransport(ServingConfigServiceTransport): - """gRPC backend transport for ServingConfigService. - - Service for modifying ServingConfig. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the create serving config method over gRPC. - - Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - Returns: - Callable[[~.CreateServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/CreateServingConfig', - request_serializer=serving_config_service.CreateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['create_serving_config'] - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete serving config method over gRPC. - - Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.DeleteServingConfigRequest], - ~.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_serving_config' not in self._stubs: - self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/DeleteServingConfig', - request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_serving_config'] - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the update serving config method over gRPC. - - Updates a ServingConfig. - - Returns: - Callable[[~.UpdateServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/UpdateServingConfig', - request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['update_serving_config'] - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - serving_config.ServingConfig]: - r"""Return a callable for the get serving config method over gRPC. - - Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.GetServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/GetServingConfig', - request_serializer=serving_config_service.GetServingConfigRequest.serialize, - response_deserializer=serving_config.ServingConfig.deserialize, - ) - return self._stubs['get_serving_config'] - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - serving_config_service.ListServingConfigsResponse]: - r"""Return a callable for the list serving configs method over gRPC. - - Lists all ServingConfigs linked to this catalog. - - Returns: - Callable[[~.ListServingConfigsRequest], - ~.ListServingConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: - self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/ListServingConfigs', - request_serializer=serving_config_service.ListServingConfigsRequest.serialize, - response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, - ) - return self._stubs['list_serving_configs'] - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the add control method over gRPC. - - Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - Returns: - Callable[[~.AddControlRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_control' not in self._stubs: - self._stubs['add_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/AddControl', - request_serializer=serving_config_service.AddControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['add_control'] - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the remove control method over gRPC. - - Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - Returns: - Callable[[~.RemoveControlRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_control' not in self._stubs: - self._stubs['remove_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/RemoveControl', - request_serializer=serving_config_service.RemoveControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['remove_control'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ServingConfigServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py deleted file mode 100644 index e3d2ccca..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,439 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ServingConfigServiceGrpcTransport - - -class ServingConfigServiceGrpcAsyncIOTransport(ServingConfigServiceTransport): - """gRPC AsyncIO backend transport for ServingConfigService. - - Service for modifying ServingConfig. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the create serving config method over gRPC. - - Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - Returns: - Callable[[~.CreateServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/CreateServingConfig', - request_serializer=serving_config_service.CreateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['create_serving_config'] - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete serving config method over gRPC. - - Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.DeleteServingConfigRequest], - 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_serving_config' not in self._stubs: - self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/DeleteServingConfig', - request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_serving_config'] - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the update serving config method over gRPC. - - Updates a ServingConfig. - - Returns: - Callable[[~.UpdateServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/UpdateServingConfig', - request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['update_serving_config'] - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - Awaitable[serving_config.ServingConfig]]: - r"""Return a callable for the get serving config method over gRPC. - - Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.GetServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/GetServingConfig', - request_serializer=serving_config_service.GetServingConfigRequest.serialize, - response_deserializer=serving_config.ServingConfig.deserialize, - ) - return self._stubs['get_serving_config'] - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - Awaitable[serving_config_service.ListServingConfigsResponse]]: - r"""Return a callable for the list serving configs method over gRPC. - - Lists all ServingConfigs linked to this catalog. - - Returns: - Callable[[~.ListServingConfigsRequest], - Awaitable[~.ListServingConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: - self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/ListServingConfigs', - request_serializer=serving_config_service.ListServingConfigsRequest.serialize, - response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, - ) - return self._stubs['list_serving_configs'] - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the add control method over gRPC. - - Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - Returns: - Callable[[~.AddControlRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_control' not in self._stubs: - self._stubs['add_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/AddControl', - request_serializer=serving_config_service.AddControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['add_control'] - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the remove control method over gRPC. - - Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - Returns: - Callable[[~.RemoveControlRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_control' not in self._stubs: - self._stubs['remove_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/RemoveControl', - request_serializer=serving_config_service.RemoveControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['remove_control'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ServingConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py deleted file mode 100644 index 5f5171c1..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py deleted file mode 100644 index 1f08ee18..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py +++ /dev/null @@ -1,730 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on the customer - website. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(UserEventServiceClient.catalog_path) - parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) - product_path = staticmethod(UserEventServiceClient.product_path) - parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_write_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_collect_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_purge_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_import_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2alpha.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_rejoin_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py deleted file mode 100644 index 98d272ff..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py +++ /dev/null @@ -1,930 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[UserEventServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on the customer - website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_write_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_collect_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_purge_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeUserEventsRequest): - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_import_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2alpha.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportUserEventsRequest): - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_rejoin_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.RejoinUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.RejoinUserEventsRequest): - request = user_event_service.RejoinUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py deleted file mode 100644 index f53ee5d7..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py deleted file mode 100644 index efd2f034..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py +++ /dev/null @@ -1,235 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_timeout=None, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_timeout=None, - client_info=client_info, - ), - self.purge_user_events: gapic_v1.method.wrap_method( - self.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.rejoin_user_events: gapic_v1.method.wrap_method( - self.rejoin_user_events, - 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 write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - user_event.UserEvent, - Awaitable[user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py deleted file mode 100644 index 3ca23eca..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index 72c6083a..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - 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 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py deleted file mode 100644 index aa87618d..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py +++ /dev/null @@ -1,284 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .catalog import ( - AttributesConfig, - Catalog, - CatalogAttribute, - CompletionConfig, - MerchantCenterLink, - MerchantCenterLinkingConfig, - ProductLevelConfig, -) -from .catalog_service import ( - AddCatalogAttributeRequest, - GetAttributesConfigRequest, - GetCompletionConfigRequest, - GetDefaultBranchRequest, - GetDefaultBranchResponse, - ListCatalogsRequest, - ListCatalogsResponse, - RemoveCatalogAttributeRequest, - ReplaceCatalogAttributeRequest, - SetDefaultBranchRequest, - UpdateAttributesConfigRequest, - UpdateCatalogRequest, - UpdateCompletionConfigRequest, -) -from .common import ( - Audience, - ColorInfo, - Condition, - CustomAttribute, - FulfillmentInfo, - Image, - Interval, - LocalInventory, - PriceInfo, - Rating, - Rule, - UserInfo, - AttributeConfigLevel, - SearchSolutionUseCase, - SolutionType, -) -from .completion_service import ( - CompleteQueryRequest, - CompleteQueryResponse, -) -from .control import ( - Control, -) -from .control_service import ( - CreateControlRequest, - DeleteControlRequest, - GetControlRequest, - ListControlsRequest, - ListControlsResponse, - UpdateControlRequest, -) -from .export_config import ( - ExportErrorsConfig, - ExportMetadata, - ExportProductsResponse, - ExportUserEventsResponse, -) -from .import_config import ( - BigQuerySource, - CompletionDataInputConfig, - GcsSource, - ImportCompletionDataRequest, - ImportCompletionDataResponse, - ImportErrorsConfig, - ImportMetadata, - ImportProductsRequest, - ImportProductsResponse, - ImportUserEventsRequest, - ImportUserEventsResponse, - ProductInlineSource, - ProductInputConfig, - UserEventImportSummary, - UserEventInlineSource, - UserEventInputConfig, -) -from .prediction_service import ( - PredictRequest, - PredictResponse, -) -from .product import ( - Product, -) -from .product_service import ( - AddFulfillmentPlacesMetadata, - AddFulfillmentPlacesRequest, - AddFulfillmentPlacesResponse, - AddLocalInventoriesMetadata, - AddLocalInventoriesRequest, - AddLocalInventoriesResponse, - CreateProductRequest, - DeleteProductRequest, - GetProductRequest, - ListProductsRequest, - ListProductsResponse, - RemoveFulfillmentPlacesMetadata, - RemoveFulfillmentPlacesRequest, - RemoveFulfillmentPlacesResponse, - RemoveLocalInventoriesMetadata, - RemoveLocalInventoriesRequest, - RemoveLocalInventoriesResponse, - SetInventoryMetadata, - SetInventoryRequest, - SetInventoryResponse, - UpdateProductRequest, -) -from .promotion import ( - Promotion, -) -from .purge_config import ( - PurgeMetadata, - PurgeProductsMetadata, - PurgeProductsRequest, - PurgeProductsResponse, - PurgeUserEventsRequest, - PurgeUserEventsResponse, -) -from .search_service import ( - SearchRequest, - SearchResponse, -) -from .serving_config import ( - ServingConfig, -) -from .serving_config_service import ( - AddControlRequest, - CreateServingConfigRequest, - DeleteServingConfigRequest, - GetServingConfigRequest, - ListServingConfigsRequest, - ListServingConfigsResponse, - RemoveControlRequest, - UpdateServingConfigRequest, -) -from .user_event import ( - CompletionDetail, - ProductDetail, - PurchaseTransaction, - UserEvent, -) -from .user_event_service import ( - CollectUserEventRequest, - RejoinUserEventsMetadata, - RejoinUserEventsRequest, - RejoinUserEventsResponse, - WriteUserEventRequest, -) - -__all__ = ( - 'AttributesConfig', - 'Catalog', - 'CatalogAttribute', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'ProductLevelConfig', - 'AddCatalogAttributeRequest', - 'GetAttributesConfigRequest', - 'GetCompletionConfigRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - 'SetDefaultBranchRequest', - 'UpdateAttributesConfigRequest', - 'UpdateCatalogRequest', - 'UpdateCompletionConfigRequest', - 'Audience', - 'ColorInfo', - 'Condition', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'Rule', - 'UserInfo', - 'AttributeConfigLevel', - 'SearchSolutionUseCase', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Control', - 'CreateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - 'UpdateControlRequest', - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeProductsMetadata', - 'PurgeProductsRequest', - 'PurgeProductsResponse', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'ServingConfig', - 'AddControlRequest', - 'CreateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'RemoveControlRequest', - 'UpdateServingConfigRequest', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py deleted file mode 100644 index 1e4a7ab5..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py +++ /dev/null @@ -1,528 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'ProductLevelConfig', - 'CatalogAttribute', - 'AttributesConfig', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'Catalog', - }, -) - - -class ProductLevelConfig(proto.Message): - r"""Configures what level the product should be uploaded with - regards to how users will be send events and how predictions - will be made. - - Attributes: - ingestion_product_type (str): - The type of [Product][google.cloud.retail.v2alpha.Product]s - allowed to be ingested into the catalog. Acceptable values - are: - - - ``primary`` (default): You can ingest - [Product][google.cloud.retail.v2alpha.Product]s of all - types. When ingesting a - [Product][google.cloud.retail.v2alpha.Product], its type - will default to - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - if unset. - - ``variant``: You can only ingest - [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s. This - means - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] - cannot be empty. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``variant`` and - [merchant_center_product_id_field][google.cloud.retail.v2alpha.ProductLevelConfig.merchant_center_product_id_field] - is ``itemGroupId``, an INVALID_ARGUMENT error is returned. - - See `Using product - levels `__ - for more details. - merchant_center_product_id_field (str): - Which field of `Merchant Center - Product `__ - should be imported as - [Product.id][google.cloud.retail.v2alpha.Product.id]. - Acceptable values are: - - - ``offerId`` (default): Import ``offerId`` as the product - ID. - - ``itemGroupId``: Import ``itemGroupId`` as the product - ID. Notice that Retail API will choose one item from the - ones with the same ``itemGroupId``, and use it to - represent the item group. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``itemGroupId`` and - [ingestion_product_type][google.cloud.retail.v2alpha.ProductLevelConfig.ingestion_product_type] - is ``variant``, an INVALID_ARGUMENT error is returned. - - See `Using product - levels `__ - for more details. - """ - - ingestion_product_type = proto.Field( - proto.STRING, - number=1, - ) - merchant_center_product_id_field = proto.Field( - proto.STRING, - number=2, - ) - - -class CatalogAttribute(proto.Message): - r"""Catalog level attribute config for an attribute. For example, - if customers want to enable/disable facet for a specific - attribute. - - Attributes: - key (str): - Required. Attribute name. For example: ``color``, - ``brands``, ``attributes.custom_attribute``, such as - ``attributes.xyz``. - in_use (bool): - Output only. Indicates whether this attribute has been used - by any products. ``True`` if at least one - [Product][google.cloud.retail.v2alpha.Product] is using this - attribute in - [Product.attributes][google.cloud.retail.v2alpha.Product.attributes]. - Otherwise, this field is ``False``. - - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - can be pre-loaded by using [AddCatalogAttribute][], - [ImportCatalogAttributes][], or [UpdateAttributesConfig][] - APIs. This field is ``False`` for pre-loaded - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s. - - Only - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s - that are not in use by products can be deleted. - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s - that are in use by products cannot be deleted; however, - their configuration properties will reset to default values - upon removal request. - - After catalog changes, it takes about 10 minutes for this - field to update. - type_ (google.cloud.retail_v2alpha.types.CatalogAttribute.AttributeType): - Output only. The type of this attribute. This is derived - from the attribute in - [Product.attributes][google.cloud.retail.v2alpha.Product.attributes]. - indexable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.IndexableOption): - When - [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] - is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if INDEXABLE_ENABLED - attribute values are indexed so that it can be filtered, - faceted, or boosted in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - dynamic_facetable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.DynamicFacetableOption): - If DYNAMIC_FACETABLE_ENABLED, attribute values are available - for dynamic facet. Could only be DYNAMIC_FACETABLE_DISABLED - if - [CatalogAttribute.indexable_option][google.cloud.retail.v2alpha.CatalogAttribute.indexable_option] - is INDEXABLE_DISABLED. Otherwise, an INVALID_ARGUMENT error - is returned. - searchable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.SearchableOption): - When - [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] - is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if SEARCHABLE_ENABLED, - attribute values are searchable by text queries in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - If SEARCHABLE_ENABLED but attribute type is numerical, - attribute values will not be searchable by text queries in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - as there are no text values associated to numerical - attributes. - """ - class AttributeType(proto.Enum): - r"""The type of an attribute.""" - UNKNOWN = 0 - TEXTUAL = 1 - NUMERICAL = 2 - - class IndexableOption(proto.Enum): - r"""The status of the indexable option of a catalog attribute.""" - INDEXABLE_OPTION_UNSPECIFIED = 0 - INDEXABLE_ENABLED = 1 - INDEXABLE_DISABLED = 2 - - class DynamicFacetableOption(proto.Enum): - r"""The status of the dynamic facetable option of a catalog - attribute. - """ - DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 - DYNAMIC_FACETABLE_ENABLED = 1 - DYNAMIC_FACETABLE_DISABLED = 2 - - class SearchableOption(proto.Enum): - r"""The status of the searchable option of a catalog attribute.""" - SEARCHABLE_OPTION_UNSPECIFIED = 0 - SEARCHABLE_ENABLED = 1 - SEARCHABLE_DISABLED = 2 - - key = proto.Field( - proto.STRING, - number=1, - ) - in_use = proto.Field( - proto.BOOL, - number=9, - ) - type_ = proto.Field( - proto.ENUM, - number=10, - enum=AttributeType, - ) - indexable_option = proto.Field( - proto.ENUM, - number=5, - enum=IndexableOption, - ) - dynamic_facetable_option = proto.Field( - proto.ENUM, - number=6, - enum=DynamicFacetableOption, - ) - searchable_option = proto.Field( - proto.ENUM, - number=7, - enum=SearchableOption, - ) - - -class AttributesConfig(proto.Message): - r"""Catalog level attribute config. - - Attributes: - name (str): - Required. Immutable. The fully qualified resource name of - the attribute config. Format: - ``projects/*/locations/*/catalogs/*/attributesConfig`` - catalog_attributes (Mapping[str, google.cloud.retail_v2alpha.types.CatalogAttribute]): - Enable attribute(s) config at catalog level. For example, - indexable, dynamic_facetable, or searchable for each - attribute. - - The key is catalog attribute's name. For example: ``color``, - ``brands``, ``attributes.custom_attribute``, such as - ``attributes.xyz``. - - The maximum number of catalog attributes allowed in a - request is 1000. - attribute_config_level (google.cloud.retail_v2alpha.types.AttributeConfigLevel): - Output only. The - [AttributeConfigLevel][google.cloud.retail.v2alpha.AttributeConfigLevel] - used for this catalog. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - catalog_attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='CatalogAttribute', - ) - attribute_config_level = proto.Field( - proto.ENUM, - number=3, - enum=common.AttributeConfigLevel, - ) - - -class CompletionConfig(proto.Message): - r"""Catalog level autocomplete config for customers to customize - autocomplete feature's settings. - - Attributes: - name (str): - Required. Immutable. Fully qualified name - ``projects/*/locations/*/catalogs/*/completionConfig`` - matching_order (str): - Specifies the matching order for autocomplete suggestions, - e.g., a query consisting of 'sh' with 'out-of-order' - specified would suggest "women's shoes", whereas a query of - 'red s' with 'exact-prefix' specified would suggest "red - shoes". Currently supported values: - - - 'out-of-order' - - 'exact-prefix' - - Default value: 'exact-prefix'. - max_suggestions (int): - The maximum number of autocomplete - suggestions returned per term. The maximum - allowed max suggestions is 20. Default value is - 20. If left unset or set to 0, then will - fallback to default value. - min_prefix_length (int): - The minimum number of characters needed to be - typed in order to get suggestions. Default value - is 2. If left unset or set to 0, then will - fallback to default value. - auto_learning (bool): - If set to true, the auto learning function is enabled. Auto - learning uses user data to generate suggestions using ML - techniques. Default value is false. Only after enabling auto - learning can users use ``cloud-retail`` data in - [CompleteQueryRequest][google.cloud.retail.v2alpha.CompleteQueryRequest]. - suggestions_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the - autocomplete phrases uploaded by the customer. - last_suggestions_import_operation (str): - Output only. Name of the LRO corresponding to the latest - suggestion terms list import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - denylist_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the / - autocomplete denylist phrases uploaded by the - customer. - last_denylist_import_operation (str): - Output only. LRO corresponding to the latest denylist - import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - allowlist_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the - autocomplete allowlist phrases uploaded by the - customer. - last_allowlist_import_operation (str): - Output only. LRO corresponding to the latest allowlist - import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - matching_order = proto.Field( - proto.STRING, - number=2, - ) - max_suggestions = proto.Field( - proto.INT32, - number=3, - ) - min_prefix_length = proto.Field( - proto.INT32, - number=4, - ) - auto_learning = proto.Field( - proto.BOOL, - number=11, - ) - suggestions_input_config = proto.Field( - proto.MESSAGE, - number=5, - message=import_config.CompletionDataInputConfig, - ) - last_suggestions_import_operation = proto.Field( - proto.STRING, - number=6, - ) - denylist_input_config = proto.Field( - proto.MESSAGE, - number=7, - message=import_config.CompletionDataInputConfig, - ) - last_denylist_import_operation = proto.Field( - proto.STRING, - number=8, - ) - allowlist_input_config = proto.Field( - proto.MESSAGE, - number=9, - message=import_config.CompletionDataInputConfig, - ) - last_allowlist_import_operation = proto.Field( - proto.STRING, - number=10, - ) - - -class MerchantCenterLink(proto.Message): - r"""Represents a link between a Merchant Center account and a - branch. Once a link is established, products from the linked - merchant center account will be streamed to the linked branch. - - Attributes: - merchant_center_account_id (int): - Required. The linked `Merchant center account - id `__. - The account must be a standalone account or a sub-account of - a MCA. - branch_id (str): - The branch id (e.g. 0/1/2) within this catalog that products - from merchant_center_account_id are streamed to. When - updating this field, an empty value will use the currently - configured default branch. However, changing the default - branch later on won't change the linked branch here. - - A single branch id can only have one linked merchant center - account id. - destinations (Sequence[str]): - String representing the destination to import for, all if - left empty. List of possible values can be found here. - [https://support.google.com/merchants/answer/7501026] List - of allowed string values: "Shopping_ads", - "Buy_on_google_listings", "Display_ads", "Local_inventory - \_ads", "Free_listings", "Free_local_listings" NOTE: The - string values are case sensitive. - region_code (str): - Region code of offers to accept. 2-letter Uppercase ISO - 3166-1 alpha-2 code. List of values can be found - `here `__ - under the ``region`` tag. If left blank no region filtering - will be performed. - - Example value: ``US``. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. ISO - 639-1. - - This specifies the language of offers in Merchant Center - that will be accepted. If empty no language filtering will - be performed. - - Example value: ``en``. - """ - - merchant_center_account_id = proto.Field( - proto.INT64, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - destinations = proto.RepeatedField( - proto.STRING, - number=3, - ) - region_code = proto.Field( - proto.STRING, - number=4, - ) - language_code = proto.Field( - proto.STRING, - number=5, - ) - - -class MerchantCenterLinkingConfig(proto.Message): - r"""Configures Merchant Center linking. - Links contained in the config will be used to sync data from a - Merchant Center account to a Cloud Retail branch. - - Attributes: - links (Sequence[google.cloud.retail_v2alpha.types.MerchantCenterLink]): - Links between Merchant Center accounts and - branches. - """ - - links = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='MerchantCenterLink', - ) - - -class Catalog(proto.Message): - r"""The catalog configuration. - - Attributes: - name (str): - Required. Immutable. The fully qualified - resource name of the catalog. - display_name (str): - Required. Immutable. The catalog display name. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - product_level_config (google.cloud.retail_v2alpha.types.ProductLevelConfig): - Required. The product level configuration. - merchant_center_linking_config (google.cloud.retail_v2alpha.types.MerchantCenterLinkingConfig): - The Merchant Center linking configuration. - Once a link is added, the data stream from - Merchant Center to Cloud Retail will be enabled - automatically. The requester must have access to - the merchant center account in order to make - changes to this field. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - product_level_config = proto.Field( - proto.MESSAGE, - number=4, - message='ProductLevelConfig', - ) - merchant_center_linking_config = proto.Field( - proto.MESSAGE, - number=6, - message='MerchantCenterLinkingConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py deleted file mode 100644 index 21d9b1c2..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py +++ /dev/null @@ -1,453 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'UpdateCatalogRequest', - 'SetDefaultBranchRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'GetCompletionConfigRequest', - 'UpdateCompletionConfigRequest', - 'GetAttributesConfigRequest', - 'UpdateAttributesConfigRequest', - 'AddCatalogAttributeRequest', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - }, -) - - -class ListCatalogsRequest(proto.Message): - r"""Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - - Attributes: - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2alpha.Catalog]s under this - location, regardless of whether or not this location exists, - a PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of - [Catalog][google.cloud.retail.v2alpha.Catalog]s to return. - If unspecified, defaults to 50. The maximum allowed value is - 1000. Values above 1000 will be coerced to 1000. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [ListCatalogsResponse.next_page_token][google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token], - received from a previous - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListCatalogsResponse(proto.Message): - r"""Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - - Attributes: - catalogs (Sequence[google.cloud.retail_v2alpha.types.Catalog]): - All the customer's - [Catalog][google.cloud.retail.v2alpha.Catalog]s. - next_page_token (str): - A token that can be sent as - [ListCatalogsRequest.page_token][google.cloud.retail.v2alpha.ListCatalogsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - catalogs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateCatalogRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] - method. - - Attributes: - catalog (google.cloud.retail_v2alpha.types.Catalog): - Required. The [Catalog][google.cloud.retail.v2alpha.Catalog] - to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2alpha.Catalog], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2alpha.Catalog] 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 - [Catalog][google.cloud.retail.v2alpha.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - catalog = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class SetDefaultBranchRequest(proto.Message): - r"""Request message to set a specified branch as new default_branch. - - Attributes: - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - branch_id (str): - The final component of the resource name of a branch. - - This field must be one of "0", "1" or "2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If there are no sufficient active products in the targeted - branch and - [force][google.cloud.retail.v2alpha.SetDefaultBranchRequest.force] - is not set, a FAILED_PRECONDITION error is returned. - note (str): - Some note on this request, this can be retrieved by - [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch] - before next valid default branch set occurs. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - force (bool): - If set to true, it permits switching to a branch with - [branch_id][google.cloud.retail.v2alpha.SetDefaultBranchRequest.branch_id] - even if it has no sufficient active products. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - force = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetDefaultBranchRequest(proto.Message): - r"""Request message to show which branch is currently the default - branch. - - Attributes: - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - - -class GetDefaultBranchResponse(proto.Message): - r"""Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. - - Attributes: - branch (str): - Full resource name of the branch id currently - set as default branch. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when this branch is set to default. - note (str): - This corresponds to - [SetDefaultBranchRequest.note][google.cloud.retail.v2alpha.SetDefaultBranchRequest.note] - field, when this branch was set as default. - """ - - branch = proto.Field( - proto.STRING, - number=1, - ) - set_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - - -class GetCompletionConfigRequest(proto.Message): - r"""Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] - method. - - Attributes: - name (str): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateCompletionConfigRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] - method. - - Attributes: - completion_config (google.cloud.retail_v2alpha.types.CompletionConfig): - Required. The - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - 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 - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - """ - - completion_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.CompletionConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetAttributesConfigRequest(proto.Message): - r"""Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] - method. - - Attributes: - name (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateAttributesConfigRequest(proto.Message): - r"""Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] - method. - - Attributes: - attributes_config (google.cloud.retail_v2alpha.types.AttributesConfig): - Required. The - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - """ - - attributes_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.AttributesConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class AddCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - catalog_attribute (google.cloud.retail_v2alpha.types.CatalogAttribute): - Required. The - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - catalog_attribute = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_catalog.CatalogAttribute, - ) - - -class RemoveCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - key (str): - Required. The attribute name key of the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - key = proto.Field( - proto.STRING, - number=2, - ) - - -class ReplaceCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - catalog_attribute (google.cloud.retail_v2alpha.types.CatalogAttribute): - Required. The updated - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to update. The following are NOT supported: - - - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key] - - If not set, all supported fields are updated. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - catalog_attribute = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_catalog.CatalogAttribute, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py deleted file mode 100644 index 25fa2861..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py +++ /dev/null @@ -1,1179 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'AttributeConfigLevel', - 'SolutionType', - 'SearchSolutionUseCase', - 'Condition', - 'Rule', - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'LocalInventory', - }, -) - - -class AttributeConfigLevel(proto.Enum): - r"""At which level we offer configuration for attributes.""" - ATTRIBUTE_CONFIG_LEVEL_UNSPECIFIED = 0 - PRODUCT_LEVEL_ATTRIBUTE_CONFIG = 1 - CATALOG_LEVEL_ATTRIBUTE_CONFIG = 2 - - -class SolutionType(proto.Enum): - r"""The type of solution.""" - SOLUTION_TYPE_UNSPECIFIED = 0 - SOLUTION_TYPE_RECOMMENDATION = 1 - SOLUTION_TYPE_SEARCH = 2 - - -class SearchSolutionUseCase(proto.Enum): - r"""The use case of Cloud Retail Search.""" - SEARCH_SOLUTION_USE_CASE_UNSPECIFIED = 0 - SEARCH_SOLUTION_USE_CASE_SEARCH = 1 - SEARCH_SOLUTION_USE_CASE_BROWSE = 2 - - -class Condition(proto.Message): - r"""Metadata that is used to define a condition that triggers an action. - A valid condition must specify at least one of 'query_terms' or - 'products_filter'. If multiple fields are specified, the condition - is met if all the fields are satisfied e.g. if a set of query terms - and product_filter are set, then only items matching the - product_filter for requests with a query matching the query terms - wil get boosted. - - Attributes: - query_terms (Sequence[google.cloud.retail_v2alpha.types.Condition.QueryTerm]): - A list (up to 10 entries) of terms to match - the query on. If not specified, match all - queries. If many query terms are specified, the - condition is matched if any of the terms is a - match (i.e. using the OR operator). - active_time_range (Sequence[google.cloud.retail_v2alpha.types.Condition.TimeRange]): - Range of time(s) specifying when Condition is - active. Condition true if any time range - matches. - """ - - class QueryTerm(proto.Message): - r"""Query terms that we want to match on. - - Attributes: - value (str): - The value of the term to match on. - Value cannot be empty. - Value can have at most 3 terms if specified as a - partial match. Each space separated string is - considered as one term. Example) "a b c" is 3 - terms and allowed, " a b c d" is 4 terms and not - allowed for partial match. - full_match (bool): - Whether this is supposed to be a full or - partial match. - """ - - value = proto.Field( - proto.STRING, - number=1, - ) - full_match = proto.Field( - proto.BOOL, - number=2, - ) - - class TimeRange(proto.Message): - r"""Used for time-dependent conditions. - Example: Want to have rule applied for week long sale. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start of time range. Range is inclusive. - end_time (google.protobuf.timestamp_pb2.Timestamp): - End of time range. Range is inclusive. - """ - - start_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - query_terms = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=QueryTerm, - ) - active_time_range = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=TimeRange, - ) - - -class Rule(proto.Message): - r"""A rule is a condition-action pair - - - A condition defines when a rule is to be triggered. - - An action specifies what occurs on that trigger. Currently only - boost rules are supported. Currently only supported by the search - endpoint. - - 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: - boost_action (google.cloud.retail_v2alpha.types.Rule.BoostAction): - A boost action. - - This field is a member of `oneof`_ ``action``. - redirect_action (google.cloud.retail_v2alpha.types.Rule.RedirectAction): - Redirects a shopper to a specific page. - - This field is a member of `oneof`_ ``action``. - oneway_synonyms_action (google.cloud.retail_v2alpha.types.Rule.OnewaySynonymsAction): - Treats specific term as a synonym with a - group of terms. Group of terms will not be - treated as synonyms with the specific term. - - This field is a member of `oneof`_ ``action``. - do_not_associate_action (google.cloud.retail_v2alpha.types.Rule.DoNotAssociateAction): - Prevents term from being associated with - other terms. - - This field is a member of `oneof`_ ``action``. - replacement_action (google.cloud.retail_v2alpha.types.Rule.ReplacementAction): - Replaces specific terms in the query. - - This field is a member of `oneof`_ ``action``. - ignore_action (google.cloud.retail_v2alpha.types.Rule.IgnoreAction): - Ignores specific terms from query during - search. - - This field is a member of `oneof`_ ``action``. - filter_action (google.cloud.retail_v2alpha.types.Rule.FilterAction): - Filters results. - - This field is a member of `oneof`_ ``action``. - twoway_synonyms_action (google.cloud.retail_v2alpha.types.Rule.TwowaySynonymsAction): - Treats a set of terms as synonyms of one - another. - - This field is a member of `oneof`_ ``action``. - condition (google.cloud.retail_v2alpha.types.Condition): - Required. The condition that triggers the - rule. If the condition is empty, the rule will - always apply. - """ - - class BoostAction(proto.Message): - r"""A boost action to apply to results matching condition - specified above. - - Attributes: - boost (float): - Strength of the condition boost, which must be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - products_filter (str): - The filter can have a max size of 5000 characters. An - expression which specifies which products to apply an action - to. The syntax and supported fields are the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": *(id: - ANY("product_1", "product_2"))* *AND* *(colorFamilies: - ANY("Red", "Blue"))* - """ - - boost = proto.Field( - proto.FLOAT, - number=1, - ) - products_filter = proto.Field( - proto.STRING, - number=2, - ) - - class FilterAction(proto.Message): - r"""- Rule Condition: - - - No [Condition][query_terms] provided is a global match. - - 1 or more [Condition][query_terms] provided is combined with - OR operator. - - - Action Input: The request query and filter that will be applied - to the retrieved products, in addition to any filters already - provided with the SearchRequest. The AND operator is used to - combine the query's existing filters with the filter rule(s). - NOTE: May result in 0 results when filters conflict. - - Action Result: Filters the returned objects to be ONLY those that - passed the filter. - - Attributes: - filter (str): - A filter to apply on the matching condition results. - Supported features: - - - [filter][google.cloud.retail.v2alpha.Rule.FilterAction.filter] - must be set. - - Filter syntax is identical to - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter]. - See more details at the Retail Search `user - guide `__. - - To filter products with product ID "product_1" or - "product_2", and color "Red" or "Blue": *(id: - ANY("product_1", "product_2"))* *AND* *(colorFamilies: - ANY("Red", "Blue"))* - """ - - filter = proto.Field( - proto.STRING, - number=1, - ) - - class RedirectAction(proto.Message): - r"""Redirects a shopper to a specific page. - - - Rule Condition: - - - Must specify [Condition][query_terms]. - - - Action Input: Request Query - - Action Result: Redirects shopper to provided uri. - - Attributes: - redirect_uri (str): - URL must have length equal or less than 2000 - characters. - """ - - redirect_uri = proto.Field( - proto.STRING, - number=1, - ) - - class TwowaySynonymsAction(proto.Message): - r"""Creates a set of terms that will be treated as synonyms of each - other. Example: synonyms of "sneakers" and "shoes". - - - "sneakers" will use a synonym of "shoes". - - "shoes" will use a synonym of "sneakers". - - Attributes: - synonyms (Sequence[str]): - Defines a set of synonyms. - Can specify up to 100 synonyms. - Must specify at least 2 synonyms. - """ - - synonyms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class OnewaySynonymsAction(proto.Message): - r"""Maps a set of terms to a set of synonyms. Set of synonyms will be - treated as synonyms of each query term only. ``query_terms`` will - not be treated as synonyms of each other. Example: "sneakers" will - use a synonym of "shoes". "shoes" will not use a synonym of - "sneakers". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. - Will treat synonyms as their synonyms. - Not themselves synonyms of the synonyms. - Can specify up to 100 terms. - synonyms (Sequence[str]): - Defines a set of synonyms. - Cannot contain duplicates. - Can specify up to 100 synonyms. - oneway_terms (Sequence[str]): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=3, - ) - synonyms = proto.RepeatedField( - proto.STRING, - number=4, - ) - oneway_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class DoNotAssociateAction(proto.Message): - r"""Prevents ``query_term`` from being associated with specified terms - during search. Example: Don't associate "gShoe" and "cheap". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. Will not consider - do_not_associate_terms for search if in search query. Can - specify up to 100 terms. - do_not_associate_terms (Sequence[str]): - Cannot contain duplicates or the query term. - Can specify up to 100 terms. - terms (Sequence[str]): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - do_not_associate_terms = proto.RepeatedField( - proto.STRING, - number=3, - ) - terms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class ReplacementAction(proto.Message): - r"""Replaces a term in the query. Multiple replacement candidates can be - specified. All ``query_terms`` will be replaced with the replacement - term. Example: Replace "gShoe" with "google shoe". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. - Will be replaced by replacement term. - Can specify up to 100 terms. - replacement_term (str): - Term that will be used for replacement. - term (str): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - replacement_term = proto.Field( - proto.STRING, - number=3, - ) - term = proto.Field( - proto.STRING, - number=1, - ) - - class IgnoreAction(proto.Message): - r"""Prevents a term in the query from being used in search. - Example: Don't search for "shoddy". - - Attributes: - ignore_terms (Sequence[str]): - Terms to ignore in the search query. - """ - - ignore_terms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - boost_action = proto.Field( - proto.MESSAGE, - number=2, - oneof='action', - message=BoostAction, - ) - redirect_action = proto.Field( - proto.MESSAGE, - number=3, - oneof='action', - message=RedirectAction, - ) - oneway_synonyms_action = proto.Field( - proto.MESSAGE, - number=6, - oneof='action', - message=OnewaySynonymsAction, - ) - do_not_associate_action = proto.Field( - proto.MESSAGE, - number=7, - oneof='action', - message=DoNotAssociateAction, - ) - replacement_action = proto.Field( - proto.MESSAGE, - number=8, - oneof='action', - message=ReplacementAction, - ) - ignore_action = proto.Field( - proto.MESSAGE, - number=9, - oneof='action', - message=IgnoreAction, - ) - filter_action = proto.Field( - proto.MESSAGE, - number=10, - oneof='action', - message=FilterAction, - ) - twoway_synonyms_action = proto.Field( - proto.MESSAGE, - number=11, - oneof='action', - message=TwowaySynonymsAction, - ) - condition = proto.Field( - proto.MESSAGE, - number=1, - message='Condition', - ) - - -class Audience(proto.Message): - r"""An intended audience of the - [Product][google.cloud.retail.v2alpha.Product] for whom it's sold. - - Attributes: - genders (Sequence[str]): - The genders of the audience. Strongly encouraged to use the - standard values: "male", "female", "unisex". - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `gender `__. - Schema.org property - `Product.audience.suggestedGender `__. - age_groups (Sequence[str]): - The age groups of the audience. Strongly encouraged to use - the standard values: "newborn" (up to 3 months old), - "infant" (3–12 months old), "toddler" (1–5 years old), - "kids" (5–13 years old), "adult" (typically teens or older). - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `age_group `__. - Schema.org property - `Product.audience.suggestedMinAge `__ - and - `Product.audience.suggestedMaxAge `__. - """ - - genders = proto.RepeatedField( - proto.STRING, - number=1, - ) - age_groups = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class ColorInfo(proto.Message): - r"""The color information of a - [Product][google.cloud.retail.v2alpha.Product]. - - Attributes: - color_families (Sequence[str]): - The standard color families. Strongly recommended to use the - following standard color groups: "Red", "Pink", "Orange", - "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", - "White", "Gray", "Black" and "Mixed". Normally it is - expected to have only 1 color family. May consider using - single "Mixed" instead of multiple values. - - A maximum of 5 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - colors (Sequence[str]): - The color display names, which may be different from - standard color family names, such as the color aliases used - in the website frontend. Normally it is expected to have - only 1 color. May consider using single "Mixed" instead of - multiple values. - - A maximum of 25 colors are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - """ - - color_families = proto.RepeatedField( - proto.STRING, - number=1, - ) - colors = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class CustomAttribute(proto.Message): - r"""A custom attribute that is not explicitly modeled in - [Product][google.cloud.retail.v2alpha.Product]. - - Attributes: - text (Sequence[str]): - The textual values of this custom attribute. For example, - ``["yellow", "green"]`` when the key is "color". - - Empty string is not allowed. Otherwise, an INVALID_ARGUMENT - error is returned. - - Exactly one of - [text][google.cloud.retail.v2alpha.CustomAttribute.text] or - [numbers][google.cloud.retail.v2alpha.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - numbers (Sequence[float]): - The numerical values of this custom attribute. For example, - ``[2.3, 15.4]`` when the key is "lengths_cm". - - Exactly one of - [text][google.cloud.retail.v2alpha.CustomAttribute.text] or - [numbers][google.cloud.retail.v2alpha.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - searchable (bool): - This field will only be used when - [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] - of the [Catalog][google.cloud.retail.v2alpha.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are searchable by text queries in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2alpha.UserEvent]. - - Only set if type - [text][google.cloud.retail.v2alpha.CustomAttribute.text] is - set. Otherwise, a INVALID_ARGUMENT error is returned. - - This field is a member of `oneof`_ ``_searchable``. - indexable (bool): - This field will only be used when - [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] - of the [Catalog][google.cloud.retail.v2alpha.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are indexed, so that it can be filtered, faceted or - boosted in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2alpha.UserEvent]. - - See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter], - [SearchRequest.facet_specs][google.cloud.retail.v2alpha.SearchRequest.facet_specs] - and - [SearchRequest.boost_spec][google.cloud.retail.v2alpha.SearchRequest.boost_spec] - for more details. - - This field is a member of `oneof`_ ``_indexable``. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - numbers = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - searchable = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - indexable = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - -class FulfillmentInfo(proto.Message): - r"""Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - Attributes: - type_ (str): - The fulfillment type, including commonly used types (such as - pickup in store and same day delivery), and custom types. - Customers have to map custom types to their display names - before rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - place_ids (Sequence[str]): - The IDs for this - [type][google.cloud.retail.v2alpha.FulfillmentInfo.type], - such as the store IDs for - [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2alpha.FulfillmentInfo.type] - or the region IDs for - [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2alpha.FulfillmentInfo.type]. - - A maximum of 3000 values are allowed. Each value must be a - string with a length limit of 30 characters, matching the - pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". - Otherwise, an INVALID_ARGUMENT error is returned. - """ - - type_ = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class Image(proto.Message): - r"""[Product][google.cloud.retail.v2alpha.Product] image. - Recommendations AI and Retail Search do not use product images to - improve prediction and search results. However, product images can - be returned in results, and are shown in prediction or search - previews in the console. - - Attributes: - uri (str): - Required. URI of the image. - - This field must be a valid UTF-8 encoded URI with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - height (int): - Height of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - width (int): - Width of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - height = proto.Field( - proto.INT32, - number=2, - ) - width = proto.Field( - proto.INT32, - number=3, - ) - - -class Interval(proto.Message): - r"""A floating point interval. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - minimum (float): - Inclusive lower bound. - - This field is a member of `oneof`_ ``min``. - exclusive_minimum (float): - Exclusive lower bound. - - This field is a member of `oneof`_ ``min``. - maximum (float): - Inclusive upper bound. - - This field is a member of `oneof`_ ``max``. - exclusive_maximum (float): - Exclusive upper bound. - - This field is a member of `oneof`_ ``max``. - """ - - minimum = proto.Field( - proto.DOUBLE, - number=1, - oneof='min', - ) - exclusive_minimum = proto.Field( - proto.DOUBLE, - number=2, - oneof='min', - ) - maximum = proto.Field( - proto.DOUBLE, - number=3, - oneof='max', - ) - exclusive_maximum = proto.Field( - proto.DOUBLE, - number=4, - oneof='max', - ) - - -class PriceInfo(proto.Message): - r"""The price information of a - [Product][google.cloud.retail.v2alpha.Product]. - - Attributes: - currency_code (str): - The 3-letter currency code defined in `ISO - 4217 `__. - - If this field is an unrecognizable currency code, an - INVALID_ARGUMENT error is returned. - - The - [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s with the - same - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] - must share the same - [currency_code][google.cloud.retail.v2alpha.PriceInfo.currency_code]. - Otherwise, a FAILED_PRECONDITION error is returned. - price (float): - Price of the product. - - Google Merchant Center property - `price `__. - Schema.org property - `Offer.price `__. - original_price (float): - Price of the product without any discount. If zero, by - default set to be the - [price][google.cloud.retail.v2alpha.PriceInfo.price]. - cost (float): - The costs associated with the sale of a particular product. - Used for gross profit reporting. - - - Profit = - [price][google.cloud.retail.v2alpha.PriceInfo.price] - - [cost][google.cloud.retail.v2alpha.PriceInfo.cost] - - Google Merchant Center property - `cost_of_goods_sold `__. - price_effective_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2alpha.PriceInfo.price] starts - to be effective. This can be set as a future timestamp, and - the [price][google.cloud.retail.v2alpha.PriceInfo.price] is - only used for search after - [price_effective_time][google.cloud.retail.v2alpha.PriceInfo.price_effective_time]. - If so, the - [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - is used before - [price_effective_time][google.cloud.retail.v2alpha.PriceInfo.price_effective_time]. - - Do not set if - [price][google.cloud.retail.v2alpha.PriceInfo.price] is - always effective because it will cause additional latency - during search. - price_expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2alpha.PriceInfo.price] stops - to be effective. The - [price][google.cloud.retail.v2alpha.PriceInfo.price] is used - for search before - [price_expire_time][google.cloud.retail.v2alpha.PriceInfo.price_expire_time]. - If this field is set, the - [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - is used after - [price_expire_time][google.cloud.retail.v2alpha.PriceInfo.price_expire_time]. - - Do not set if - [price][google.cloud.retail.v2alpha.PriceInfo.price] is - always effective because it will cause additional latency - during search. - price_range (google.cloud.retail_v2alpha.types.PriceInfo.PriceRange): - Output only. The price range of all the child - [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s grouped - together on the - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]. Only - populated for - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct]. - Do not set this field in API requests. - """ - - class PriceRange(proto.Message): - r"""The price range of all - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. - - Attributes: - price (google.cloud.retail_v2alpha.types.Interval): - The inclusive - [Product.pricing_info.price][google.cloud.retail.v2alpha.PriceInfo.price] - interval of all - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] having the - same - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. - original_price (google.cloud.retail_v2alpha.types.Interval): - The inclusive - [Product.pricing_info.original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - internal of all - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] having the - same - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. - """ - - price = proto.Field( - proto.MESSAGE, - number=1, - message='Interval', - ) - original_price = proto.Field( - proto.MESSAGE, - number=2, - message='Interval', - ) - - currency_code = proto.Field( - proto.STRING, - number=1, - ) - price = proto.Field( - proto.FLOAT, - number=2, - ) - original_price = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - price_effective_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - price_expire_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - price_range = proto.Field( - proto.MESSAGE, - number=7, - message=PriceRange, - ) - - -class Rating(proto.Message): - r"""The rating of a [Product][google.cloud.retail.v2alpha.Product]. - - Attributes: - rating_count (int): - The total number of ratings. This value is independent of - the value of - [rating_histogram][google.cloud.retail.v2alpha.Rating.rating_histogram]. - - This value must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - average_rating (float): - The average rating of the - [Product][google.cloud.retail.v2alpha.Product]. - - The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT - error is returned. - rating_histogram (Sequence[int]): - List of rating counts per rating value (index = rating - 1). - The list is empty if there is no rating. If the list is - non-empty, its size is always 5. Otherwise, an - INVALID_ARGUMENT error is returned. - - For example, [41, 14, 13, 47, 303]. It means that the - [Product][google.cloud.retail.v2alpha.Product] got 41 - ratings with 1 star, 14 ratings with 2 star, and so on. - """ - - rating_count = proto.Field( - proto.INT32, - number=1, - ) - average_rating = proto.Field( - proto.FLOAT, - number=2, - ) - rating_histogram = proto.RepeatedField( - proto.INT32, - number=3, - ) - - -class UserInfo(proto.Message): - r"""Information of an end user. - - Attributes: - user_id (str): - Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. - - Always use a hashed value for this ID. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - ip_address (str): - The end user's IP address. This field is used to extract - location information for personalization. - - This field must be either an IPv4 address (e.g. - "104.133.9.80") or an IPv6 address (e.g. - "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an - INVALID_ARGUMENT error is returned. - - This should not be set when: - - - setting - [SearchRequest.user_info][google.cloud.retail.v2alpha.SearchRequest.user_info]. - - using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2alpha.UserInfo.direct_user_request] - is set. - user_agent (str): - User agent as included in the HTTP header. Required for - getting - [SearchResponse.sponsored_results][google.cloud.retail.v2alpha.SearchResponse.sponsored_results]. - - The field must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This should not be set when using the client side event - reporting with GTM or JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2alpha.UserInfo.direct_user_request] - is set. - direct_user_request (bool): - True if the request is made directly from the end user, in - which case the - [ip_address][google.cloud.retail.v2alpha.UserInfo.ip_address] - and - [user_agent][google.cloud.retail.v2alpha.UserInfo.user_agent] - can be populated from the HTTP request. This flag should be - set only if the API request is made directly from the end - user such as a mobile app (and not if a gateway or a server - is processing and pushing the user events). - - This should not be set when using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent]. - """ - - user_id = proto.Field( - proto.STRING, - number=1, - ) - ip_address = proto.Field( - proto.STRING, - number=2, - ) - user_agent = proto.Field( - proto.STRING, - number=3, - ) - direct_user_request = proto.Field( - proto.BOOL, - number=4, - ) - - -class LocalInventory(proto.Message): - r"""The inventory information at a place (e.g. a store) - identified by a place ID. - - Attributes: - place_id (str): - The place ID for the current set of inventory - information. - price_info (google.cloud.retail_v2alpha.types.PriceInfo): - Product price and cost information. - - Google Merchant Center property - `price `__. - attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): - Additional local inventory attributes, for example, store - name, promotion tags, etc. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - At most 30 attributes are allowed. - - The key must be a UTF-8 encoded string with a length - limit of 32 characters. - - The key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis - or KEY_1_LIKE_THIS. - - The attribute values must be of the same type (text or - number). - - Only 1 value is allowed for each attribute. - - For text values, the length limit is 256 UTF-8 - characters. - - The attribute does not support search. The ``searchable`` - field should be unset or set to false. - - The max summed total bytes of custom attribute keys and - values per product is 5MiB. - fulfillment_types (Sequence[str]): - Input only. Supported fulfillment types. Valid fulfillment - type values include commonly used types (such as pickup in - store and same day delivery), and custom types. Customers - have to map custom types to their display names before - rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - All the elements must be distinct. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - place_id = proto.Field( - proto.STRING, - number=1, - ) - price_info = proto.Field( - proto.MESSAGE, - number=2, - message='PriceInfo', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='CustomAttribute', - ) - fulfillment_types = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py deleted file mode 100644 index f3bb27b3..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'CompleteQueryRequest', - 'CompleteQueryResponse', - }, -) - - -class CompleteQueryRequest(proto.Message): - r"""Auto-complete parameters. - - Attributes: - catalog (str): - Required. Catalog for which the completion is performed. - - Full resource name of catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - query (str): - Required. The query used to generate - suggestions. - The maximum number of allowed characters is 255. - visitor_id (str): - Required field. A unique identifier for tracking visitors. - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - language_codes (Sequence[str]): - The language filters applied to the output suggestions. If - set, it should contain the language of the query. If not - set, suggestions are returned without considering language - restrictions. This is the BCP-47 language code, such as - "en-US" or "sr-Latn". For more information, see `Tags for - Identifying - Languages `__. The - maximum number of language codes is 3. - device_type (str): - The device type context for completion suggestions. It is - useful to apply different suggestions on different device - types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the - suggestions are across all device types. - - Supported formats: - - - ``UNKNOWN_DEVICE_TYPE`` - - - ``DESKTOP`` - - - ``MOBILE`` - - - A customized string starts with ``OTHER_``, e.g. - ``OTHER_IPHONE``. - dataset (str): - Determines which dataset to use for fetching completion. - "user-data" will use the imported dataset through - [CompletionService.ImportCompletionData][google.cloud.retail.v2alpha.CompletionService.ImportCompletionData]. - "cloud-retail" will use the dataset generated by cloud - retail based on user events. If leave empty, it will use the - "user-data". - - Current supported values: - - - user-data - - - cloud-retail This option requires additional - allowlisting. Before using cloud-retail, contact Cloud - Retail support team first. - max_suggestions (int): - Completion max suggestions. If left unset or set to 0, then - will fallback to the configured value - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions]. - - The maximum allowed max suggestions is 20. If it is set - higher, it will be capped by 20. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - visitor_id = proto.Field( - proto.STRING, - number=7, - ) - language_codes = proto.RepeatedField( - proto.STRING, - number=3, - ) - device_type = proto.Field( - proto.STRING, - number=4, - ) - dataset = proto.Field( - proto.STRING, - number=6, - ) - max_suggestions = proto.Field( - proto.INT32, - number=5, - ) - - -class CompleteQueryResponse(proto.Message): - r"""Response of the auto-complete query. - - Attributes: - completion_results (Sequence[google.cloud.retail_v2alpha.types.CompleteQueryResponse.CompletionResult]): - Results of the matching suggestions. The - result list is ordered and the first result is - top suggestion. - attribution_token (str): - A unique complete token. This should be included in the - [UserEvent.completion_detail][google.cloud.retail.v2alpha.UserEvent.completion_detail] - for search events resulting from this completion, which - enables accurate attribution of complete model performance. - recent_search_results (Sequence[google.cloud.retail_v2alpha.types.CompleteQueryResponse.RecentSearchResult]): - Matched recent searches of this user. The maximum number of - recent searches is 10. This field is a restricted feature. - Contact Retail Search support team if you are interested in - enabling it. - - This feature is only available when - [CompleteQueryRequest.visitor_id][google.cloud.retail.v2alpha.CompleteQueryRequest.visitor_id] - field is set and - [UserEvent][google.cloud.retail.v2alpha.UserEvent] is - imported. The recent searches satisfy the follow rules: - - - They are ordered from latest to oldest. - - They are matched with - [CompleteQueryRequest.query][google.cloud.retail.v2alpha.CompleteQueryRequest.query] - case insensitively. - - They are transformed to lower cases. - - They are UTF-8 safe. - - Recent searches are deduplicated. More recent searches will - be reserved when duplication happens. - """ - - class CompletionResult(proto.Message): - r"""Resource that represents completion results. - - Attributes: - suggestion (str): - The suggestion for the query. - attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): - Custom attributes for the suggestion term. - - - For "user-data", the attributes are additional custom - attributes ingested through BigQuery. - - For "cloud-retail", the attributes are product attributes - generated by Cloud Retail. - """ - - suggestion = proto.Field( - proto.STRING, - number=1, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=common.CustomAttribute, - ) - - class RecentSearchResult(proto.Message): - r"""Recent search of this user. - - Attributes: - recent_search (str): - The recent search query. - """ - - recent_search = proto.Field( - proto.STRING, - number=1, - ) - - completion_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=CompletionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - recent_search_results = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=RecentSearchResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py deleted file mode 100644 index 93e84d08..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py +++ /dev/null @@ -1,123 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'Control', - }, -) - - -class Control(proto.Message): - r"""Configures dynamic serving time metadata that is used to pre - and post process search/recommendation model results. - - 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: - facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec): - A facet specification to perform faceted - search. - - This field is a member of `oneof`_ ``control``. - rule (google.cloud.retail_v2alpha.types.Rule): - A rule control - a condition-action pair. - Enacts a set action when the condition is - triggered. For example: Boost "gShoe" when query - full matches "Running Shoes". - - This field is a member of `oneof`_ ``control``. - name (str): - Immutable. Fully qualified name - projects/\ */locations/global/catalogs/*/controls/\* - display_name (str): - Required. The human readable control display name. Used in - Retail UI. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is thrown. - associated_serving_config_ids (Sequence[str]): - Output only. List of serving configuration - ids that that are associated with this control. - Note the association is managed via the - ServingConfig, this is an output only - denormalizeed view. Assumed to be in the same - catalog. - solution_types (Sequence[google.cloud.retail_v2alpha.types.SolutionType]): - Required. Immutable. The solution types that the serving - config is used for. Currently we support setting only one - type of solution at creation time. - - Only ``SOLUTION_TYPE_SEARCH`` value is supported at the - moment. If no solution type is provided at creation time, - will default to SOLUTION_TYPE_SEARCH. - search_solution_use_case (Sequence[google.cloud.retail_v2alpha.types.SearchSolutionUseCase]): - Required. Specifies the use case for the control. Affects - what condition fields can be set. Only settable by search - controls. Will default to SEARCH_SOLUTION_USE_CASE_SEARCH if - not specified. Currently only allow one - search_solution_use_case per control. - """ - - facet_spec = proto.Field( - proto.MESSAGE, - number=3, - oneof='control', - message=search_service.SearchRequest.FacetSpec, - ) - rule = proto.Field( - proto.MESSAGE, - number=4, - oneof='control', - message=common.Rule, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - associated_serving_config_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - solution_types = proto.RepeatedField( - proto.ENUM, - number=6, - enum=common.SolutionType, - ) - search_solution_use_case = proto.RepeatedField( - proto.ENUM, - number=7, - enum=common.SearchSolutionUseCase, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py deleted file mode 100644 index da0c4915..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py +++ /dev/null @@ -1,197 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'CreateControlRequest', - 'UpdateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - }, -) - - -class CreateControlRequest(proto.Message): - r"""Request for CreateControl method. - - Attributes: - parent (str): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - control (google.cloud.retail_v2alpha.types.Control): - Required. The Control to create. - control_id (str): - Required. The ID to use for the Control, which will become - the final component of the Control's resource name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-_/. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - control = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_control.Control, - ) - control_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateControlRequest(proto.Message): - r"""Request for UpdateControl method. - - Attributes: - control (google.cloud.retail_v2alpha.types.Control): - Required. The Control to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Control][google.cloud.retail.v2alpha.Control] to update. - The following are NOT supported: - - - [Control.name][google.cloud.retail.v2alpha.Control.name] - - If not set or empty, all supported fields are updated. - """ - - control = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_control.Control, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteControlRequest(proto.Message): - r"""Request for DeleteControl method. - - Attributes: - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetControlRequest(proto.Message): - r"""Request for GetControl method. - - Attributes: - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListControlsRequest(proto.Message): - r"""Request for ListControls method. - - Attributes: - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - page_size (int): - Optional. Maximum number of results to - return. If unspecified, defaults to 50. Max - allowed value is 1000. - page_token (str): - Optional. A page token, received from a previous - ``ListControls`` call. Provide this to retrieve the - subsequent page. - filter (str): - Optional. A filter to apply on the list results. Supported - features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2alpha.ListControlsRequest.filter] - is unset. - - List controls that are used in a single ServingConfig: - 'serving_config = "boosted_home_page_cvr"' - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListControlsResponse(proto.Message): - r"""Response for ListControls method. - - Attributes: - controls (Sequence[google.cloud.retail_v2alpha.types.Control]): - All the Controls for a given catalog. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - controls = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_control.Control, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py deleted file mode 100644 index ffb42fde..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py +++ /dev/null @@ -1,134 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - }, -) - - -class ExportErrorsConfig(proto.Message): - r"""Configuration of destination for Export related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage path for import errors. This must be an - empty, existing Cloud Storage bucket. Export errors will be - written to a file in this bucket, one per line, as a - JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ExportMetadata(proto.Message): - r"""Metadata related to the progress of the Export operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class ExportProductsResponse(proto.Message): - r"""Response of the ExportProductsRequest. If the long running - operation is done, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2alpha.types.ExportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExportErrorsConfig', - ) - - -class ExportUserEventsResponse(proto.Message): - r"""Response of the ExportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2alpha.types.ExportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExportErrorsConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py deleted file mode 100644 index b6260358..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py +++ /dev/null @@ -1,691 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import user_event -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'GcsSource', - 'BigQuerySource', - 'ProductInlineSource', - 'UserEventInlineSource', - 'ImportErrorsConfig', - 'ImportProductsRequest', - 'ImportUserEventsRequest', - 'ImportCompletionDataRequest', - 'ProductInputConfig', - 'UserEventInputConfig', - 'CompletionDataInputConfig', - 'ImportMetadata', - 'ImportProductsResponse', - 'ImportUserEventsResponse', - 'UserEventImportSummary', - 'ImportCompletionDataResponse', - }, -) - - -class GcsSource(proto.Message): - r"""Google Cloud Storage location for input content. - format. - - Attributes: - input_uris (Sequence[str]): - Required. Google Cloud Storage URIs to input files. URI can - be up to 2000 characters long. URIs can match the full - object path (for example, - ``gs://bucket/directory/object.json``) or a pattern matching - one or more files, such as ``gs://bucket/directory/*.json``. - A request can contain at most 100 files, and each file can - be up to 2 GB. See `Importing product - information `__ - for the expected file format and setup instructions. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2alpha.Product] per line. - Each product must have a valid - [Product.id][google.cloud.retail.v2alpha.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2alpha.UserEvent] per - line. - - ``user_event_ga360``: Using - https://support.google.com/analytics/answer/3437719. - - Supported values for control imports: - - - 'control' (default): One JSON - [Control][google.cloud.retail.v2alpha.Control] per line. - - Supported values for catalog attribute imports: - - - 'catalog_attribute' (default): One CSV - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - per line. - """ - - input_uris = proto.RepeatedField( - proto.STRING, - number=1, - ) - data_schema = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""BigQuery source import data from. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - partition_date (google.type.date_pb2.Date): - BigQuery time partitioned table's \_PARTITIONDATE in - YYYY-MM-DD format. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - - This field is a member of `oneof`_ ``partition``. - project_id (str): - The project ID (can be project # or ID) that - the BigQuery source is in with a length limit of - 128 characters. If not specified, inherits the - project ID from the parent request. - dataset_id (str): - Required. The BigQuery data set to copy the - data from with a length limit of 1,024 - characters. - table_id (str): - Required. The BigQuery table to copy the data - from with a length limit of 1,024 characters. - gcs_staging_dir (str): - Intermediate Cloud Storage directory used for - the import with a length limit of 2,000 - characters. Can be specified if one wants to - have the BigQuery export to a specific Cloud - Storage directory. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2alpha.Product] per line. - Each product must have a valid - [Product.id][google.cloud.retail.v2alpha.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2alpha.UserEvent] per - line. - - ``user_event_ga360``: The schema is available here: - https://support.google.com/analytics/answer/3437719. - - ``user_event_ga4``: This feature is in private preview. - Please contact the support team for importing Google - Analytics 4 events. The schema is available here: - https://support.google.com/analytics/answer/7029846. - - Supported values for auto-completion imports: - - - ``suggestions`` (default): One JSON completion suggestion - per line. - - ``denylist``: One JSON deny suggestion per line. - - ``allowlist``: One JSON allow suggestion per line. - """ - - partition_date = proto.Field( - proto.MESSAGE, - number=6, - oneof='partition', - message=date_pb2.Date, - ) - project_id = proto.Field( - proto.STRING, - number=5, - ) - dataset_id = proto.Field( - proto.STRING, - number=1, - ) - table_id = proto.Field( - proto.STRING, - number=2, - ) - gcs_staging_dir = proto.Field( - proto.STRING, - number=3, - ) - data_schema = proto.Field( - proto.STRING, - number=4, - ) - - -class ProductInlineSource(proto.Message): - r"""The inline source for the input config for ImportProducts - method. - - Attributes: - products (Sequence[google.cloud.retail_v2alpha.types.Product]): - Required. A list of products to update/create. Each product - must have a valid - [Product.id][google.cloud.retail.v2alpha.Product.id]. - Recommended max of 100 items. - """ - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=product.Product, - ) - - -class UserEventInlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (Sequence[google.cloud.retail_v2alpha.types.UserEvent]): - Required. A list of user events to import. - Recommended max of 10k items. - """ - - user_events = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - -class ImportErrorsConfig(proto.Message): - r"""Configuration of destination for Import related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage prefix for import errors. This must be - an empty, existing Cloud Storage directory. Import errors - will be written to sharded files in this directory, one per - line, as a JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportProductsRequest(proto.Message): - r"""Request message for Import methods. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` - - If no updateMask is specified, requires products.create - permission. If updateMask is specified, requires - products.update permission. - request_id (str): - Deprecated. This field has no effect. - input_config (google.cloud.retail_v2alpha.types.ProductInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - imported 'products' to update. If not set, will - by default update all fields. - reconciliation_mode (google.cloud.retail_v2alpha.types.ImportProductsRequest.ReconciliationMode): - The mode of reconciliation between existing products and the - products to be imported. Defaults to - [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - """ - class ReconciliationMode(proto.Enum): - r"""Indicates how imported products are reconciled with the - existing products created or imported before. - """ - RECONCILIATION_MODE_UNSPECIFIED = 0 - INCREMENTAL = 1 - FULL = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - request_id = proto.Field( - proto.STRING, - number=6, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='ProductInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - reconciliation_mode = proto.Field( - proto.ENUM, - number=5, - enum=ReconciliationMode, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=7, - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog`` - input_config (google.cloud.retail_v2alpha.types.UserEventInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. Cannot be set for inline user - event imports. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='UserEventInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - - -class ImportCompletionDataRequest(proto.Message): - r"""Request message for ImportCompletionData methods. - - Attributes: - parent (str): - Required. The catalog which the suggestions dataset belongs - to. - - Format: - ``projects/1234/locations/global/catalogs/default_catalog``. - input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): - Required. The desired input location of the - data. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='CompletionDataInputConfig', - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=3, - ) - - -class ProductInputConfig(proto.Message): - r"""The input config source for products. - - 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: - product_inline_source (google.cloud.retail_v2alpha.types.ProductInlineSource): - The Inline source for the input content for - products. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2alpha.types.GcsSource): - Google Cloud Storage location for the input - content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - product_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='ProductInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class UserEventInputConfig(proto.Message): - r"""The input config source for user events. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - user_event_inline_source (google.cloud.retail_v2alpha.types.UserEventInlineSource): - Required. The Inline source for the input - content for UserEvents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2alpha.types.GcsSource): - Required. Google Cloud Storage location for - the input content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): - Required. BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - user_event_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='UserEventInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class CompletionDataInputConfig(proto.Message): - r"""The input config source for completion data. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): - Required. BigQuery input source. - Add the IAM permission "BigQuery Data Viewer" - for - cloud-retail-customer-data-access@system.gserviceaccount.com - before using this feature otherwise an error is - thrown. - - This field is a member of `oneof`_ ``source``. - """ - - big_query_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='BigQuerySource', - ) - - -class ImportMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - request_id (str): - Deprecated. This field is never set. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=3, - ) - failure_count = proto.Field( - proto.INT64, - number=4, - ) - request_id = proto.Field( - proto.STRING, - number=5, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=6, - ) - - -class ImportProductsResponse(proto.Message): - r"""Response of the - [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. - If the long running operation is done, then this message is returned - by the google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - import_summary (google.cloud.retail_v2alpha.types.UserEventImportSummary): - Aggregated statistics of user event import - status. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - import_summary = proto.Field( - proto.MESSAGE, - number=3, - message='UserEventImportSummary', - ) - - -class UserEventImportSummary(proto.Message): - r"""A summary of import result. The UserEventImportSummary - summarizes the import status for user events. - - Attributes: - joined_events_count (int): - Count of user events imported with complete - existing catalog information. - unjoined_events_count (int): - Count of user events imported, but with - catalog information not found in the imported - catalog. - """ - - joined_events_count = proto.Field( - proto.INT64, - number=1, - ) - unjoined_events_count = proto.Field( - proto.INT64, - number=2, - ) - - -class ImportCompletionDataResponse(proto.Message): - r"""Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. - 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 (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py deleted file mode 100644 index 51233cae..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import user_event as gcr_user_event -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'PredictRequest', - 'PredictResponse', - }, -) - - -class PredictRequest(proto.Message): - r"""Request message for Predict method. - - Attributes: - placement (str): - Required. Full resource name of the format: - {name=projects/*/locations/global/catalogs/default_catalog/placements/*} - The ID of the Recommendations AI placement. Before you can - request predictions from your model, you must create at - least one placement for it. For more information, see - `Managing - placements `__. - - The full list of available placements can be seen at - https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements - user_event (google.cloud.retail_v2alpha.types.UserEvent): - Required. Context about the user, what they - are looking at and what action they took to - trigger the predict request. Note that this user - event detail won't be ingested to userEvent - logs. Thus, a separate userEvent write request - is required for event logging. - page_size (int): - Maximum number of results to return per page. - Set this property to the number of prediction - results needed. If zero, the service will choose - a reasonable default. The maximum allowed value - is 100. Values above 100 will be coerced to 100. - page_token (str): - The previous PredictResponse.next_page_token. - filter (str): - Filter for restricting prediction results with a length - limit of 5,000 characters. Accepts values for tags and the - ``filterOutOfStockItems`` flag. - - - Tag expressions. Restricts predictions to products that - match all of the specified tags. Boolean operators ``OR`` - and ``NOT`` are supported if the expression is enclosed - in parentheses, and must be separated from the tag values - by a space. ``-"tagA"`` is also supported and is - equivalent to ``NOT "tagA"``. Tag values must be double - quoted UTF-8 encoded strings with a size limit of 1,000 - characters. - - Note: "Recently viewed" models don't support tag - filtering at the moment. - - - filterOutOfStockItems. Restricts predictions to products - that do not have a stockState value of OUT_OF_STOCK. - - Examples: - - - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT - "promotional") - - filterOutOfStockItems tag=(-"promotional") - - filterOutOfStockItems - - If your filter blocks all prediction results, the API will - return generic (unfiltered) popular products. If you only - want results strictly matching the filters, set - ``strictFiltering`` to True in ``PredictRequest.params`` to - receive empty results instead. Note that the API will never - return items with storageStatus of "EXPIRED" or "DELETED" - regardless of filter choices. - validate_only (bool): - Use validate only mode for this prediction - query. If set to true, a dummy model will be - used that returns arbitrary products. Note that - the validate only mode should only be used for - testing the API, or if the model is not ready. - params (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional domain specific parameters for the predictions. - - Allowed values: - - - ``returnProduct``: Boolean. If set to true, the - associated product object will be returned in the - ``results.metadata`` field in the prediction response. - - ``returnScore``: Boolean. If set to true, the prediction - 'score' corresponding to each returned product will be - set in the ``results.metadata`` field in the prediction - response. The given 'score' indicates the probability of - an product being clicked/purchased given the user's - context and history. - - ``strictFiltering``: Boolean. True by default. If set to - false, the service will return generic (unfiltered) - popular products instead of empty if your filter blocks - all prediction results. - - ``priceRerankLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of - {'no-price-reranking', 'low-price-reranking', - 'medium-price-reranking', 'high-price-reranking'}. This - gives request-level control and adjusts prediction - results based on product price. - - ``diversityLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of {'no-diversity', - 'low-diversity', 'medium-diversity', 'high-diversity', - 'auto-diversity'}. This gives request-level control and - adjusts prediction results based on product category. - labels (Mapping[str, str]): - The labels applied to a resource must meet the following - requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters, and cannot be empty. Values can - be empty, and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - """ - - placement = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - validate_only = proto.Field( - proto.BOOL, - number=6, - ) - params = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class PredictResponse(proto.Message): - r"""Response message for predict method. - - Attributes: - results (Sequence[google.cloud.retail_v2alpha.types.PredictResponse.PredictionResult]): - A list of recommended products. The order - represents the ranking (from the most relevant - product to the least). - attribution_token (str): - A unique attribution token. This should be included in the - [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs - resulting from this recommendation, which enables accurate - attribution of recommendation model performance. - missing_ids (Sequence[str]): - IDs of products in the request that were - missing from the inventory. - validate_only (bool): - True if the validateOnly property was set in - the request. - """ - - class PredictionResult(proto.Message): - r"""PredictionResult represents the recommendation prediction - results. - - Attributes: - id (str): - ID of the recommended product - metadata (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional product metadata / annotations. - - Possible values: - - - ``product``: JSON representation of the product. Will be - set if ``returnProduct`` is set to true in - ``PredictRequest.params``. - - ``score``: Prediction score in double value. Will be set - if ``returnScore`` is set to true in - ``PredictRequest.params``. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - metadata = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=PredictionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - missing_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py deleted file mode 100644 index 492a51ff..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py +++ /dev/null @@ -1,705 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'Product', - }, -) - - -class Product(proto.Message): - r"""Product captures all metadata information of items to be - recommended or searched. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this product becomes unavailable for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - If it is set, the - [Product][google.cloud.retail.v2alpha.Product] is not - available for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - after - [expire_time][google.cloud.retail.v2alpha.Product.expire_time]. - However, the product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - [expire_time][google.cloud.retail.v2alpha.Product.expire_time] - must be later than - [available_time][google.cloud.retail.v2alpha.Product.available_time] - and - [publish_time][google.cloud.retail.v2alpha.Product.publish_time], - otherwise an INVALID_ARGUMENT error is thrown. - - Corresponding properties: Google Merchant Center property - `expiration_date `__. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Input only. The TTL (time to live) of the product. - - If it is set, it must be a non-negative value, and - [expire_time][google.cloud.retail.v2alpha.Product.expire_time] - is set as current timestamp plus - [ttl][google.cloud.retail.v2alpha.Product.ttl]. The derived - [expire_time][google.cloud.retail.v2alpha.Product.expire_time] - is returned in the output and - [ttl][google.cloud.retail.v2alpha.Product.ttl] is left blank - when retrieving the - [Product][google.cloud.retail.v2alpha.Product]. - - If it is set, the product is not available for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - after current timestamp plus - [ttl][google.cloud.retail.v2alpha.Product.ttl]. However, the - product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This field is a member of `oneof`_ ``expiration``. - name (str): - Immutable. Full resource name of the product, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. - id (str): - Immutable. [Product][google.cloud.retail.v2alpha.Product] - identifier, which is the final component of - [name][google.cloud.retail.v2alpha.Product.name]. For - example, this field is "id_1", if - [name][google.cloud.retail.v2alpha.Product.name] is - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `id `__. - Schema.org property - `Product.sku `__. - type_ (google.cloud.retail_v2alpha.types.Product.Type): - Immutable. The type of the product. Default to - [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2alpha.ProductLevelConfig.ingestion_product_type] - if unset. - primary_product_id (str): - Variant group identifier. Must be an - [id][google.cloud.retail.v2alpha.Product.id], with the same - parent branch with this product. Otherwise, an error is - thrown. - - For - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]s, this field - can only be empty or set to the same value as - [id][google.cloud.retail.v2alpha.Product.id]. - - For VARIANT [Product][google.cloud.retail.v2alpha.Product]s, - this field cannot be empty. A maximum of 2,000 products are - allowed to share the same - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]. Otherwise, - an INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `item_group_id `__. - Schema.org property - `Product.inProductGroupWithID `__. - collection_member_ids (Sequence[str]): - The [id][google.cloud.retail.v2alpha.Product.id] of the - collection members when - [type][google.cloud.retail.v2alpha.Product.type] is - [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION]. - - Non-existent product ids are allowed. The - [type][google.cloud.retail.v2alpha.Product.type] of the - members must be either - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - or - [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - otherwise and INVALID_ARGUMENT error is thrown. Should not - set it for other types. A maximum of 1000 values are - allowed. Otherwise, an INVALID_ARGUMENT error is return. - gtin (str): - The Global Trade Item Number (GTIN) of the product. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This field must be a Unigram. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `gtin `__. - Schema.org property - `Product.isbn `__, - `Product.gtin8 `__, - `Product.gtin12 `__, - `Product.gtin13 `__, or - `Product.gtin14 `__. - - If the value is not a valid GTIN, an INVALID_ARGUMENT error - is returned. - categories (Sequence[str]): - Product categories. This field is repeated for supporting - one product belonging to several parallel categories. - Strongly recommended using the full path for better search / - recommendation quality. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - For example, if a shoes product belongs to both ["Shoes & - Accessories" -> "Shoes"] and ["Sports & Fitness" -> - "Athletic Clothing" -> "Shoes"], it could be represented as: - - :: - - "categories": [ - "Shoes & Accessories > Shoes", - "Sports & Fitness > Athletic Clothing > Shoes" - ] - - Must be set for - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] otherwise an - INVALID_ARGUMENT error is returned. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. Empty values - are not allowed. Each value must be a UTF-8 encoded string - with a length limit of 5,000 characters. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `google_product_category `__. - Schema.org property [Product.category] - (https://schema.org/category). - title (str): - Required. Product title. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `title `__. - Schema.org property - `Product.name `__. - brands (Sequence[str]): - The brands of the product. - - A maximum of 30 brands are allowed. Each brand must be a - UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `brand `__. - Schema.org property - `Product.brand `__. - description (str): - Product description. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `description `__. - Schema.org property - `Product.description `__. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. - - For product prediction, this field is ignored and the model - automatically detects the text language. The - [Product][google.cloud.retail.v2alpha.Product] can include - text in different languages, but duplicating - [Product][google.cloud.retail.v2alpha.Product]s to provide - text in multiple languages can result in degraded model - performance. - - For product search this field is in use. It defaults to - "en-US" if unset. - attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): - Highly encouraged. Extra product attributes to be included. - For example, for products, this could include the store - name, vendor, style, color, etc. These are very strong - signals for recommendation model, thus we highly recommend - providing the attributes here. - - Features that can take on one of a limited number of - possible values. Two types of features can be set are: - - Textual features. some examples would be the brand/maker of - a product, or country of a customer. Numerical features. - Some examples would be the height/weight of a product, or - age of a customer. - - For example: - ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - Max entries count: 200. - - The key must be a UTF-8 encoded string with a length - limit of 128 characters. - - For indexable attribute, the key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, - ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a - non-empty UTF-8 encoded string with a length limit of 256 - characters. - - For number attributes, at most 400 values are allowed. - tags (Sequence[str]): - Custom tags associated with the product. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. This value - must be a UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This tag can be used for filtering recommendation results by - passing the tag as part of the - [PredictRequest.filter][google.cloud.retail.v2alpha.PredictRequest.filter]. - - Corresponding properties: Google Merchant Center property - `custom_label_0–4 `__. - price_info (google.cloud.retail_v2alpha.types.PriceInfo): - Product price and cost information. - - Corresponding properties: Google Merchant Center property - `price `__. - rating (google.cloud.retail_v2alpha.types.Rating): - The rating of this product. - available_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this - [Product][google.cloud.retail.v2alpha.Product] becomes - available for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - availability (google.cloud.retail_v2alpha.types.Product.Availability): - The online availability of the - [Product][google.cloud.retail.v2alpha.Product]. Default to - [Availability.IN_STOCK][google.cloud.retail.v2alpha.Product.Availability.IN_STOCK]. - - Corresponding properties: Google Merchant Center property - `availability `__. - Schema.org property - `Offer.availability `__. - available_quantity (google.protobuf.wrappers_pb2.Int32Value): - The available quantity of the item. - fulfillment_info (Sequence[google.cloud.retail_v2alpha.types.FulfillmentInfo]): - Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - All the elements must have distinct - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type]. - Otherwise, an INVALID_ARGUMENT error is returned. - uri (str): - Canonical URL directly linking to the product detail page. - - It is strongly recommended to provide a valid uri for the - product, otherwise the service performance could be - significantly degraded. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `link `__. - Schema.org property `Offer.url `__. - images (Sequence[google.cloud.retail_v2alpha.types.Image]): - Product images for the product. We highly recommend putting - the main image first. - - A maximum of 300 images are allowed. - - Corresponding properties: Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - audience (google.cloud.retail_v2alpha.types.Audience): - The target group associated with a given - audience (e.g. male, veterans, car owners, - musicians, etc.) of the product. - color_info (google.cloud.retail_v2alpha.types.ColorInfo): - The color of the product. - - Corresponding properties: Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - sizes (Sequence[str]): - The size of the product. To represent different size systems - or size types, consider using this format: - [[[size_system:]size_type:]size_value]. - - For example, in "US:MENS:M", "US" represents size system; - "MENS" represents size type; "M" represents size value. In - "GIRLS:27", size system is empty; "GIRLS" represents size - type; "27" represents size value. In "32 inches", both size - system and size type are empty, while size value is "32 - inches". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `size `__, - `size_type `__, - and - `size_system `__. - Schema.org property - `Product.size `__. - materials (Sequence[str]): - The material of the product. For example, "leather", - "wooden". - - A maximum of 20 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 200 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `material `__. - Schema.org property - `Product.material `__. - patterns (Sequence[str]): - The pattern or graphic print of the product. For example, - "striped", "polka dot", "paisley". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `pattern `__. - Schema.org property - `Product.pattern `__. - conditions (Sequence[str]): - The condition of the product. Strongly encouraged to use the - standard values: "new", "refurbished", "used". - - A maximum of 1 value is allowed per - [Product][google.cloud.retail.v2alpha.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `condition `__. - Schema.org property - `Offer.itemCondition `__. - promotions (Sequence[google.cloud.retail_v2alpha.types.Promotion]): - The promotions applied to the product. A maximum of 10 - values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. Only - [Promotion.promotion_id][google.cloud.retail.v2alpha.Promotion.promotion_id] - will be used, other fields will be ignored if set. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the product is published by the retailer - for the first time, which indicates the freshness of the - products. Note that this field is different from - [available_time][google.cloud.retail.v2alpha.Product.available_time], - given it purely describes product freshness regardless of - when it is available on search and recommendation. - retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the - [Product][google.cloud.retail.v2alpha.Product]s are returned - in - [SearchResponse][google.cloud.retail.v2alpha.SearchResponse]. - - Supported fields for all - [type][google.cloud.retail.v2alpha.Product.type]s: - - - [audience][google.cloud.retail.v2alpha.Product.audience] - - [availability][google.cloud.retail.v2alpha.Product.availability] - - [brands][google.cloud.retail.v2alpha.Product.brands] - - [color_info][google.cloud.retail.v2alpha.Product.color_info] - - [conditions][google.cloud.retail.v2alpha.Product.conditions] - - [gtin][google.cloud.retail.v2alpha.Product.gtin] - - [materials][google.cloud.retail.v2alpha.Product.materials] - - [name][google.cloud.retail.v2alpha.Product.name] - - [patterns][google.cloud.retail.v2alpha.Product.patterns] - - [price_info][google.cloud.retail.v2alpha.Product.price_info] - - [rating][google.cloud.retail.v2alpha.Product.rating] - - [sizes][google.cloud.retail.v2alpha.Product.sizes] - - [title][google.cloud.retail.v2alpha.Product.title] - - [uri][google.cloud.retail.v2alpha.Product.uri] - - Supported fields only for - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION]: - - - [categories][google.cloud.retail.v2alpha.Product.categories] - - [description][google.cloud.retail.v2alpha.Product.description] - - [images][google.cloud.retail.v2alpha.Product.images] - - Supported fields only for - [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT]: - - - Only the first image in - [images][google.cloud.retail.v2alpha.Product.images] - - To mark - [attributes][google.cloud.retail.v2alpha.Product.attributes] - as retrievable, include paths of the form "attributes.key" - where "key" is the key of a custom attribute, as specified - in - [attributes][google.cloud.retail.v2alpha.Product.attributes]. - - For - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION], - the following fields are always returned in - [SearchResponse][google.cloud.retail.v2alpha.SearchResponse] - by default: - - - [name][google.cloud.retail.v2alpha.Product.name] - - For - [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT], - the following fields are always returned in by default: - - - [name][google.cloud.retail.v2alpha.Product.name] - - [color_info][google.cloud.retail.v2alpha.Product.color_info] - - Maximum number of paths is 30. Otherwise, an - INVALID_ARGUMENT error is returned. - - Note: Returning more fields in - [SearchResponse][google.cloud.retail.v2alpha.SearchResponse] - may increase response payload size and serving latency. - variants (Sequence[google.cloud.retail_v2alpha.types.Product]): - Output only. Product variants grouped together on primary - product which share similar product attributes. It's - automatically grouped by - [primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] - for all the product variants. Only populated for - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct]. - Do not set this field in API requests. - """ - class Type(proto.Enum): - r"""The type of this product.""" - TYPE_UNSPECIFIED = 0 - PRIMARY = 1 - VARIANT = 2 - COLLECTION = 3 - - class Availability(proto.Enum): - r"""Product availability. If this field is unspecified, the - product is assumed to be in stock. - """ - AVAILABILITY_UNSPECIFIED = 0 - IN_STOCK = 1 - OUT_OF_STOCK = 2 - PREORDER = 3 - BACKORDER = 4 - - expire_time = proto.Field( - proto.MESSAGE, - number=16, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl = proto.Field( - proto.MESSAGE, - number=17, - oneof='expiration', - message=duration_pb2.Duration, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - type_ = proto.Field( - proto.ENUM, - number=3, - enum=Type, - ) - primary_product_id = proto.Field( - proto.STRING, - number=4, - ) - collection_member_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - gtin = proto.Field( - proto.STRING, - number=6, - ) - categories = proto.RepeatedField( - proto.STRING, - number=7, - ) - title = proto.Field( - proto.STRING, - number=8, - ) - brands = proto.RepeatedField( - proto.STRING, - number=9, - ) - description = proto.Field( - proto.STRING, - number=10, - ) - language_code = proto.Field( - proto.STRING, - number=11, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=12, - message=common.CustomAttribute, - ) - tags = proto.RepeatedField( - proto.STRING, - number=13, - ) - price_info = proto.Field( - proto.MESSAGE, - number=14, - message=common.PriceInfo, - ) - rating = proto.Field( - proto.MESSAGE, - number=15, - message=common.Rating, - ) - available_time = proto.Field( - proto.MESSAGE, - number=18, - message=timestamp_pb2.Timestamp, - ) - availability = proto.Field( - proto.ENUM, - number=19, - enum=Availability, - ) - available_quantity = proto.Field( - proto.MESSAGE, - number=20, - message=wrappers_pb2.Int32Value, - ) - fulfillment_info = proto.RepeatedField( - proto.MESSAGE, - number=21, - message=common.FulfillmentInfo, - ) - uri = proto.Field( - proto.STRING, - number=22, - ) - images = proto.RepeatedField( - proto.MESSAGE, - number=23, - message=common.Image, - ) - audience = proto.Field( - proto.MESSAGE, - number=24, - message=common.Audience, - ) - color_info = proto.Field( - proto.MESSAGE, - number=25, - message=common.ColorInfo, - ) - sizes = proto.RepeatedField( - proto.STRING, - number=26, - ) - materials = proto.RepeatedField( - proto.STRING, - number=27, - ) - patterns = proto.RepeatedField( - proto.STRING, - number=28, - ) - conditions = proto.RepeatedField( - proto.STRING, - number=29, - ) - promotions = proto.RepeatedField( - proto.MESSAGE, - number=34, - message=promotion.Promotion, - ) - publish_time = proto.Field( - proto.MESSAGE, - number=33, - message=timestamp_pb2.Timestamp, - ) - retrievable_fields = proto.Field( - proto.MESSAGE, - number=30, - message=field_mask_pb2.FieldMask, - ) - variants = proto.RepeatedField( - proto.MESSAGE, - number=31, - message='Product', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py deleted file mode 100644 index ddfc08ed..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py +++ /dev/null @@ -1,877 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'CreateProductRequest', - 'GetProductRequest', - 'UpdateProductRequest', - 'DeleteProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'SetInventoryRequest', - 'SetInventoryMetadata', - 'SetInventoryResponse', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesResponse', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesResponse', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesResponse', - }, -) - - -class CreateProductRequest(proto.Message): - r"""Request message for [CreateProduct][] method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - product (google.cloud.retail_v2alpha.types.Product): - Required. The [Product][google.cloud.retail.v2alpha.Product] - to create. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2alpha.Product], which will - become the final component of the - [Product.name][google.cloud.retail.v2alpha.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2alpha.Product]s with the - same - [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - product_id = proto.Field( - proto.STRING, - number=3, - ) - - -class GetProductRequest(proto.Message): - r"""Request message for [GetProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested - [Product][google.cloud.retail.v2alpha.Product] does not - exist, a NOT_FOUND error is returned. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateProductRequest(proto.Message): - r"""Request message for [UpdateProduct][] method. - - Attributes: - product (google.cloud.retail_v2alpha.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Product][google.cloud.retail.v2alpha.Product] to update. - The immutable and output only fields are NOT supported. If - not set, all supported fields (the fields that are neither - immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - a new [Product][google.cloud.retail.v2alpha.Product] will be - created. In this situation, ``update_mask`` is ignored. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteProductRequest(proto.Message): - r"""Request message for [DeleteProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2alpha.Product] to delete - can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] with more - than one - [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2alpha.Product] will be - deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProductsRequest(proto.Message): - r"""Request message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - - Attributes: - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list products - under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2alpha.Product]s under this - branch, regardless of whether or not this branch exists, a - PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of - [Product][google.cloud.retail.v2alpha.Product]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 - [ListProductsResponse.next_page_token][google.cloud.retail.v2alpha.ListProductsResponse.next_page_token], - received from a previous - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - filter (str): - A filter to apply on the list results. Supported features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2alpha.ListProductsRequest.filter] - is unset. - - List - [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s sharing - the same - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]. For - example: ``primary_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2alpha.Product]s - bundled in a - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product]. For - example: ``collection_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2alpha.Product]s with - a partibular type. For example: ``type = "PRIMARY"`` - ``type = "VARIANT"`` ``type = "COLLECTION"`` - - If the field is unrecognizable, an INVALID_ARGUMENT error is - returned. - - If the specified - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] or - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product] does not - exist, a NOT_FOUND error is returned. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields of [Product][google.cloud.retail.v2alpha.Product] - to return in the responses. If not set or empty, the - following fields are returned: - - - [Product.name][google.cloud.retail.v2alpha.Product.name] - - [Product.id][google.cloud.retail.v2alpha.Product.id] - - [Product.title][google.cloud.retail.v2alpha.Product.title] - - [Product.uri][google.cloud.retail.v2alpha.Product.uri] - - [Product.images][google.cloud.retail.v2alpha.Product.images] - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.brands][google.cloud.retail.v2alpha.Product.brands] - - If "*" is provided, all fields are returned. - [Product.name][google.cloud.retail.v2alpha.Product.name] is - always returned no matter what mask is set. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - require_total_size (bool): - If true and - [page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] - is empty, - [ListProductsResponse.total_size][google.cloud.retail.v2alpha.ListProductsResponse.total_size] - is set to the total count of matched items irrespective of - pagination. - - Notice that setting this field to true affects the - performance. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - require_total_size = proto.Field( - proto.BOOL, - number=6, - ) - - -class ListProductsResponse(proto.Message): - r"""Response message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - - Attributes: - products (Sequence[google.cloud.retail_v2alpha.types.Product]): - The [Product][google.cloud.retail.v2alpha.Product]s. - next_page_token (str): - A token that can be sent as - [ListProductsRequest.page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - total_size (int): - The total count of matched - [Product][google.cloud.retail.v2alpha.Product]s irrespective - of pagination. The total number of - [Product][google.cloud.retail.v2alpha.Product]s returned by - pagination may be less than the - [total_size][google.cloud.retail.v2alpha.ListProductsResponse.total_size] - that matches. - - This field is ignored if - [ListProductsRequest.require_total_size][google.cloud.retail.v2alpha.ListProductsRequest.require_total_size] - is not set or - [ListProductsRequest.page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] - is not empty. - """ - - @property - def raw_page(self): - return self - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - - -class SetInventoryRequest(proto.Message): - r"""Request message for [SetInventory][] method. - - Attributes: - inventory (google.cloud.retail_v2alpha.types.Product): - Required. The inventory information to update. The allowable - fields to update are: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product] named in - [Product.name][google.cloud.retail.v2alpha.Product.name], - regardless of whether or not it exists, a PERMISSION_DENIED - error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting the - last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of fulfillment - types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear in - [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types have - empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following inventory - fields: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - - If a full overwrite of inventory information while ignoring - timestamps is needed, [UpdateProduct][] should be invoked - instead. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2alpha.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the request is issued, used to - prevent out-of-order updates on inventory fields - with the last update time recorded. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] with name - [Product.name][google.cloud.retail.v2alpha.Product.name] is - not found, the inventory update will still be processed and - retained for at most 1 day until the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - inventory = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - set_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - set_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=4, - ) - - -class SetInventoryMetadata(proto.Message): - r"""Metadata related to the progress of the SetInventory operation. - Currently empty because there is no meaningful metadata populated - from the [SetInventory][] method. - - """ - - -class SetInventoryResponse(proto.Message): - r"""Response of the SetInventoryRequest. Currently empty because there - is no meaningful response populated from the [SetInventory][] - method. - - """ - - -class AddFulfillmentPlacesRequest(proto.Message): - r"""Request message for [AddFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery" to be added for this - [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type]. - Duplicate IDs will be automatically ignored. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If the total number of place IDs exceeds 2000 for this - [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type] - after adding, then the update will be rejected. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - the fulfillment information will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - add_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class AddFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the AddFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [AddFulfillmentPlaces][] method. - - """ - - -class AddFulfillmentPlacesResponse(proto.Message): - r"""Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - - -class AddLocalInventoriesRequest(proto.Message): - r"""Request message for [AddLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - local_inventories (Sequence[google.cloud.retail_v2alpha.types.LocalInventory]): - Required. A list of inventory information at - difference places. Each place is identified by - its place ID. At most 3000 inventories are - allowed per request. - add_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided list of - [LocalInventory][google.cloud.retail.v2alpha.LocalInventory] - to update. The field is updated to the provided value. - - If a field is set while the place does not have a previous - local inventory, the local inventory at that store is - created. - - If a field is set while the value of that field is not - provided, the original field value, if it exists, is - deleted. - - If the mask is not set or set with empty paths, all - inventory fields will be updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory updates are - issued. Used to prevent out-of-order updates on - local inventory fields. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - the local inventory will still be processed and retained for - at most 1 day and processed once the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - local_inventories = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.LocalInventory, - ) - add_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - add_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=6, - ) - - -class AddLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the AddLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [AddLocalInventories][] method. - - """ - - -class AddLocalInventoriesResponse(proto.Message): - r"""Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesRequest(proto.Message): - r"""Request message for [RemoveLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - place_ids (Sequence[str]): - Required. A list of place IDs to have their - inventory deleted. At most 3000 place IDs are - allowed per request. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory deletions are - issued. Used to prevent out-of-order updates and - deletions on local inventory fields. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - the local inventory removal request will still be processed - and retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class RemoveLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesResponse(proto.Message): - r"""Response of the [RemoveLocalInventories][] API. Currently empty - because there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - - -class RemoveFulfillmentPlacesRequest(proto.Message): - r"""Request message for [RemoveFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery", to be removed for this - [type][google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type]. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - the fulfillment information will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class RemoveFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveFulfillmentPlaces][] method. - - """ - - -class RemoveFulfillmentPlacesResponse(proto.Message): - r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty - because there is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py deleted file mode 100644 index bd5b8a58..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'Promotion', - }, -) - - -class Promotion(proto.Message): - r"""Promotion information. - - Attributes: - promotion_id (str): - ID of the promotion. For example, "free gift". - - The value must be a UTF-8 encoded string with a length limit - of 128 characters, and match the pattern: - ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or - ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is - returned. - - Google Merchant Center property - `promotion `__. - """ - - promotion_id = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py deleted file mode 100644 index ad7ff6f6..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py +++ /dev/null @@ -1,251 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'PurgeMetadata', - 'PurgeProductsMetadata', - 'PurgeProductsRequest', - 'PurgeProductsResponse', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - }, -) - - -class PurgeMetadata(proto.Message): - r"""Metadata related to the progress of the Purge operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - """ - - -class PurgeProductsMetadata(proto.Message): - r"""Metadata related to the progress of the PurgeProducts - operation. This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were deleted - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=3, - ) - failure_count = proto.Field( - proto.INT64, - number=4, - ) - - -class PurgeProductsRequest(proto.Message): - r"""Request message for PurgeProducts method. - - Attributes: - parent (str): - Required. The resource name of the branch under which the - products are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}/branches/${branchId}`` - filter (str): - Required. The filter string to specify the products to be - deleted with a length limit of 5,000 characters. - - Empty string filter is not allowed. "*" implies delete all - items in a branch. - - The eligible fields for filtering are: - - - ``availability``: Double quoted - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - string. - - ``create_time`` : in ISO 8601 "zulu" format. - - Supported syntax: - - - Comparators (">", "<", ">=", "<=", "="). Examples: - - - create_time <= "2015-02-13T17:05:46Z" - - availability = "IN_STOCK" - - - Conjunctions ("AND") Examples: - - - create_time <= "2015-02-13T17:05:46Z" AND availability - = "PREORDER" - - - Disjunctions ("OR") Examples: - - - create_time <= "2015-02-13T17:05:46Z" OR availability - = "IN_STOCK" - - - Can support nested queries. Examples: - - - (create_time <= "2015-02-13T17:05:46Z" AND - availability = "PREORDER") OR (create_time >= - "2015-02-14T13:03:32Z" AND availability = "IN_STOCK") - - - Filter Limits: - - - Filter should not contain more than 6 conditions. - - Max nesting depth should not exceed 2 levels. - - Examples queries: - - - Delete back order products created before a timestamp. - create_time <= "2015-02-13T17:05:46Z" OR availability = - "BACKORDER". - force (bool): - Actually perform the purge. If ``force`` is set to false, - the method will return the expected purge count without - deleting any products. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeProductsResponse(proto.Message): - r"""Response of the PurgeProductsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purge_count (int): - The total count of products purged as a - result of the operation. - purge_sample (Sequence[str]): - A sample of the product names that will be deleted. Only - populated if ``force`` is set to false. A max of 100 names - will be returned and the names are chosen at random. - """ - - purge_count = proto.Field( - proto.INT64, - number=1, - ) - purge_sample = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class PurgeUserEventsRequest(proto.Message): - r"""Request message for PurgeUserEvents method. - - Attributes: - parent (str): - Required. The resource name of the catalog under which the - events are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}`` - filter (str): - Required. The filter string to specify the events to be - deleted with a length limit of 5,000 characters. Empty - string filter is not allowed. The eligible fields for - filtering are: - - - ``eventType``: Double quoted - [UserEvent.event_type][google.cloud.retail.v2alpha.UserEvent.event_type] - string. - - ``eventTime``: in ISO 8601 "zulu" format. - - ``visitorId``: Double quoted string. Specifying this will - delete all events associated with a visitor. - - ``userId``: Double quoted string. Specifying this will - delete all events associated with a user. - - Examples: - - - Deleting all events in a time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - - Deleting specific eventType in time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` - - Deleting all events for a specific visitor: - ``visitorId = "visitor1024"`` - - The filtering fields are assumed to have an implicit AND. - force (bool): - Actually perform the purge. If ``force`` is set to false, - the method will return the expected purge count without - deleting any user events. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeUserEventsResponse(proto.Message): - r"""Response of the PurgeUserEventsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purged_events_count (int): - The total count of events purged as a result - of the operation. - """ - - purged_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py deleted file mode 100644 index e4dc0ba2..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py +++ /dev/null @@ -1,1099 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'SearchRequest', - 'SearchResponse', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - - Attributes: - placement (str): - Required. The resource name of the search engine placement, - such as - ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` - This field is used to identify the serving configuration - name and the set of models that will be used to make the - search. - branch (str): - The branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - - Use "default_branch" as the branch ID or leave this field - empty, to search products under the default branch. - query (str): - Raw search query. - visitor_id (str): - Required. A unique identifier for tracking visitors. For - example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - This should be the same identifier as - [UserEvent.visitor_id][google.cloud.retail.v2alpha.UserEvent.visitor_id]. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2alpha.types.UserInfo): - User information. - page_size (int): - Maximum number of - [Product][google.cloud.retail.v2alpha.Product]s to return. - If unspecified, defaults to a reasonable value. The maximum - allowed value is 120. Values above 120 will be coerced to - 120. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [SearchResponse.next_page_token][google.cloud.retail.v2alpha.SearchResponse.next_page_token], - received from a previous - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - offset (int): - A 0-indexed integer that specifies the current offset (that - is, starting result location, amongst the - [Product][google.cloud.retail.v2alpha.Product]s deemed by - the API as relevant) in search results. This field is only - considered if - [page_token][google.cloud.retail.v2alpha.SearchRequest.page_token] - is unset. - - If this field is negative, an INVALID_ARGUMENT is returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. Filter expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - canonical_filter (str): - The default filter that is applied when a user performs a - search without checking any filters on the search page. - - The filter applied to every search request when quality - improvement such as query expansion is needed. For example, - if a query does not have enough results, an expanded query - with - [SearchRequest.canonical_filter][google.cloud.retail.v2alpha.SearchRequest.canonical_filter] - will be returned as a supplement of the original query. This - field is strongly recommended to achieve high search - quality. - - See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for more details about filter syntax. - order_by (str): - The order in which products are returned. Products can be - ordered by a field in an - [Product][google.cloud.retail.v2alpha.Product] object. Leave - it unset if ordered by relevance. OrderBy expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - facet_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec]): - Facet specifications for faceted search. If empty, no facets - are returned. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - dynamic_facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec): - Deprecated. Refer to - https://cloud.google.com/retail/docs/configs#dynamic - to enable dynamic facets. Do not set this field. - The specification for dynamically generated - facets. Notice that only textual facets can be - dynamically generated. - boost_spec (google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec): - Boost specification to boost certain products. See more - details at this `user - guide `__. - - Notice that if both - [ServingConfig.boost_control_ids][google.cloud.retail.v2alpha.ServingConfig.boost_control_ids] - and [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. - query_expansion_spec (google.cloud.retail_v2alpha.types.SearchRequest.QueryExpansionSpec): - The query expansion specification that specifies the - conditions under which query expansion will occur. See more - details at this `user - guide `__. - relevance_threshold (google.cloud.retail_v2alpha.types.SearchRequest.RelevanceThreshold): - The relevance threshold of the search results. - - Defaults to - [RelevanceThreshold.HIGH][google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH], - which means only the most relevant results are shown, and - the least number of results are returned. See more details - at this `user - guide `__. - variant_rollup_keys (Sequence[str]): - The keys to fetch and rollup the matching - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s attributes, - [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo] - or - [LocalInventory][google.cloud.retail.v2alpha.LocalInventory]s - attributes. The attributes from all the matching - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s or - [LocalInventory][google.cloud.retail.v2alpha.LocalInventory]s - are merged and de-duplicated. Notice that rollup attributes - will lead to extra query latency. Maximum number of keys is - 30. - - For - [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], - a fulfillment type and a fulfillment ID must be provided in - the format of "fulfillmentType.fulfillmentId". E.g., in - "pickupInStore.store123", "pickupInStore" is fulfillment - type and "store123" is the store ID. - - Supported keys are: - - - colorFamilies - - price - - originalPrice - - discount - - variantId - - inventory(place_id,price) - - inventory(place_id,original_price) - - inventory(place_id,attributes.key), where key is any key - in the [Product.inventories.attributes][] map. - - attributes.key, where key is any key in the - [Product.attributes][google.cloud.retail.v2alpha.Product.attributes] - map. - - pickupInStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "pickup-in-store". - - shipToStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "ship-to-store". - - sameDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "same-day-delivery". - - nextDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "next-day-delivery". - - customFulfillment1.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-1". - - customFulfillment2.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-2". - - customFulfillment3.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-3". - - customFulfillment4.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-4". - - customFulfillment5.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-5". - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. Required for - category navigation queries to achieve good search quality. - The format should be the same as - [UserEvent.page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories]; - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - search_mode (google.cloud.retail_v2alpha.types.SearchRequest.SearchMode): - The search mode of the search request. If not - specified, a single search request triggers both - product search and faceted search. - personalization_spec (google.cloud.retail_v2alpha.types.SearchRequest.PersonalizationSpec): - The specification for personalization. - """ - class RelevanceThreshold(proto.Enum): - r"""The relevance threshold of the search results. The higher - relevance threshold is, the higher relevant results are shown - and the less number of results are returned. - """ - RELEVANCE_THRESHOLD_UNSPECIFIED = 0 - HIGH = 1 - MEDIUM = 2 - LOW = 3 - LOWEST = 4 - - class SearchMode(proto.Enum): - r"""The search mode of each search request.""" - SEARCH_MODE_UNSPECIFIED = 0 - PRODUCT_SEARCH_ONLY = 1 - FACETED_SEARCH_ONLY = 2 - - class FacetSpec(proto.Message): - r"""A facet specification to perform faceted search. - - Attributes: - facet_key (google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec.FacetKey): - Required. The facet key specification. - limit (int): - Maximum of facet values that should be returned for this - facet. If unspecified, defaults to 20. The maximum allowed - value is 300. Values above 300 will be coerced to 300. - - If this field is negative, an INVALID_ARGUMENT is returned. - excluded_filter_keys (Sequence[str]): - List of keys to exclude when faceting. - - By default, - [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] - is not excluded from the filter unless it is listed in this - field. - - For example, suppose there are 100 products with color facet - "Red" and 200 products with color facet "Blue". A query - containing the filter "colorFamilies:ANY("Red")" and have - "colorFamilies" as - [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] - will by default return the "Red" with count 100. - - If this field contains "colorFamilies", then the query - returns both the "Red" with count 100 and "Blue" with count - 200, because the "colorFamilies" key is now excluded from - the filter. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - enable_dynamic_position (bool): - Enables dynamic position for this facet. If set to true, the - position of this facet among all facets in the response is - determined by Google Retail Search. It will be ordered - together with dynamic facets if dynamic facets is enabled. - If set to false, the position of this facet in the response - will be the same as in the request, and it will be ranked - before the facets with dynamic position enable and all - dynamic facets. - - For example, you may always want to have rating facet - returned in the response, but it's not necessarily to always - display the rating facet at the top. In that case, you can - set enable_dynamic_position to true so that the position of - rating facet in response will be determined by Google Retail - Search. - - Another example, assuming you have the following facets in - the request: - - - "rating", enable_dynamic_position = true - - - "price", enable_dynamic_position = false - - - "brands", enable_dynamic_position = false - - And also you have a dynamic facets enable, which will - generate a facet 'gender'. Then the final order of the - facets in the response can be ("price", "brands", "rating", - "gender") or ("price", "brands", "gender", "rating") depends - on how Google Retail Search orders "gender" and "rating" - facets. However, notice that "price" and "brands" will - always be ranked at 1st and 2nd position since their - enable_dynamic_position are false. - """ - - class FacetKey(proto.Message): - r"""Specifies how a facet is computed. - - Attributes: - key (str): - Required. Supported textual and numerical facet keys in - [Product][google.cloud.retail.v2alpha.Product] object, over - which the facet values are computed. Facet key is - case-sensitive. - - Allowed facet keys when - [FacetKey.query][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.query] - is not specified: - - - textual_field = - - - "brands" - - "categories" - - "genders" - - "ageGroups" - - "availability" - - "colorFamilies" - - "colors" - - "sizes" - - "materials" - - "patterns" - - "conditions" - - "attributes.key" - - "pickupInStore" - - "shipToStore" - - "sameDayDelivery" - - "nextDayDelivery" - - "customFulfillment1" - - "customFulfillment2" - - "customFulfillment3" - - "customFulfillment4" - - "customFulfillment5" - - "inventory(place_id,attributes.key)" - - - numerical_field = - - - "price" - - "discount" - - "rating" - - "ratingCount" - - "attributes.key" - - "inventory(place_id,price)" - - "inventory(place_id,original_price)" - - "inventory(place_id,attributes.key)". - intervals (Sequence[google.cloud.retail_v2alpha.types.Interval]): - Set only if values should be bucketized into - intervals. Must be set for facets with numerical - values. Must not be set for facet with text - values. Maximum number of intervals is 30. - restricted_values (Sequence[str]): - Only get facet for the given restricted values. For example, - when using "pickupInStore" as key and set restricted values - to ["store123", "store456"], only facets for "store123" and - "store456" are returned. Only supported on textual fields - and fulfillments. Maximum is 20. - - Must be set for the fulfillment facet keys: - - - pickupInStore - - - shipToStore - - - sameDayDelivery - - - nextDayDelivery - - - customFulfillment1 - - - customFulfillment2 - - - customFulfillment3 - - - customFulfillment4 - - - customFulfillment5 - prefixes (Sequence[str]): - Only get facet values that start with the - given string prefix. For example, suppose - "categories" has three values "Women > Shoe", - "Women > Dress" and "Men > Shoe". If set - "prefixes" to "Women", the "categories" facet - will give only "Women > Shoe" and "Women > - Dress". Only supported on textual fields. - Maximum is 10. - contains (Sequence[str]): - Only get facet values that contains the given - strings. For example, suppose "categories" has - three values "Women > Shoe", "Women > Dress" and - "Men > Shoe". If set "contains" to "Shoe", the - "categories" facet will give only "Women > Shoe" - and "Men > Shoe". Only supported on textual - fields. Maximum is 10. - order_by (str): - The order in which [Facet.values][] are returned. - - Allowed values are: - - - "count desc", which means order by - [Facet.FacetValue.count][] descending. - - - "value desc", which means order by - [Facet.FacetValue.value][] descending. Only applies to - textual facets. - - If not set, textual values are sorted in `natural - order `__; - numerical intervals are sorted in the order given by - [FacetSpec.FacetKey.intervals][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.intervals]; - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - are sorted in the order given by - [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.restricted_values]. - query (str): - The query that is used to compute facet for the given facet - key. When provided, it will override the default behavior of - facet computation. The query syntax is the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for detail syntax and limitations. Notice that there is no - limitation on - [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] - when query is specified. - - In the response, [FacetValue.value][] will be always "1" and - [FacetValue.count][] will be the number of results that - matches the query. - - For example, you can set a customized facet for - "shipToStore", where - [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] - is "customizedShipToStore", and - [FacetKey.query][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.query] - is "availability: ANY("IN_STOCK") AND shipToStore: - ANY("123")". Then the facet will count the products that are - both in stock and ship to store "123". - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - intervals = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Interval, - ) - restricted_values = proto.RepeatedField( - proto.STRING, - number=3, - ) - prefixes = proto.RepeatedField( - proto.STRING, - number=8, - ) - contains = proto.RepeatedField( - proto.STRING, - number=9, - ) - order_by = proto.Field( - proto.STRING, - number=4, - ) - query = proto.Field( - proto.STRING, - number=5, - ) - - facet_key = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.FacetSpec.FacetKey', - ) - limit = proto.Field( - proto.INT32, - number=2, - ) - excluded_filter_keys = proto.RepeatedField( - proto.STRING, - number=3, - ) - enable_dynamic_position = proto.Field( - proto.BOOL, - number=4, - ) - - class DynamicFacetSpec(proto.Message): - r"""The specifications of dynamically generated facets. - - Attributes: - mode (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec.Mode): - Mode of the DynamicFacet feature. Defaults to - [Mode.DISABLED][google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec.Mode.DISABLED] - if it's unset. - """ - class Mode(proto.Enum): - r"""Enum to control DynamicFacet mode""" - MODE_UNSPECIFIED = 0 - DISABLED = 1 - ENABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.DynamicFacetSpec.Mode', - ) - - class BoostSpec(proto.Message): - r"""Boost specification to boost certain items. - - Attributes: - condition_boost_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - Condition boost specifications. If a product - matches multiple conditions in the - specifictions, boost scores from these - specifications are all applied and combined in a - non-linear way. Maximum number of specifications - is 10. - skip_boost_spec_validation (bool): - Whether to skip boostspec validation. If this field is set - to true, invalid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] - will be ignored and valid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] - will still be applied. - - This field is a member of `oneof`_ ``_skip_boost_spec_validation``. - """ - - class ConditionBoostSpec(proto.Message): - r"""Boost applies to products which match a condition. - - Attributes: - condition (str): - An expression which specifies a boost condition. The syntax - and supported fields are the same as a filter expression. - See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": - - - (id: ANY("product_1", "product_2")) AND - (colorFamilies: ANY("Red","Blue")) - boost (float): - Strength of the condition boost, which should be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - """ - - condition = proto.Field( - proto.STRING, - number=1, - ) - boost = proto.Field( - proto.FLOAT, - number=2, - ) - - condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - skip_boost_spec_validation = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - - class QueryExpansionSpec(proto.Message): - r"""Specification to determine under which conditions query - expansion should occur. - - Attributes: - condition (google.cloud.retail_v2alpha.types.SearchRequest.QueryExpansionSpec.Condition): - The condition under which query expansion should occur. - Default to - [Condition.DISABLED][google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - pin_unexpanded_results (bool): - Whether to pin unexpanded results. If this - field is set to true, unexpanded products are - always at the top of the search results, - followed by the expanded results. - """ - class Condition(proto.Enum): - r"""Enum describing under which condition query expansion should - occur. - """ - CONDITION_UNSPECIFIED = 0 - DISABLED = 1 - AUTO = 3 - - condition = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.QueryExpansionSpec.Condition', - ) - pin_unexpanded_results = proto.Field( - proto.BOOL, - number=2, - ) - - class PersonalizationSpec(proto.Message): - r"""The specification for personalization. - - Attributes: - mode (google.cloud.retail_v2alpha.types.SearchRequest.PersonalizationSpec.Mode): - Defaults to - [Mode.AUTO][google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""The personalization mode of each search request.""" - MODE_UNSPECIFIED = 0 - AUTO = 1 - DISABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.PersonalizationSpec.Mode', - ) - - placement = proto.Field( - proto.STRING, - number=1, - ) - branch = proto.Field( - proto.STRING, - number=2, - ) - query = proto.Field( - proto.STRING, - number=3, - ) - visitor_id = proto.Field( - proto.STRING, - number=4, - ) - user_info = proto.Field( - proto.MESSAGE, - number=5, - message=common.UserInfo, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - offset = proto.Field( - proto.INT32, - number=9, - ) - filter = proto.Field( - proto.STRING, - number=10, - ) - canonical_filter = proto.Field( - proto.STRING, - number=28, - ) - order_by = proto.Field( - proto.STRING, - number=11, - ) - facet_specs = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=FacetSpec, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=21, - message=DynamicFacetSpec, - ) - boost_spec = proto.Field( - proto.MESSAGE, - number=13, - message=BoostSpec, - ) - query_expansion_spec = proto.Field( - proto.MESSAGE, - number=14, - message=QueryExpansionSpec, - ) - relevance_threshold = proto.Field( - proto.ENUM, - number=15, - enum=RelevanceThreshold, - ) - variant_rollup_keys = proto.RepeatedField( - proto.STRING, - number=17, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=23, - ) - search_mode = proto.Field( - proto.ENUM, - number=31, - enum=SearchMode, - ) - personalization_spec = proto.Field( - proto.MESSAGE, - number=32, - message=PersonalizationSpec, - ) - - -class SearchResponse(proto.Message): - r"""Response message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - - Attributes: - results (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.SearchResult]): - A list of matched items. The order represents - the ranking. - facets (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.Facet]): - Results of facets requested by user. - total_size (int): - The estimated total count of matched items irrespective of - pagination. The count of - [results][google.cloud.retail.v2alpha.SearchResponse.results] - returned by pagination may be less than the - [total_size][google.cloud.retail.v2alpha.SearchResponse.total_size] - that matches. - corrected_query (str): - If spell correction applies, the corrected - query. Otherwise, empty. - attribution_token (str): - A unique search token. This should be included in the - [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs - resulting from this search, which enables accurate - attribution of search model performance. - next_page_token (str): - A token that can be sent as - [SearchRequest.page_token][google.cloud.retail.v2alpha.SearchRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - query_expansion_info (google.cloud.retail_v2alpha.types.SearchResponse.QueryExpansionInfo): - Query expansion information for the returned - results. - redirect_uri (str): - The URI of a customer-defined redirect page. If redirect - action is triggered, no search will be performed, and only - [redirect_uri][google.cloud.retail.v2alpha.SearchResponse.redirect_uri] - and - [attribution_token][google.cloud.retail.v2alpha.SearchResponse.attribution_token] - will be set in the response. - applied_controls (Sequence[str]): - The fully qualified resource name of applied - `controls `__. - invalid_condition_boost_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - The invalid - [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] - that are not applied during serving. - """ - - class SearchResult(proto.Message): - r"""Represents the search results. - - Attributes: - id (str): - [Product.id][google.cloud.retail.v2alpha.Product.id] of the - searched [Product][google.cloud.retail.v2alpha.Product]. - product (google.cloud.retail_v2alpha.types.Product): - The product data snippet in the search response. Only - [Product.name][google.cloud.retail.v2alpha.Product.name] is - guaranteed to be populated. - - [Product.variants][google.cloud.retail.v2alpha.Product.variants] - contains the product variants that match the search query. - If there are multiple product variants matching the query, - top 5 most relevant product variants are returned and - ordered by relevancy. - - If relevancy can be deternmined, use - [matching_variant_fields][google.cloud.retail.v2alpha.SearchResponse.SearchResult.matching_variant_fields] - to look up matched product variants fields. If relevancy - cannot be determined, e.g. when searching "shoe" all - products in a shoe product can be a match, 5 product - variants are returned but order is meaningless. - matching_variant_count (int): - The count of matched - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s. - matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): - If a - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] matches the - search query, this map indicates which - [Product][google.cloud.retail.v2alpha.Product] fields are - matched. The key is the - [Product.name][google.cloud.retail.v2alpha.Product.name], - the value is a field mask of the matched - [Product][google.cloud.retail.v2alpha.Product] fields. If - matched attributes cannot be determined, this map will be - empty. - - For example, a key "sku1" with field mask - "products.color_info" indicates there is a match between - "sku1" [ColorInfo][google.cloud.retail.v2alpha.ColorInfo] - and the query. - variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): - The rollup matching - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] attributes. - The key is one of the - [SearchRequest.variant_rollup_keys][google.cloud.retail.v2alpha.SearchRequest.variant_rollup_keys]. - The values are the merged and de-duplicated - [Product][google.cloud.retail.v2alpha.Product] attributes. - Notice that the rollup values are respect filter. For - example, when filtering by "colorFamilies:ANY("red")" and - rollup "colorFamilies", only "red" is returned. - - For textual and numerical attributes, the rollup values is a - list of string or double values with type - [google.protobuf.ListValue][google.protobuf.ListValue]. For - example, if there are two variants with colors "red" and - "blue", the rollup values are - - :: - - { key: "colorFamilies" - value { - list_value { - values { string_value: "red" } - values { string_value: "blue" } - } - } - } - - For - [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], - the rollup values is a double value with type - [google.protobuf.Value][google.protobuf.Value]. For example, - ``{key: "pickupInStore.store1" value { number_value: 10 }}`` - means a there are 10 variants in this product are available - in the store "store1". - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - matching_variant_count = proto.Field( - proto.INT32, - number=3, - ) - matching_variant_fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - variant_rollup_values = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - - class Facet(proto.Message): - r"""A facet result. - - Attributes: - key (str): - The key for this facet. E.g., "colorFamilies" - or "price" or "attributes.attr1". - values (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.Facet.FacetValue]): - The facet values for this field. - dynamic_facet (bool): - Whether the facet is dynamically generated. - """ - - class FacetValue(proto.Message): - r"""A facet value which contains value names and their count. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Text value of a facet, such as "Black" for - facet "colorFamilies". - - This field is a member of `oneof`_ ``facet_value``. - interval (google.cloud.retail_v2alpha.types.Interval): - Interval value for a facet, such as [10, 20) for facet - "price". - - This field is a member of `oneof`_ ``facet_value``. - count (int): - Number of items that have this facet value. - """ - - value = proto.Field( - proto.STRING, - number=1, - oneof='facet_value', - ) - interval = proto.Field( - proto.MESSAGE, - number=2, - oneof='facet_value', - message=common.Interval, - ) - count = proto.Field( - proto.INT64, - number=3, - ) - - key = proto.Field( - proto.STRING, - number=1, - ) - values = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SearchResponse.Facet.FacetValue', - ) - dynamic_facet = proto.Field( - proto.BOOL, - number=3, - ) - - class QueryExpansionInfo(proto.Message): - r"""Information describing query expansion including whether - expansion has occurred. - - Attributes: - expanded_query (bool): - Bool describing whether query expansion has - occurred. - pinned_result_count (int): - Number of pinned results. This field will only be set when - expansion happens and - [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] - is set to true. - """ - - expanded_query = proto.Field( - proto.BOOL, - number=1, - ) - pinned_result_count = proto.Field( - proto.INT64, - number=2, - ) - - @property - def raw_page(self): - return self - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=SearchResult, - ) - facets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Facet, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - corrected_query = proto.Field( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - next_page_token = proto.Field( - proto.STRING, - number=6, - ) - query_expansion_info = proto.Field( - proto.MESSAGE, - number=7, - message=QueryExpansionInfo, - ) - redirect_uri = proto.Field( - proto.STRING, - number=10, - ) - applied_controls = proto.RepeatedField( - proto.STRING, - number=12, - ) - invalid_condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py deleted file mode 100644 index c8c3ccca..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py +++ /dev/null @@ -1,309 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'ServingConfig', - }, -) - - -class ServingConfig(proto.Message): - r"""Configures metadata that is used to generate serving time results - (e.g. search results or recommendation predictions). The - ServingConfig is passed in the search and predict request and - together with the Catalog.default_branch, generates results. - - Attributes: - name (str): - Immutable. Fully qualified name - projects/\ */locations/global/catalogs/*/servingConfig/\* - display_name (str): - Required. The human readable serving config display name. - Used in Retail UI. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - model_id (str): - The id of the model to use at serving time. Currently only - RecommendationModels are supported: - https://cloud.google.com/retail/recommendations-ai/docs/create-models - Can be changed but only to a compatible model (e.g. - others-you-may-like CTR to others-you-may-like CVR). - - Required when - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - price_reranking_level (str): - How much price ranking we want in serving results. Price - reranking causes product items with a similar recommendation - probability to be ordered by price, with the highest-priced - items first. This setting could result in a decrease in - click-through and conversion rates. Allowed values are: - - - 'no-price-reranking' - - 'low-price-raranking' - - 'medium-price-reranking' - - 'high-price-reranking' - - If not specified, we choose default based on model type. - Default value: 'no-price-reranking'. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - facet_control_ids (Sequence[str]): - Facet specifications for faceted search. If empty, no facets - are returned. The ids refer to the ids of - [Control][google.cloud.retail.v2alpha.Control] resources - with only the Facet control set. These controls are assumed - to be in the same - [Catalog][google.cloud.retail.v2alpha.Catalog] as the - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]. - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - dynamic_facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec): - The specification for dynamically generated facets. Notice - that only textual facets can be dynamically generated. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - boost_control_ids (Sequence[str]): - Condition boost specifications. If a product matches - multiple conditions in the specifications, boost scores from - these specifications are all applied and combined in a - non-linear way. Maximum number of specifications is 100. - - Notice that if both - [ServingConfig.boost_control_ids][google.cloud.retail.v2alpha.ServingConfig.boost_control_ids] - and [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - filter_control_ids (Sequence[str]): - Condition filter specifications. If a product matches - multiple conditions in the specifications, filters from - these specifications are all applied and combined via the - AND operator. Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - redirect_control_ids (Sequence[str]): - Condition redirect specifications. Only the first triggered - redirect action is applied, even if multiple apply. Maximum - number of specifications is 1000. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - twoway_synonyms_control_ids (Sequence[str]): - Condition synonyms specifications. If multiple syonyms - conditions match, all matching synonyms control in the list - will execute. Order of controls in the list will not matter. - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - oneway_synonyms_control_ids (Sequence[str]): - Condition oneway synonyms specifications. If multiple oneway - synonyms conditions match, all matching oneway synonyms - controls in the list will execute. Order of controls in the - list will not matter. Maximum number of specifications is - 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - do_not_associate_control_ids (Sequence[str]): - Condition do not associate specifications. If multiple do - not associate conditions match, all matching do not - associate controls in the list will execute. - - - Order does not matter. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - replacement_control_ids (Sequence[str]): - Condition replacement specifications. - - - Applied according to the order in the list. - - A previously replaced term can not be re-replaced. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - ignore_control_ids (Sequence[str]): - Condition ignore specifications. If multiple ignore - conditions match, all matching ignore controls in the list - will execute. - - - Order does not matter. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - diversity_level (str): - How much diversity to use in recommendation model results - e.g. 'medium-diversity' or 'high-diversity'. Currently - supported values: - - - 'no-diversity' - - 'low-diversity' - - 'medium-diversity' - - 'high-diversity' - - 'auto-diversity' - - If not specified, we choose default based on recommendation - model type. Default value: 'no-diversity'. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - enable_category_filter_level (str): - Whether to add additional category filters on the - 'similar-items' model. If not specified, we enable it by - default. Allowed values are: - - - 'no-category-match': No additional filtering of original - results from the model and the customer's filters. - - 'relaxed-category-match': Only keep results with - categories that match at least one item categories in the - PredictRequests's context item. - - - If customer also sends filters in the PredictRequest, - then the results will satisfy both conditions (user - given and category match). - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - solution_types (Sequence[google.cloud.retail_v2alpha.types.SolutionType]): - Required. Immutable. Specifies the solution - types that a serving config can be associated - with. Currently we support setting only one type - of solution. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - model_id = proto.Field( - proto.STRING, - number=3, - ) - price_reranking_level = proto.Field( - proto.STRING, - number=4, - ) - facet_control_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=6, - message=search_service.SearchRequest.DynamicFacetSpec, - ) - boost_control_ids = proto.RepeatedField( - proto.STRING, - number=7, - ) - filter_control_ids = proto.RepeatedField( - proto.STRING, - number=9, - ) - redirect_control_ids = proto.RepeatedField( - proto.STRING, - number=10, - ) - twoway_synonyms_control_ids = proto.RepeatedField( - proto.STRING, - number=18, - ) - oneway_synonyms_control_ids = proto.RepeatedField( - proto.STRING, - number=12, - ) - do_not_associate_control_ids = proto.RepeatedField( - proto.STRING, - number=13, - ) - replacement_control_ids = proto.RepeatedField( - proto.STRING, - number=14, - ) - ignore_control_ids = proto.RepeatedField( - proto.STRING, - number=15, - ) - diversity_level = proto.Field( - proto.STRING, - number=8, - ) - enable_category_filter_level = proto.Field( - proto.STRING, - number=16, - ) - solution_types = proto.RepeatedField( - proto.ENUM, - number=19, - enum=common.SolutionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py deleted file mode 100644 index 635f42bb..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py +++ /dev/null @@ -1,234 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'CreateServingConfigRequest', - 'UpdateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'AddControlRequest', - 'RemoveControlRequest', - }, -) - - -class CreateServingConfigRequest(proto.Message): - r"""Request for CreateServingConfig method. - - Attributes: - parent (str): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - serving_config (google.cloud.retail_v2alpha.types.ServingConfig): - Required. The ServingConfig to create. - serving_config_id (str): - Required. The ID to use for the ServingConfig, which will - become the final component of the ServingConfig's resource - name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-_/. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - serving_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_serving_config.ServingConfig, - ) - serving_config_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateServingConfigRequest(proto.Message): - r"""Request for UpdateServingConfig method. - - Attributes: - serving_config (google.cloud.retail_v2alpha.types.ServingConfig): - Required. The ServingConfig to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] - - If not set, all supported fields are updated. - """ - - serving_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_serving_config.ServingConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteServingConfigRequest(proto.Message): - r"""Request for DeleteServingConfig method. - - Attributes: - name (str): - Required. The resource name of the ServingConfig to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetServingConfigRequest(proto.Message): - r"""Request for GetServingConfig method. - - Attributes: - name (str): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListServingConfigsRequest(proto.Message): - r"""Request for ListServingConfigs method. - - Attributes: - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - page_size (int): - Optional. Maximum number of results to - return. If unspecified, defaults to 100. If a - value greater than 100 is provided, at most 100 - results are returned. - page_token (str): - Optional. A page token, received from a previous - ``ListServingConfigs`` call. Provide this to retrieve the - subsequent page. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListServingConfigsResponse(proto.Message): - r"""Response for ListServingConfigs method. - - Attributes: - serving_configs (Sequence[google.cloud.retail_v2alpha.types.ServingConfig]): - All the ServingConfigs for a given catalog. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - serving_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_serving_config.ServingConfig, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class AddControlRequest(proto.Message): - r"""Request for AddControl method. - - Attributes: - serving_config (str): - Required. The source ServingConfig resource name . Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - control_id (str): - Required. The id of the control to apply. Assumed to be in - the same catalog as the serving config - if id is not found - a NOT_FOUND error is returned. - """ - - serving_config = proto.Field( - proto.STRING, - number=1, - ) - control_id = proto.Field( - proto.STRING, - number=2, - ) - - -class RemoveControlRequest(proto.Message): - r"""Request for RemoveControl method. - - Attributes: - serving_config (str): - Required. The source ServingConfig resource name . Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - control_id (str): - Required. The id of the control to apply. - Assumed to be in the same catalog as the serving - config. - """ - - serving_config = proto.Field( - proto.STRING, - number=1, - ) - control_id = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py deleted file mode 100644 index f9d6a684..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py +++ /dev/null @@ -1,507 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'UserEvent', - 'ProductDetail', - 'CompletionDetail', - 'PurchaseTransaction', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information Retail API needs - to know about how end users interact with customers' website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - - ``add-to-cart``: Products being added to cart. - - ``category-page-view``: Special pages such as sale or - promotion pages viewed. - - ``detail-page-view``: Products detail page viewed. - - ``home-page-view``: Homepage viewed. - - ``promotion-offered``: Promotion is offered to a user. - - ``promotion-not-offered``: Promotion is not offered to a - user. - - ``purchase-complete``: User finishing a purchase. - - ``search``: Product search. - - ``shopping-cart-page-view``: User viewing a shopping - cart. - visitor_id (str): - Required. A unique identifier for tracking visitors. - - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor log in/out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - The field should not contain PII or user-data. We recommend - to use Google Analystics `Client - ID `__ - for this field. - session_id (str): - A unique identifier for tracking a visitor session with a - length limit of 128 bytes. A session is an aggregation of an - end user behavior in a time span. - - A general guideline to populate the sesion_id: - - 1. If user has no activity for 30 min, a new session_id - should be assigned. - 2. The session_id should be unique across users, suggest use - uuid or add visitor_id as prefix. - event_time (google.protobuf.timestamp_pb2.Timestamp): - Only required for - [UserEventService.ImportUserEvents][google.cloud.retail.v2alpha.UserEventService.ImportUserEvents] - method. Timestamp of when the user event happened. - experiment_ids (Sequence[str]): - A list of identifiers for the independent - experiment groups this user event belongs to. - This is used to distinguish between user events - associated with different experiment setups - (e.g. using Retail API, using different - recommendation models). - attribution_token (str): - Highly recommended for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2alpha.PredictionService.Predict]. - This field enables accurate attribution of recommendation - model performance. - - The value must be a valid - [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] - for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2alpha.PredictionService.Predict]. - The value must be a valid - [SearchResponse.attribution_token][google.cloud.retail.v2alpha.SearchResponse.attribution_token] - for user events that are the result of - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - This token enables us to accurately attribute page view or - purchase back to the event and the particular predict - response containing this clicked/purchased product. If user - clicks on product K in the recommendation results, pass - [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] - as a URL parameter to product K's page. When recording - events on product K's page, log the - [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] - to this field. - product_details (Sequence[google.cloud.retail_v2alpha.types.ProductDetail]): - The main product details related to the event. - - This field is required for the following event types: - - - ``add-to-cart`` - - ``detail-page-view`` - - ``purchase-complete`` - - ``search`` - - In a ``search`` event, this field represents the products - returned to the end user on the current page (the end user - may have not finished browsing the whole page yet). When a - new page is returned to the end user, after - pagination/filtering/ordering even for the same query, a new - ``search`` event with different - [product_details][google.cloud.retail.v2alpha.UserEvent.product_details] - is desired. The end user may have not finished browsing the - whole page yet. - completion_detail (google.cloud.retail_v2alpha.types.CompletionDetail): - The main auto-completion details related to the event. - - This field should be set for ``search`` event when - autocomplete function is enabled and the user clicks a - suggestion for search. - attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): - Extra user event features to include in the recommendation - model. - - If you provide custom attributes for ingested user events, - also include them in the user events that you associate with - prediction requests. Custom attribute formatting must be - consistent between imported events and events provided with - prediction requests. This lets the Retail API use those - custom attributes when training models and serving - predictions, which helps improve recommendation quality. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - The key must be a UTF-8 encoded string with a length - limit of 5,000 characters. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a UTF-8 - encoded string with a length limit of 256 characters. - - For number attributes, at most 400 values are allowed. - - For product recommendations, an example of extra user - information is traffic_channel, which is how a user arrives - at the site. Users can arrive at the site by coming to the - site directly, coming through Google search, or in other - ways. - cart_id (str): - The ID or name of the associated shopping cart. This ID is - used to associate multiple items added or present in the - cart before purchase. - - This can only be set for ``add-to-cart``, - ``purchase-complete``, or ``shopping-cart-page-view`` - events. - purchase_transaction (google.cloud.retail_v2alpha.types.PurchaseTransaction): - A transaction represents the entire purchase transaction. - - Required for ``purchase-complete`` events. Other event types - should not set this field. Otherwise, an INVALID_ARGUMENT - error is returned. - search_query (str): - The user's search query. - - See - [SearchRequest.query][google.cloud.retail.v2alpha.SearchRequest.query] - for definition. - - The value must be a UTF-8 encoded string with a length limit - of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - At least one of - [search_query][google.cloud.retail.v2alpha.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. - - See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - order_by (str): - The order in which products are returned. - - See - [SearchRequest.order_by][google.cloud.retail.v2alpha.SearchRequest.order_by] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - offset (int): - An integer that specifies the current offset for pagination - (the 0-indexed starting location, amongst the products - deemed by the API as relevant). - - See - [SearchRequest.offset][google.cloud.retail.v2alpha.SearchRequest.offset] - for definition. - - If this field is negative, an INVALID_ARGUMENT is returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - - Required for ``category-page-view`` events. At least one of - [search_query][google.cloud.retail.v2alpha.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2alpha.types.UserInfo): - User information. - uri (str): - Complete URL (window.location.href) of the - user's current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. Maximum length - 5,000 characters. - referrer_uri (str): - The referrer URL of the current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. - page_view_id (str): - A unique ID of a web page view. - - This should be kept the same for all user events triggered - from the same pageview. For example, an item detail page - view could trigger multiple events as the user is browsing - the page. The ``pageViewId`` property should be kept the - same for all these events so that they can be grouped - together properly. - - When using the client side event reporting with JavaScript - pixel and Google Tag Manager, this value is filled in - automatically. - """ - - event_type = proto.Field( - proto.STRING, - number=1, - ) - visitor_id = proto.Field( - proto.STRING, - number=2, - ) - session_id = proto.Field( - proto.STRING, - number=21, - ) - event_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - experiment_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - product_details = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='ProductDetail', - ) - completion_detail = proto.Field( - proto.MESSAGE, - number=22, - message='CompletionDetail', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=common.CustomAttribute, - ) - cart_id = proto.Field( - proto.STRING, - number=8, - ) - purchase_transaction = proto.Field( - proto.MESSAGE, - number=9, - message='PurchaseTransaction', - ) - search_query = proto.Field( - proto.STRING, - number=10, - ) - filter = proto.Field( - proto.STRING, - number=16, - ) - order_by = proto.Field( - proto.STRING, - number=17, - ) - offset = proto.Field( - proto.INT32, - number=18, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=11, - ) - user_info = proto.Field( - proto.MESSAGE, - number=12, - message=common.UserInfo, - ) - uri = proto.Field( - proto.STRING, - number=13, - ) - referrer_uri = proto.Field( - proto.STRING, - number=14, - ) - page_view_id = proto.Field( - proto.STRING, - number=15, - ) - - -class ProductDetail(proto.Message): - r"""Detailed product information associated with a user event. - - Attributes: - product (google.cloud.retail_v2alpha.types.Product): - Required. [Product][google.cloud.retail.v2alpha.Product] - information. - - Required field(s): - - - [Product.id][google.cloud.retail.v2alpha.Product.id] - - Optional override field(s): - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - If any supported optional fields are provided, we will treat - them as a full override when looking up product information - from the catalog. Thus, it is important to ensure that the - overriding fields are accurate and complete. - - All other product fields are ignored and instead populated - via catalog lookup after event ingestion. - quantity (google.protobuf.wrappers_pb2.Int32Value): - Quantity of the product associated with the user event. - - For example, this field will be 2 if two products are added - to the shopping cart for ``purchase-complete`` event. - Required for ``add-to-cart`` and ``purchase-complete`` event - types. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - quantity = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -class CompletionDetail(proto.Message): - r"""Detailed completion information including completion - attribution token and clicked completion info. - - Attributes: - completion_attribution_token (str): - Completion attribution token in - [CompleteQueryResponse.attribution_token][google.cloud.retail.v2alpha.CompleteQueryResponse.attribution_token]. - selected_suggestion (str): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2alpha.CompleteQueryResponse.CompletionResult.suggestion]. - selected_position (int): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2alpha.CompleteQueryResponse.CompletionResult.suggestion] - position, starting from 0. - """ - - completion_attribution_token = proto.Field( - proto.STRING, - number=1, - ) - selected_suggestion = proto.Field( - proto.STRING, - number=2, - ) - selected_position = proto.Field( - proto.INT32, - number=3, - ) - - -class PurchaseTransaction(proto.Message): - r"""A transaction represents the entire purchase transaction. - - Attributes: - id (str): - The transaction ID with a length limit of 128 - characters. - revenue (float): - Required. Total non-zero revenue or grand - total associated with the transaction. This - value include shipping, tax, or other - adjustments to total revenue that you want to - include as part of your revenue calculations. - tax (float): - All the taxes associated with the - transaction. - cost (float): - All the costs associated with the products. These can be - manufacturing costs, shipping expenses not borne by the end - user, or any other costs, such that: - - - Profit = - [revenue][google.cloud.retail.v2alpha.PurchaseTransaction.revenue] - - - [tax][google.cloud.retail.v2alpha.PurchaseTransaction.tax] - - - [cost][google.cloud.retail.v2alpha.PurchaseTransaction.cost] - currency_code (str): - Required. Currency code. Use three-character - ISO-4217 code. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - revenue = proto.Field( - proto.FLOAT, - number=2, - ) - tax = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - currency_code = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py deleted file mode 100644 index 0e679b22..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import user_event as gcr_user_event - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'WriteUserEventRequest', - 'CollectUserEventRequest', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'RejoinUserEventsMetadata', - }, -) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (google.cloud.retail_v2alpha.types.UserEvent): - Required. User event to write. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (str): - Required. URL encoded UserEvent proto with a - length limit of 2,000,000 characters. - uri (str): - The URL including cgi-parameters but - excluding the hash fragment with a length limit - of 5,000 characters. This is often more useful - than the referer URL, because many browsers only - send the domain for 3rd party requests. - ets (int): - The event timestamp in milliseconds. This - prevents browser caching of otherwise identical - get requests. The name is abbreviated to reduce - the payload bytes. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.STRING, - number=2, - ) - uri = proto.Field( - proto.STRING, - number=3, - ) - ets = proto.Field( - proto.INT64, - number=4, - ) - - -class RejoinUserEventsRequest(proto.Message): - r"""Request message for RejoinUserEvents method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event_rejoin_scope (google.cloud.retail_v2alpha.types.RejoinUserEventsRequest.UserEventRejoinScope): - The type of the user event rejoin to define the scope and - range of the user events to be rejoined with the latest - product catalog. Defaults to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not - set, or set to an invalid integer value. - """ - class UserEventRejoinScope(proto.Enum): - r"""The scope of user events to be rejoined with the latest product - catalog. If the rejoining aims at reducing number of unjoined - events, set UserEventRejoinScope to UNJOINED_EVENTS. If the - rejoining aims at correcting product catalog information in joined - events, set UserEventRejoinScope to JOINED_EVENTS. If all events - needs to be rejoined, set UserEventRejoinScope to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. - """ - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 - JOINED_EVENTS = 1 - UNJOINED_EVENTS = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event_rejoin_scope = proto.Field( - proto.ENUM, - number=2, - enum=UserEventRejoinScope, - ) - - -class RejoinUserEventsResponse(proto.Message): - r"""Response message for RejoinUserEvents method. - - Attributes: - rejoined_user_events_count (int): - Number of user events that were joined with - latest product catalog. - """ - - rejoined_user_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -class RejoinUserEventsMetadata(proto.Message): - r"""Metadata for RejoinUserEvents method. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/mypy.ini b/owl-bot-staging/v2alpha/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v2alpha/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2alpha/noxfile.py b/owl-bot-staging/v2alpha/noxfile.py deleted file mode 100644 index 9f7eeaa1..00000000 --- a/owl-bot-staging/v2alpha/noxfile.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.6", - "3.7", - "3.8", - "3.9", - "3.10", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==19.10b0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.9" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/retail_v2alpha/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py deleted file mode 100644 index 9b5622c2..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async] -from google.cloud import retail_v2alpha - - -async def sample_add_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py deleted file mode 100644 index ec76bc9f..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync] -from google.cloud import retail_v2alpha - - -def sample_add_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py deleted file mode 100644 index d2f66638..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetAttributesConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_get_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetAttributesConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py deleted file mode 100644 index 91c914b3..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_get_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py deleted file mode 100644 index 9da8e840..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetCompletionConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_get_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetCompletionConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py deleted file mode 100644 index 5da5cd9f..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_get_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py deleted file mode 100644 index 2134a810..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetDefaultBranch_async] -from google.cloud import retail_v2alpha - - -async def sample_get_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py deleted file mode 100644 index d233b424..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync] -from google.cloud import retail_v2alpha - - -def sample_get_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py deleted file mode 100644 index 7e7fbf33..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_ListCatalogs_async] -from google.cloud import retail_v2alpha - - -async def sample_list_catalogs(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py deleted file mode 100644 index 8165c25b..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_ListCatalogs_sync] -from google.cloud import retail_v2alpha - - -def sample_list_catalogs(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py deleted file mode 100644 index f79bd768..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async] -from google.cloud import retail_v2alpha - - -async def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = await client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py deleted file mode 100644 index 35b6611c..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync] -from google.cloud import retail_v2alpha - - -def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py deleted file mode 100644 index c42a8bb1..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReplaceCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async] -from google.cloud import retail_v2alpha - - -async def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py deleted file mode 100644 index 56e779ab..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReplaceCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync] -from google.cloud import retail_v2alpha - - -def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py deleted file mode 100644 index 9ddf2f8e..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_SetDefaultBranch_async] -from google.cloud import retail_v2alpha - - -async def sample_set_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - -# [END retail_v2alpha_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py deleted file mode 100644 index 6fa13ce6..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync] -from google.cloud import retail_v2alpha - - -def sample_set_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - -# [END retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py deleted file mode 100644 index c4654be4..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_update_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - attributes_config = retail_v2alpha.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2alpha.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = await client.update_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py deleted file mode 100644 index 1f4d3432..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_update_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - attributes_config = retail_v2alpha.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2alpha.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = client.update_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py deleted file mode 100644 index 6035f718..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateCatalog_async] -from google.cloud import retail_v2alpha - - -async def sample_update_catalog(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2alpha.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2alpha.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py deleted file mode 100644 index 35fff0d1..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateCatalog_sync] -from google.cloud import retail_v2alpha - - -def sample_update_catalog(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2alpha.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2alpha.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py deleted file mode 100644 index 26cac134..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_update_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - completion_config = retail_v2alpha.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2alpha.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = await client.update_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py deleted file mode 100644 index b9e11448..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_update_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - completion_config = retail_v2alpha.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2alpha.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = client.update_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py deleted file mode 100644 index 13dce99f..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CompletionService_CompleteQuery_async] -from google.cloud import retail_v2alpha - - -async def sample_complete_query(): - # Create a client - client = retail_v2alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py deleted file mode 100644 index 20687e33..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CompletionService_CompleteQuery_sync] -from google.cloud import retail_v2alpha - - -def sample_complete_query(): - # Create a client - client = retail_v2alpha.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py deleted file mode 100644 index d1a515f2..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CompletionService_ImportCompletionData_async] -from google.cloud import retail_v2alpha - - -async def sample_import_completion_data(): - # Create a client - client = retail_v2alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2alpha.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py deleted file mode 100644 index 3c6ddc55..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CompletionService_ImportCompletionData_sync] -from google.cloud import retail_v2alpha - - -def sample_import_completion_data(): - # Create a client - client = retail_v2alpha.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2alpha.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py deleted file mode 100644 index 131de87e..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_CreateControl_async] -from google.cloud import retail_v2alpha - - -async def sample_create_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = await client.create_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_CreateControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py deleted file mode 100644 index 8fee66d8..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_CreateControl_sync] -from google.cloud import retail_v2alpha - - -def sample_create_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = client.create_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_CreateControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py deleted file mode 100644 index ae438a78..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_DeleteControl_async] -from google.cloud import retail_v2alpha - - -async def sample_delete_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteControlRequest( - name="name_value", - ) - - # Make the request - await client.delete_control(request=request) - - -# [END retail_v2alpha_generated_ControlService_DeleteControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py deleted file mode 100644 index b83ddcd5..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_DeleteControl_sync] -from google.cloud import retail_v2alpha - - -def sample_delete_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteControlRequest( - name="name_value", - ) - - # Make the request - client.delete_control(request=request) - - -# [END retail_v2alpha_generated_ControlService_DeleteControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py deleted file mode 100644 index 588c8955..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_GetControl_async] -from google.cloud import retail_v2alpha - - -async def sample_get_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetControlRequest( - name="name_value", - ) - - # Make the request - response = await client.get_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_GetControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py deleted file mode 100644 index f04eb36b..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_GetControl_sync] -from google.cloud import retail_v2alpha - - -def sample_get_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetControlRequest( - name="name_value", - ) - - # Make the request - response = client.get_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_GetControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py deleted file mode 100644 index 005329c1..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListControls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_ListControls_async] -from google.cloud import retail_v2alpha - - -async def sample_list_controls(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ControlService_ListControls_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py deleted file mode 100644 index 301c6036..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListControls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_ListControls_sync] -from google.cloud import retail_v2alpha - - -def sample_list_controls(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ControlService_ListControls_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py deleted file mode 100644 index dc422066..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_UpdateControl_async] -from google.cloud import retail_v2alpha - - -async def sample_update_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.UpdateControlRequest( - control=control, - ) - - # Make the request - response = await client.update_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_UpdateControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py deleted file mode 100644 index cf7823fd..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_UpdateControl_sync] -from google.cloud import retail_v2alpha - - -def sample_update_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.UpdateControlRequest( - control=control, - ) - - # Make the request - response = client.update_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_UpdateControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py deleted file mode 100644 index 7d3c4540..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_PredictionService_Predict_async] -from google.cloud import retail_v2alpha - - -async def sample_predict(): - # Create a client - client = retail_v2alpha.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py deleted file mode 100644 index c3dbd187..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_PredictionService_Predict_sync] -from google.cloud import retail_v2alpha - - -def sample_predict(): - # Create a client - client = retail_v2alpha.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py deleted file mode 100644 index 4ef15987..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async] -from google.cloud import retail_v2alpha - - -async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py deleted file mode 100644 index 03f0cd6d..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync] -from google.cloud import retail_v2alpha - - -def sample_add_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py deleted file mode 100644 index c3b7dfdf..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_AddLocalInventories_async] -from google.cloud import retail_v2alpha - - -async def sample_add_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py deleted file mode 100644 index b91b57f3..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_AddLocalInventories_sync] -from google.cloud import retail_v2alpha - - -def sample_add_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py deleted file mode 100644 index 8ca45663..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_CreateProduct_async] -from google.cloud import retail_v2alpha - - -async def sample_create_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py deleted file mode 100644 index b2946508..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_CreateProduct_sync] -from google.cloud import retail_v2alpha - - -def sample_create_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py deleted file mode 100644 index 1ae74222..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_DeleteProduct_async] -from google.cloud import retail_v2alpha - - -async def sample_delete_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - -# [END retail_v2alpha_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py deleted file mode 100644 index faebc2e4..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_DeleteProduct_sync] -from google.cloud import retail_v2alpha - - -def sample_delete_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - -# [END retail_v2alpha_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py deleted file mode 100644 index 70903b9e..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_GetProduct_async] -from google.cloud import retail_v2alpha - - -async def sample_get_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py deleted file mode 100644 index 25fccda2..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_GetProduct_sync] -from google.cloud import retail_v2alpha - - -def sample_get_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py deleted file mode 100644 index 5cfaf031..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_ImportProducts_async] -from google.cloud import retail_v2alpha - - -async def sample_import_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2alpha.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py deleted file mode 100644 index ca54ea57..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_ImportProducts_sync] -from google.cloud import retail_v2alpha - - -def sample_import_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2alpha.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py deleted file mode 100644 index 8dcf7a71..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_ListProducts_async] -from google.cloud import retail_v2alpha - - -async def sample_list_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py deleted file mode 100644 index aa96e9c2..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_ListProducts_sync] -from google.cloud import retail_v2alpha - - -def sample_list_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py deleted file mode 100644 index 8adf6af4..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_PurgeProducts_async] -from google.cloud import retail_v2alpha - - -async def sample_purge_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeProductsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_PurgeProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py deleted file mode 100644 index 72c32c88..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_PurgeProducts_sync] -from google.cloud import retail_v2alpha - - -def sample_purge_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeProductsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_PurgeProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py deleted file mode 100644 index da379da0..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async] -from google.cloud import retail_v2alpha - - -async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py deleted file mode 100644 index 55bf6522..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync] -from google.cloud import retail_v2alpha - - -def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py deleted file mode 100644 index bc0b9406..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_RemoveLocalInventories_async] -from google.cloud import retail_v2alpha - - -async def sample_remove_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py deleted file mode 100644 index 40e0b2bb..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync] -from google.cloud import retail_v2alpha - - -def sample_remove_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py deleted file mode 100644 index 64dc769c..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_SetInventory_async] -from google.cloud import retail_v2alpha - - -async def sample_set_inventory(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2alpha.Product() - inventory.title = "title_value" - - request = retail_v2alpha.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py deleted file mode 100644 index 9dbf88b6..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_SetInventory_sync] -from google.cloud import retail_v2alpha - - -def sample_set_inventory(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2alpha.Product() - inventory.title = "title_value" - - request = retail_v2alpha.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py deleted file mode 100644 index 35df5c2b..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_UpdateProduct_async] -from google.cloud import retail_v2alpha - - -async def sample_update_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py deleted file mode 100644 index 6248e977..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_UpdateProduct_sync] -from google.cloud import retail_v2alpha - - -def sample_update_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py deleted file mode 100644 index 75520b76..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_SearchService_Search_async] -from google.cloud import retail_v2alpha - - -async def sample_search(): - # Create a client - client = retail_v2alpha.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py deleted file mode 100644 index 2b2853a3..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_SearchService_Search_sync] -from google.cloud import retail_v2alpha - - -def sample_search(): - # Create a client - client = retail_v2alpha.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py deleted file mode 100644 index 0694590c..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_AddControl_async] -from google.cloud import retail_v2alpha - - -async def sample_add_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.add_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_AddControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py deleted file mode 100644 index 10d50ff7..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_AddControl_sync] -from google.cloud import retail_v2alpha - - -def sample_add_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.add_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_AddControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py deleted file mode 100644 index 33b080fc..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_create_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = await client.create_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py deleted file mode 100644 index e7b0e80e..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_create_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = client.create_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py deleted file mode 100644 index f8259bdf..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_delete_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_serving_config(request=request) - - -# [END retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py deleted file mode 100644 index 621916ef..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_delete_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_serving_config(request=request) - - -# [END retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py deleted file mode 100644 index fdfd4d80..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_GetServingConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_get_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_GetServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py deleted file mode 100644 index a1408016..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_get_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py deleted file mode 100644 index c8244f95..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServingConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async] -from google.cloud import retail_v2alpha - - -async def sample_list_serving_configs(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py deleted file mode 100644 index 86e02687..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServingConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync] -from google.cloud import retail_v2alpha - - -def sample_list_serving_configs(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py deleted file mode 100644 index 66e07902..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_RemoveControl_async] -from google.cloud import retail_v2alpha - - -async def sample_remove_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.remove_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_RemoveControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py deleted file mode 100644 index 8b39362b..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_RemoveControl_sync] -from google.cloud import retail_v2alpha - - -def sample_remove_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.remove_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_RemoveControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py deleted file mode 100644 index 64e82dba..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_update_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = await client.update_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py deleted file mode 100644 index 46d2d65c..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_update_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = client.update_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py deleted file mode 100644 index f8aa3f78..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_CollectUserEvent_async] -from google.cloud import retail_v2alpha - - -async def sample_collect_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py deleted file mode 100644 index 026972b1..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_CollectUserEvent_sync] -from google.cloud import retail_v2alpha - - -def sample_collect_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py deleted file mode 100644 index 540ce130..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_ImportUserEvents_async] -from google.cloud import retail_v2alpha - - -async def sample_import_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2alpha.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py deleted file mode 100644 index fe9310db..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_ImportUserEvents_sync] -from google.cloud import retail_v2alpha - - -def sample_import_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2alpha.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py deleted file mode 100644 index 17d5c66d..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_PurgeUserEvents_async] -from google.cloud import retail_v2alpha - - -async def sample_purge_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py deleted file mode 100644 index d8b2ae83..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync] -from google.cloud import retail_v2alpha - - -def sample_purge_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py deleted file mode 100644 index d38bb5f4..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_RejoinUserEvents_async] -from google.cloud import retail_v2alpha - - -async def sample_rejoin_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py deleted file mode 100644 index f88f6437..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync] -from google.cloud import retail_v2alpha - - -def sample_rejoin_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py deleted file mode 100644 index 2dda0e65..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_WriteUserEvent_async] -from google.cloud import retail_v2alpha - - -async def sample_write_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py deleted file mode 100644 index a121bdbd..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_WriteUserEvent_sync] -from google.cloud import retail_v2alpha - - -def sample_write_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json b/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json deleted file mode 100644 index ea2cf419..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json +++ /dev/null @@ -1,7066 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.retail.v2alpha", - "version": "v2alpha" - } - ], - "language": "PYTHON", - "name": "google-cloud-retail" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.add_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "AddCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "add_catalog_attribute" - }, - "description": "Sample for AddCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.add_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "AddCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "add_catalog_attribute" - }, - "description": "Sample for AddCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetAttributesConfigRequest" - }, - { - "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.retail_v2alpha.types.AttributesConfig", - "shortName": "get_attributes_config" - }, - "description": "Sample for GetAttributesConfig", - "file": "retail_v2alpha_generated_catalog_service_get_attributes_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetAttributesConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_attributes_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetAttributesConfigRequest" - }, - { - "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.retail_v2alpha.types.AttributesConfig", - "shortName": "get_attributes_config" - }, - "description": "Sample for GetAttributesConfig", - "file": "retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_completion_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetCompletionConfigRequest" - }, - { - "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.retail_v2alpha.types.CompletionConfig", - "shortName": "get_completion_config" - }, - "description": "Sample for GetCompletionConfig", - "file": "retail_v2alpha_generated_catalog_service_get_completion_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetCompletionConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_completion_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_completion_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetCompletionConfigRequest" - }, - { - "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.retail_v2alpha.types.CompletionConfig", - "shortName": "get_completion_config" - }, - "description": "Sample for GetCompletionConfig", - "file": "retail_v2alpha_generated_catalog_service_get_completion_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_completion_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2alpha_generated_catalog_service_get_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetDefaultBranch_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2alpha_generated_catalog_service_get_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListCatalogsRequest" - }, - { - "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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsAsyncPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2alpha_generated_catalog_service_list_catalogs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_ListCatalogs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_list_catalogs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListCatalogsRequest" - }, - { - "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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2alpha_generated_catalog_service_list_catalogs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_ListCatalogs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_list_catalogs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.remove_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "RemoveCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "remove_catalog_attribute" - }, - "description": "Sample for RemoveCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.remove_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "RemoveCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "remove_catalog_attribute" - }, - "description": "Sample for RemoveCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.replace_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ReplaceCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "replace_catalog_attribute" - }, - "description": "Sample for ReplaceCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.replace_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ReplaceCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "replace_catalog_attribute" - }, - "description": "Sample for ReplaceCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2alpha_generated_catalog_service_set_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_SetDefaultBranch_async", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_set_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2alpha_generated_catalog_service_set_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_set_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest" - }, - { - "name": "attributes_config", - "type": "google.cloud.retail_v2alpha.types.AttributesConfig" - }, - { - "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.retail_v2alpha.types.AttributesConfig", - "shortName": "update_attributes_config" - }, - "description": "Sample for UpdateAttributesConfig", - "file": "retail_v2alpha_generated_catalog_service_update_attributes_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_attributes_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest" - }, - { - "name": "attributes_config", - "type": "google.cloud.retail_v2alpha.types.AttributesConfig" - }, - { - "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.retail_v2alpha.types.AttributesConfig", - "shortName": "update_attributes_config" - }, - "description": "Sample for UpdateAttributesConfig", - "file": "retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2alpha.types.Catalog" - }, - { - "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.retail_v2alpha.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2alpha_generated_catalog_service_update_catalog_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCatalog_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_catalog_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2alpha.types.Catalog" - }, - { - "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.retail_v2alpha.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2alpha_generated_catalog_service_update_catalog_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCatalog_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_catalog_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_completion_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest" - }, - { - "name": "completion_config", - "type": "google.cloud.retail_v2alpha.types.CompletionConfig" - }, - { - "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.retail_v2alpha.types.CompletionConfig", - "shortName": "update_completion_config" - }, - "description": "Sample for UpdateCompletionConfig", - "file": "retail_v2alpha_generated_catalog_service_update_completion_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_completion_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_completion_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest" - }, - { - "name": "completion_config", - "type": "google.cloud.retail_v2alpha.types.CompletionConfig" - }, - { - "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.retail_v2alpha.types.CompletionConfig", - "shortName": "update_completion_config" - }, - "description": "Sample for UpdateCompletionConfig", - "file": "retail_v2alpha_generated_catalog_service_update_completion_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_completion_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2alpha.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2alpha_generated_completion_service_complete_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CompletionService_CompleteQuery_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_completion_service_complete_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2alpha.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2alpha_generated_completion_service_complete_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CompletionService_CompleteQuery_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_completion_service_complete_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2alpha.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2alpha_generated_completion_service_import_completion_data_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CompletionService_ImportCompletionData_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_completion_service_import_completion_data_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2alpha.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2alpha_generated_completion_service_import_completion_data_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CompletionService_ImportCompletionData_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_completion_service_import_completion_data_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.create_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.CreateControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "CreateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateControlRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "control", - "type": "google.cloud.retail_v2alpha.types.Control" - }, - { - "name": "control_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.retail_v2alpha.types.Control", - "shortName": "create_control" - }, - "description": "Sample for CreateControl", - "file": "retail_v2alpha_generated_control_service_create_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_CreateControl_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_create_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.create_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.CreateControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "CreateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateControlRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "control", - "type": "google.cloud.retail_v2alpha.types.Control" - }, - { - "name": "control_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.retail_v2alpha.types.Control", - "shortName": "create_control" - }, - "description": "Sample for CreateControl", - "file": "retail_v2alpha_generated_control_service_create_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_CreateControl_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_create_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.delete_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.DeleteControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "DeleteControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteControlRequest" - }, - { - "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_control" - }, - "description": "Sample for DeleteControl", - "file": "retail_v2alpha_generated_control_service_delete_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_DeleteControl_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_delete_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.delete_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.DeleteControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "DeleteControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteControlRequest" - }, - { - "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_control" - }, - "description": "Sample for DeleteControl", - "file": "retail_v2alpha_generated_control_service_delete_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_DeleteControl_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_delete_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.get_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.GetControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "GetControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetControlRequest" - }, - { - "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.retail_v2alpha.types.Control", - "shortName": "get_control" - }, - "description": "Sample for GetControl", - "file": "retail_v2alpha_generated_control_service_get_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_GetControl_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_get_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.get_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.GetControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "GetControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetControlRequest" - }, - { - "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.retail_v2alpha.types.Control", - "shortName": "get_control" - }, - "description": "Sample for GetControl", - "file": "retail_v2alpha_generated_control_service_get_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_GetControl_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_get_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.list_controls", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.ListControls", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "ListControls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListControlsRequest" - }, - { - "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.retail_v2alpha.services.control_service.pagers.ListControlsAsyncPager", - "shortName": "list_controls" - }, - "description": "Sample for ListControls", - "file": "retail_v2alpha_generated_control_service_list_controls_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_ListControls_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_list_controls_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.list_controls", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.ListControls", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "ListControls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListControlsRequest" - }, - { - "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.retail_v2alpha.services.control_service.pagers.ListControlsPager", - "shortName": "list_controls" - }, - "description": "Sample for ListControls", - "file": "retail_v2alpha_generated_control_service_list_controls_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_ListControls_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_list_controls_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.update_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.UpdateControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "UpdateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateControlRequest" - }, - { - "name": "control", - "type": "google.cloud.retail_v2alpha.types.Control" - }, - { - "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.retail_v2alpha.types.Control", - "shortName": "update_control" - }, - "description": "Sample for UpdateControl", - "file": "retail_v2alpha_generated_control_service_update_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_UpdateControl_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_update_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.update_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.UpdateControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "UpdateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateControlRequest" - }, - { - "name": "control", - "type": "google.cloud.retail_v2alpha.types.Control" - }, - { - "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.retail_v2alpha.types.Control", - "shortName": "update_control" - }, - "description": "Sample for UpdateControl", - "file": "retail_v2alpha_generated_control_service_update_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_UpdateControl_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_update_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.PredictionServiceAsyncClient", - "shortName": "PredictionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.PredictionServiceAsyncClient.predict", - "method": { - "fullName": "google.cloud.retail.v2alpha.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2alpha.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2alpha_generated_prediction_service_predict_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_PredictionService_Predict_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_prediction_service_predict_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.PredictionServiceClient", - "shortName": "PredictionServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.PredictionServiceClient.predict", - "method": { - "fullName": "google.cloud.retail.v2alpha.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2alpha.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2alpha_generated_prediction_service_predict_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_PredictionService_Predict_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_prediction_service_predict_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2alpha_generated_product_service_add_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_add_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2alpha_generated_product_service_add_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_AddLocalInventories_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_add_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2alpha_generated_product_service_add_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_AddLocalInventories_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_add_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "name": "product_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.retail_v2alpha.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2alpha_generated_product_service_create_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_CreateProduct_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_create_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "name": "product_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.retail_v2alpha.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2alpha_generated_product_service_create_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_CreateProduct_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_create_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2alpha_generated_product_service_delete_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_DeleteProduct_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_delete_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2alpha_generated_product_service_delete_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_DeleteProduct_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_delete_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetProductRequest" - }, - { - "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.retail_v2alpha.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2alpha_generated_product_service_get_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_GetProduct_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_get_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetProductRequest" - }, - { - "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.retail_v2alpha.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2alpha_generated_product_service_get_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_GetProduct_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_get_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2alpha_generated_product_service_import_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_ImportProducts_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_import_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2alpha_generated_product_service_import_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_ImportProducts_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_import_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListProductsRequest" - }, - { - "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.retail_v2alpha.services.product_service.pagers.ListProductsAsyncPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2alpha_generated_product_service_list_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_ListProducts_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_list_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListProductsRequest" - }, - { - "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.retail_v2alpha.services.product_service.pagers.ListProductsPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2alpha_generated_product_service_list_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_ListProducts_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_list_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.purge_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.PurgeProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "PurgeProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PurgeProductsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_products" - }, - "description": "Sample for PurgeProducts", - "file": "retail_v2alpha_generated_product_service_purge_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_PurgeProducts_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_purge_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.purge_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.PurgeProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "PurgeProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PurgeProductsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_products" - }, - "description": "Sample for PurgeProducts", - "file": "retail_v2alpha_generated_product_service_purge_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_PurgeProducts_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_purge_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2alpha_generated_product_service_remove_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_RemoveLocalInventories_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_remove_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2alpha_generated_product_service_remove_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_remove_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2alpha_generated_product_service_set_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_SetInventory_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_set_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2alpha_generated_product_service_set_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_SetInventory_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_set_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "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.retail_v2alpha.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2alpha_generated_product_service_update_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_UpdateProduct_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_update_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "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.retail_v2alpha.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2alpha_generated_product_service_update_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_UpdateProduct_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_update_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.SearchServiceAsyncClient.search", - "method": { - "fullName": "google.cloud.retail.v2alpha.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2alpha.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2alpha_generated_search_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_SearchService_Search_async", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_search_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.SearchServiceClient", - "shortName": "SearchServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.SearchServiceClient.search", - "method": { - "fullName": "google.cloud.retail.v2alpha.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2alpha.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.services.search_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2alpha_generated_search_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_SearchService_Search_sync", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_search_service_search_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.add_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.AddControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "AddControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "add_control" - }, - "description": "Sample for AddControl", - "file": "retail_v2alpha_generated_serving_config_service_add_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_AddControl_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_add_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.add_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.AddControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "AddControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "add_control" - }, - "description": "Sample for AddControl", - "file": "retail_v2alpha_generated_serving_config_service_add_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_AddControl_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_add_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.create_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.CreateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "CreateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateServingConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2alpha.types.ServingConfig" - }, - { - "name": "serving_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "create_serving_config" - }, - "description": "Sample for CreateServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_create_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_create_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.create_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.CreateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "CreateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateServingConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2alpha.types.ServingConfig" - }, - { - "name": "serving_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "create_serving_config" - }, - "description": "Sample for CreateServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.delete_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.DeleteServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "DeleteServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteServingConfigRequest" - }, - { - "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_serving_config" - }, - "description": "Sample for DeleteServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.delete_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.DeleteServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "DeleteServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteServingConfigRequest" - }, - { - "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_serving_config" - }, - "description": "Sample for DeleteServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.get_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.GetServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "GetServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetServingConfigRequest" - }, - { - "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.retail_v2alpha.types.ServingConfig", - "shortName": "get_serving_config" - }, - "description": "Sample for GetServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_get_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_GetServingConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_get_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.get_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.GetServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "GetServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetServingConfigRequest" - }, - { - "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.retail_v2alpha.types.ServingConfig", - "shortName": "get_serving_config" - }, - "description": "Sample for GetServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.list_serving_configs", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.ListServingConfigs", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "ListServingConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListServingConfigsRequest" - }, - { - "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.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsAsyncPager", - "shortName": "list_serving_configs" - }, - "description": "Sample for ListServingConfigs", - "file": "retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.list_serving_configs", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.ListServingConfigs", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "ListServingConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListServingConfigsRequest" - }, - { - "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.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsPager", - "shortName": "list_serving_configs" - }, - "description": "Sample for ListServingConfigs", - "file": "retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.remove_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.RemoveControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "RemoveControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "remove_control" - }, - "description": "Sample for RemoveControl", - "file": "retail_v2alpha_generated_serving_config_service_remove_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_RemoveControl_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_remove_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.remove_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.RemoveControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "RemoveControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "remove_control" - }, - "description": "Sample for RemoveControl", - "file": "retail_v2alpha_generated_serving_config_service_remove_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_RemoveControl_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_remove_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.update_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.UpdateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "UpdateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2alpha.types.ServingConfig" - }, - { - "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.retail_v2alpha.types.ServingConfig", - "shortName": "update_serving_config" - }, - "description": "Sample for UpdateServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_update_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_update_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.update_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.UpdateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "UpdateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2alpha.types.ServingConfig" - }, - { - "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.retail_v2alpha.types.ServingConfig", - "shortName": "update_serving_config" - }, - "description": "Sample for UpdateServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2alpha_generated_user_event_service_collect_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_CollectUserEvent_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_collect_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2alpha_generated_user_event_service_collect_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_CollectUserEvent_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_collect_user_event_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2alpha_generated_user_event_service_import_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_ImportUserEvents_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_import_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2alpha_generated_user_event_service_import_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_ImportUserEvents_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_import_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2alpha_generated_user_event_service_purge_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_PurgeUserEvents_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_purge_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2alpha_generated_user_event_service_purge_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_purge_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_RejoinUserEvents_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2alpha_generated_user_event_service_write_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_WriteUserEvent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_write_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2alpha_generated_user_event_service_write_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_WriteUserEvent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_write_user_event_sync.py" - } - ] -} diff --git a/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py b/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py deleted file mode 100644 index 5fbe2d4d..00000000 --- a/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py +++ /dev/null @@ -1,219 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class retailCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_catalog_attribute': ('attributes_config', 'catalog_attribute', ), - 'add_control': ('serving_config', 'control_id', ), - 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), - 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), - 'create_control': ('parent', 'control', 'control_id', ), - 'create_product': ('parent', 'product', 'product_id', ), - 'create_serving_config': ('parent', 'serving_config', 'serving_config_id', ), - 'delete_control': ('name', ), - 'delete_product': ('name', ), - 'delete_serving_config': ('name', ), - 'get_attributes_config': ('name', ), - 'get_completion_config': ('name', ), - 'get_control': ('name', ), - 'get_default_branch': ('catalog', ), - 'get_product': ('name', ), - 'get_serving_config': ('name', ), - 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), - 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), - 'import_user_events': ('parent', 'input_config', 'errors_config', ), - 'list_catalogs': ('parent', 'page_size', 'page_token', ), - 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', 'require_total_size', ), - 'list_serving_configs': ('parent', 'page_size', 'page_token', ), - 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), - 'purge_products': ('parent', 'filter', 'force', ), - 'purge_user_events': ('parent', 'filter', 'force', ), - 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), - 'remove_catalog_attribute': ('attributes_config', 'key', ), - 'remove_control': ('serving_config', 'control_id', ), - 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), - 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), - 'replace_catalog_attribute': ('attributes_config', 'catalog_attribute', 'update_mask', ), - 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'relevance_threshold', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), - 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), - 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), - 'update_attributes_config': ('attributes_config', 'update_mask', ), - 'update_catalog': ('catalog', 'update_mask', ), - 'update_completion_config': ('completion_config', 'update_mask', ), - 'update_control': ('control', 'update_mask', ), - 'update_product': ('product', 'update_mask', 'allow_missing', ), - 'update_serving_config': ('serving_config', 'update_mask', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=retailCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the retail client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2alpha/setup.py b/owl-bot-staging/v2alpha/setup.py deleted file mode 100644 index 1103510b..00000000 --- a/owl-bot-staging/v2alpha/setup.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-retail', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-retail", - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 2.8.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'googleapis-common-protos >= 1.55.0, <2.0.0dev', - 'proto-plus >= 1.19.7', - ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v2alpha/tests/__init__.py b/owl-bot-staging/v2alpha/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2alpha/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/tests/unit/__init__.py b/owl-bot-staging/v2alpha/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py deleted file mode 100644 index 8815d72e..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py +++ /dev/null @@ -1,3844 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.catalog_service import CatalogServiceAsyncClient -from google.cloud.retail_v2alpha.services.catalog_service import CatalogServiceClient -from google.cloud.retail_v2alpha.services.catalog_service import pagers -from google.cloud.retail_v2alpha.services.catalog_service import transports -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CatalogServiceClient._get_default_mtls_endpoint(None) is None - assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CatalogServiceGrpcTransport, "grpc"), - (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_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", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_catalog_service_client_get_transport_class(): - transport = CatalogServiceClient.get_transport_class() - available_transports = [ - transports.CatalogServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CatalogServiceClient.get_transport_class("grpc") - assert transport == transports.CatalogServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CatalogServiceClient, CatalogServiceAsyncClient -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_catalog_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ListCatalogsRequest, - dict, -]) -def test_list_catalogs(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalogs), - '__call__') as call: - client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - -@pytest.mark.asyncio -async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_catalogs_async_from_dict(): - await test_list_catalogs_async(request_type=dict) - - -def test_list_catalogs_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = catalog_service.ListCatalogsResponse() - client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_catalogs( - 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_catalogs_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_catalogs_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_catalogs( - 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_catalogs_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - - -def test_list_catalogs_pager(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_catalogs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, catalog.Catalog) - for i in results) -def test_list_catalogs_pages(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = list(client.list_catalogs(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_catalogs_async_pager(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_catalogs(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, catalog.Catalog) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_catalogs_async_pages(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCatalogRequest, - dict, -]) -def test_update_catalog(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - ) - response = client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_catalog_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalog), - '__call__') as call: - client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - -@pytest.mark.asyncio -async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_catalog_async_from_dict(): - await test_update_catalog_async(request_type=dict) - - -def test_update_catalog_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = gcr_catalog.Catalog() - client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_catalog_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -def test_update_catalog_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_catalog_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.SetDefaultBranchRequest, - dict, -]) -def test_set_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_set_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_set_default_branch_async_from_dict(): - await test_set_default_branch_async(request_type=dict) - - -def test_set_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = None - client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_set_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_set_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetDefaultBranchRequest, - dict, -]) -def test_get_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - ) - response = client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -def test_get_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_default_branch), - '__call__') as call: - client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - )) - response = await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -@pytest.mark.asyncio -async def test_get_default_branch_async_from_dict(): - await test_get_default_branch_async(request_type=dict) - - -def test_get_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = catalog_service.GetDefaultBranchResponse() - client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_get_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_get_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetCompletionConfigRequest, - dict, -]) -def test_get_completion_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - ) - response = client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -def test_get_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_completion_config), - '__call__') as call: - client.get_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - -@pytest.mark.asyncio -async def test_get_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCompletionConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - )) - response = await client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -@pytest.mark.asyncio -async def test_get_completion_config_async_from_dict(): - await test_get_completion_config_async(request_type=dict) - - -def test_get_completion_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCompletionConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - call.return_value = catalog.CompletionConfig() - client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_completion_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCompletionConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - await client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_completion_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_completion_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_completion_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_completion_config( - catalog_service.GetCompletionConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_completion_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_completion_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_completion_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_completion_config( - catalog_service.GetCompletionConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCompletionConfigRequest, - dict, -]) -def test_update_completion_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - ) - response = client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -def test_update_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_completion_config), - '__call__') as call: - client.update_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - -@pytest.mark.asyncio -async def test_update_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCompletionConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - )) - response = await client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -@pytest.mark.asyncio -async def test_update_completion_config_async_from_dict(): - await test_update_completion_config_async(request_type=dict) - - -def test_update_completion_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCompletionConfigRequest() - - request.completion_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - call.return_value = catalog.CompletionConfig() - client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'completion_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_completion_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCompletionConfigRequest() - - request.completion_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - await client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'completion_config.name=name_value', - ) in kw['metadata'] - - -def test_update_completion_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_completion_config( - completion_config=catalog.CompletionConfig(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].completion_config - mock_val = catalog.CompletionConfig(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_completion_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_completion_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_completion_config( - completion_config=catalog.CompletionConfig(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].completion_config - mock_val = catalog.CompletionConfig(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_completion_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetAttributesConfigRequest, - dict, -]) -def test_get_attributes_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_get_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_attributes_config), - '__call__') as call: - client.get_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - -@pytest.mark.asyncio -async def test_get_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetAttributesConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_get_attributes_config_async_from_dict(): - await test_get_attributes_config_async(request_type=dict) - - -def test_get_attributes_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetAttributesConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_attributes_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetAttributesConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_attributes_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_attributes_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_attributes_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_attributes_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_attributes_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_attributes_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateAttributesConfigRequest, - dict, -]) -def test_update_attributes_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_update_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_attributes_config), - '__call__') as call: - client.update_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - -@pytest.mark.asyncio -async def test_update_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateAttributesConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_update_attributes_config_async_from_dict(): - await test_update_attributes_config_async(request_type=dict) - - -def test_update_attributes_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateAttributesConfigRequest() - - request.attributes_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_attributes_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateAttributesConfigRequest() - - request.attributes_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config.name=name_value', - ) in kw['metadata'] - - -def test_update_attributes_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_attributes_config( - attributes_config=catalog.AttributesConfig(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].attributes_config - mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_attributes_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_attributes_config( - attributes_config=catalog.AttributesConfig(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].attributes_config - mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.AddCatalogAttributeRequest, - dict, -]) -def test_add_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_add_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - client.add_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_add_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.AddCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_add_catalog_attribute_async_from_dict(): - await test_add_catalog_attribute_async(request_type=dict) - - -def test_add_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.AddCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.AddCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - catalog_service.RemoveCatalogAttributeRequest, - dict, -]) -def test_remove_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_remove_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - client.remove_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.RemoveCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_async_from_dict(): - await test_remove_catalog_attribute_async(request_type=dict) - - -def test_remove_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.RemoveCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.RemoveCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ReplaceCatalogAttributeRequest, - dict, -]) -def test_replace_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_replace_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - client.replace_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ReplaceCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_async_from_dict(): - await test_replace_catalog_attribute_async(request_type=dict) - - -def test_replace_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ReplaceCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ReplaceCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CatalogServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.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 = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CatalogServiceGrpcTransport, - ) - -def test_catalog_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_catalog_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_catalogs', - 'update_catalog', - 'set_default_branch', - 'get_default_branch', - 'get_completion_config', - 'update_completion_config', - 'get_attributes_config', - 'update_attributes_config', - 'add_catalog_attribute', - 'remove_catalog_attribute', - 'replace_catalog_attribute', - ) - 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_catalog_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.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport( - 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_catalog_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.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport() - adc.assert_called_once() - - -def test_catalog_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) - CatalogServiceClient() - 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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -def test_catalog_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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - transports.CatalogServiceRestTransport, - ], -) -def test_catalog_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.CatalogServiceGrpcTransport, grpc_helpers), - (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_catalog_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_no_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_with_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_catalog_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcTransport( - 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_catalog_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcAsyncIOTransport( - 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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_attributes_config_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.attributes_config_path(project, location, catalog) - assert expected == actual - - -def test_parse_attributes_config_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CatalogServiceClient.attributes_config_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_attributes_config_path(path) - assert expected == actual - -def test_branch_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = CatalogServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "branch": "clam", - } - path = CatalogServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_branch_path(path) - assert expected == actual - -def test_catalog_path(): - project = "whelk" - location = "octopus" - catalog = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - } - path = CatalogServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_completion_config_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.completion_config_path(project, location, catalog) - assert expected == actual - - -def test_parse_completion_config_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - } - path = CatalogServiceClient.completion_config_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_completion_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CatalogServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = CatalogServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = CatalogServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = CatalogServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CatalogServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = CatalogServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = CatalogServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = CatalogServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = CatalogServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CatalogServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py deleted file mode 100644 index b6ce8b74..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py +++ /dev/null @@ -1,1502 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.completion_service import CompletionServiceAsyncClient -from google.cloud.retail_v2alpha.services.completion_service import CompletionServiceClient -from google.cloud.retail_v2alpha.services.completion_service import transports -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CompletionServiceClient._get_default_mtls_endpoint(None) is None - assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CompletionServiceGrpcTransport, "grpc"), - (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_completion_service_client_get_transport_class(): - transport = CompletionServiceClient.get_transport_class() - available_transports = [ - transports.CompletionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CompletionServiceClient.get_transport_class("grpc") - assert transport == transports.CompletionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CompletionServiceClient, CompletionServiceAsyncClient -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_completion_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CompletionServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - ) - response = client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - -@pytest.mark.asyncio -async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - )) - response = await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -@pytest.mark.asyncio -async def test_complete_query_async_from_dict(): - await test_complete_query_async(request_type=dict) - - -def test_complete_query_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = completion_service.CompleteQueryResponse() - client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_complete_query_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) - await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportCompletionDataRequest, - dict, -]) -def test_import_completion_data(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_completion_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - -@pytest.mark.asyncio -async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_completion_data_async_from_dict(): - await test_import_completion_data_async(request_type=dict) - - -def test_import_completion_data_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # 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_completion_data_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CompletionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CompletionServiceGrpcTransport, - ) - -def test_completion_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_completion_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'complete_query', - 'import_completion_data', - ) - 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_completion_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_completion_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport() - adc.assert_called_once() - - -def test_completion_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CompletionServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, - ], -) -def test_completion_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionServiceGrpcTransport, grpc_helpers), - (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_completion_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_no_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_with_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_completion_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_completion_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_completion_service_grpc_lro_client(): - client = CompletionServiceClient( - 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_completion_service_grpc_lro_async_client(): - client = CompletionServiceAsyncClient( - 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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CompletionServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CompletionServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CompletionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CompletionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = CompletionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CompletionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CompletionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CompletionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = CompletionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CompletionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CompletionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CompletionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CompletionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py deleted file mode 100644 index 158ed377..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py +++ /dev/null @@ -1,2617 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.control_service import ControlServiceAsyncClient -from google.cloud.retail_v2alpha.services.control_service import ControlServiceClient -from google.cloud.retail_v2alpha.services.control_service import pagers -from google.cloud.retail_v2alpha.services.control_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.cloud.retail_v2alpha.types import search_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ControlServiceClient._get_default_mtls_endpoint(None) is None - assert ControlServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ControlServiceClient, "grpc"), - (ControlServiceAsyncClient, "grpc_asyncio"), -]) -def test_control_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ControlServiceGrpcTransport, "grpc"), - (transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_control_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", [ - (ControlServiceClient, "grpc"), - (ControlServiceAsyncClient, "grpc_asyncio"), -]) -def test_control_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_control_service_client_get_transport_class(): - transport = ControlServiceClient.get_transport_class() - available_transports = [ - transports.ControlServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ControlServiceClient.get_transport_class("grpc") - assert transport == transports.ControlServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -def test_control_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(ControlServiceClient, '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(ControlServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "true"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "false"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_control_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ControlServiceClient, ControlServiceAsyncClient -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -def test_control_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_control_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_control_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_control_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.control_service.transports.ControlServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ControlServiceClient( - 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", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_control_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.CreateControlRequest, - dict, -]) -def test_create_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -def test_create_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.create_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - -@pytest.mark.asyncio -async def test_create_control_async(transport: str = 'grpc_asyncio', request_type=control_service.CreateControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - )) - response = await client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -@pytest.mark.asyncio -async def test_create_control_async_from_dict(): - await test_create_control_async(request_type=dict) - - -def test_create_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.CreateControlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - call.return_value = gcr_control.Control() - client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.CreateControlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - await client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_control( - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) - assert arg == mock_val - arg = args[0].control_id - mock_val = 'control_id_value' - assert arg == mock_val - - -def test_create_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.CreateControlRequest(), - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_id_value', - ) - -@pytest.mark.asyncio -async def test_create_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_control( - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) - assert arg == mock_val - arg = args[0].control_id - mock_val = 'control_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.CreateControlRequest(), - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.DeleteControlRequest, - dict, -]) -def test_delete_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.delete_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - -@pytest.mark.asyncio -async def test_delete_control_async(transport: str = 'grpc_asyncio', request_type=control_service.DeleteControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_control_async_from_dict(): - await test_delete_control_async(request_type=dict) - - -def test_delete_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.DeleteControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__call__') as call: - call.return_value = None - client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.DeleteControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__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_control( - 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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.DeleteControlRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__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_control( - 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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.DeleteControlRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.UpdateControlRequest, - dict, -]) -def test_update_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -def test_update_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.update_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - -@pytest.mark.asyncio -async def test_update_control_async(transport: str = 'grpc_asyncio', request_type=control_service.UpdateControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - )) - response = await client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -@pytest.mark.asyncio -async def test_update_control_async_from_dict(): - await test_update_control_async(request_type=dict) - - -def test_update_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.UpdateControlRequest() - - request.control.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - call.return_value = gcr_control.Control() - client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'control.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.UpdateControlRequest() - - request.control.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - await client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'control.name=name_value', - ) in kw['metadata'] - - -def test_update_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_control( - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_control( - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.GetControlRequest, - dict, -]) -def test_get_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -def test_get_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.get_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - -@pytest.mark.asyncio -async def test_get_control_async(transport: str = 'grpc_asyncio', request_type=control_service.GetControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - )) - response = await client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -@pytest.mark.asyncio -async def test_get_control_async_from_dict(): - await test_get_control_async(request_type=dict) - - -def test_get_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.GetControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - call.return_value = control.Control() - client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.GetControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) - await client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_control( - 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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.GetControlRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_control( - 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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.GetControlRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.ListControlsRequest, - dict, -]) -def test_list_controls(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_controls_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_controls), - '__call__') as call: - client.list_controls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - -@pytest.mark.asyncio -async def test_list_controls_async(transport: str = 'grpc_asyncio', request_type=control_service.ListControlsRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_controls_async_from_dict(): - await test_list_controls_async(request_type=dict) - - -def test_list_controls_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.ListControlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - call.return_value = control_service.ListControlsResponse() - client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_controls_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.ListControlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) - await client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_controls_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_controls( - 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_controls_flattened_error(): - client = ControlServiceClient( - credentials=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_controls( - control_service.ListControlsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_controls_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_controls( - 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_controls_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_controls( - control_service.ListControlsRequest(), - parent='parent_value', - ) - - -def test_list_controls_pager(transport_name: str = "grpc"): - client = ControlServiceClient( - 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_controls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_controls(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, control.Control) - for i in results) -def test_list_controls_pages(transport_name: str = "grpc"): - client = ControlServiceClient( - 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_controls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - pages = list(client.list_controls(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_controls_async_pager(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_controls(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, control.Control) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_controls_async_pages(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_controls(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ControlServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ControlServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ControlServiceClient.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 = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ControlServiceGrpcTransport, - ) - -def test_control_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ControlServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_control_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.control_service.transports.ControlServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ControlServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_control', - 'delete_control', - 'update_control', - 'get_control', - 'list_controls', - ) - 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_control_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.retail_v2alpha.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ControlServiceTransport( - 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_control_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.retail_v2alpha.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ControlServiceTransport() - adc.assert_called_once() - - -def test_control_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) - ControlServiceClient() - 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.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - ], -) -def test_control_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.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - transports.ControlServiceRestTransport, - ], -) -def test_control_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.ControlServiceGrpcTransport, grpc_helpers), - (transports.ControlServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_control_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_control_service_host_no_port(transport_name): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_control_service_host_with_port(transport_name): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_control_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ControlServiceGrpcTransport( - 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_control_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ControlServiceGrpcAsyncIOTransport( - 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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = ControlServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = ControlServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_control_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - control = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) - actual = ControlServiceClient.control_path(project, location, catalog, control) - assert expected == actual - - -def test_parse_control_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "control": "clam", - } - path = ControlServiceClient.control_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_control_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ControlServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ControlServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ControlServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ControlServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ControlServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ControlServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ControlServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ControlServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.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 = ControlServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ControlServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.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.ControlServiceTransport, '_prep_wrapped_messages') as prep: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ControlServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ControlServiceClient.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 = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ControlServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ControlServiceClient( - 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", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py deleted file mode 100644 index 92f4d20d..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py +++ /dev/null @@ -1,1330 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.prediction_service import PredictionServiceAsyncClient -from google.cloud.retail_v2alpha.services.prediction_service import PredictionServiceClient -from google.cloud.retail_v2alpha.services.prediction_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import prediction_service -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import user_event -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PredictionServiceClient._get_default_mtls_endpoint(None) is None - assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PredictionServiceGrpcTransport, "grpc"), - (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_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", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_prediction_service_client_get_transport_class(): - transport = PredictionServiceClient.get_transport_class() - available_transports = [ - transports.PredictionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = PredictionServiceClient.get_transport_class("grpc") - assert transport == transports.PredictionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - PredictionServiceClient, PredictionServiceAsyncClient -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_prediction_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - prediction_service.PredictRequest, - dict, -]) -def test_predict(request_type, transport: str = 'grpc'): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - response = client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - -@pytest.mark.asyncio -async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - )) - response = await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -@pytest.mark.asyncio -async def test_predict_async_from_dict(): - await test_predict_async(request_type=dict) - - -def test_predict_field_headers(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = prediction_service.PredictResponse() - client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_predict_field_headers_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) - await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PredictionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PredictionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.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 = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, - ) - -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'predict', - ) - 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport( - 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport() - adc.assert_called_once() - - -def test_prediction_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) - PredictionServiceClient() - 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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -def test_prediction_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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - transports.PredictionServiceRestTransport, - ], -) -def test_prediction_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.PredictionServiceGrpcTransport, grpc_helpers), - (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_prediction_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_no_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_with_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_prediction_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcTransport( - 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_prediction_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcAsyncIOTransport( - 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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_product_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - product = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - "branch": "winkle", - "product": "nautilus", - } - path = PredictionServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PredictionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = PredictionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = PredictionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = PredictionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PredictionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = PredictionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = PredictionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = PredictionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = PredictionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PredictionServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py deleted file mode 100644 index b6106cae..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py +++ /dev/null @@ -1,4288 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.product_service import ProductServiceAsyncClient -from google.cloud.retail_v2alpha.services.product_service import ProductServiceClient -from google.cloud.retail_v2alpha.services.product_service import pagers -from google.cloud.retail_v2alpha.services.product_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import purge_config -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ProductServiceClient._get_default_mtls_endpoint(None) is None - assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ProductServiceGrpcTransport, "grpc"), - (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_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", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_product_service_client_get_transport_class(): - transport = ProductServiceClient.get_transport_class() - available_transports = [ - transports.ProductServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ProductServiceClient.get_transport_class("grpc") - assert transport == transports.ProductServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_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(ProductServiceClient, '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(ProductServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ProductServiceClient, ProductServiceAsyncClient -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_product_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.CreateProductRequest, - dict, -]) -def test_create_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_create_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - -@pytest.mark.asyncio -async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_create_product_async_from_dict(): - await test_create_product_async(request_type=dict) - - -def test_create_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - - -def test_create_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - -@pytest.mark.asyncio -async def test_create_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.GetProductRequest, - dict, -]) -def test_get_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_get_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - -@pytest.mark.asyncio -async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_get_product_async_from_dict(): - await test_get_product_async(request_type=dict) - - -def test_get_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = product.Product() - client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.GetProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.GetProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.ListProductsRequest, - dict, -]) -def test_list_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - -@pytest.mark.asyncio -async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_products_async_from_dict(): - await test_list_products_async(request_type=dict) - - -def test_list_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = product_service.ListProductsResponse() - client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_products( - 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_products_flattened_error(): - client = ProductServiceClient( - credentials=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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_products_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_products( - 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_products_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - - -def test_list_products_pager(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_products(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, product.Product) - for i in results) -def test_list_products_pages(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = list(client.list_products(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_products_async_pager(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_products(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, product.Product) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_products_async_pages(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_products(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - product_service.UpdateProductRequest, - dict, -]) -def test_update_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_update_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - -@pytest.mark.asyncio -async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_update_product_async_from_dict(): - await test_update_product_async(request_type=dict) - - -def test_update_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -def test_update_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.DeleteProductRequest, - dict, -]) -def test_delete_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - -@pytest.mark.asyncio -async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_product_async_from_dict(): - await test_delete_product_async(request_type=dict) - - -def test_delete_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = None - client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeProductsRequest, - dict, -]) -def test_purge_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - client.purge_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - -@pytest.mark.asyncio -async def test_purge_products_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.purge_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_products_async_from_dict(): - await test_purge_products_async(request_type=dict) - - -def test_purge_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_purge_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportProductsRequest, - dict, -]) -def test_import_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - -@pytest.mark.asyncio -async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__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_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_products_async_from_dict(): - await test_import_products_async(request_type=dict) - - -def test_import_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - product_service.SetInventoryRequest, - dict, -]) -def test_set_inventory(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_inventory_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - -@pytest.mark.asyncio -async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_inventory_async_from_dict(): - await test_set_inventory_async(request_type=dict) - - -def test_set_inventory_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_inventory_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -def test_set_inventory_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_set_inventory_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_set_inventory_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_inventory_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddFulfillmentPlacesRequest, - dict, -]) -def test_add_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async_from_dict(): - await test_add_fulfillment_places_async(request_type=dict) - - -def test_add_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveFulfillmentPlacesRequest, - dict, -]) -def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async_from_dict(): - await test_remove_fulfillment_places_async(request_type=dict) - - -def test_remove_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddLocalInventoriesRequest, - dict, -]) -def test_add_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_local_inventories_async_from_dict(): - await test_add_local_inventories_async(request_type=dict) - - -def test_add_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveLocalInventoriesRequest, - dict, -]) -def test_remove_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_local_inventories_async_from_dict(): - await test_remove_local_inventories_async(request_type=dict) - - -def test_remove_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProductServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ProductServiceClient.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 = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProductServiceGrpcTransport, - ) - -def test_product_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_product_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.product_service.transports.ProductServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_product', - 'get_product', - 'list_products', - 'update_product', - 'delete_product', - 'purge_products', - 'import_products', - 'set_inventory', - 'add_fulfillment_places', - 'remove_fulfillment_places', - 'add_local_inventories', - 'remove_local_inventories', - ) - 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_product_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.retail_v2alpha.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport( - 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_product_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.retail_v2alpha.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport() - adc.assert_called_once() - - -def test_product_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) - ProductServiceClient() - 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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - ], -) -def test_product_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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - transports.ProductServiceRestTransport, - ], -) -def test_product_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.ProductServiceGrpcTransport, grpc_helpers), - (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_product_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_no_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_with_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_product_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcTransport( - 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_product_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcAsyncIOTransport( - 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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_product_service_grpc_lro_client(): - client = ProductServiceClient( - 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_product_service_grpc_lro_async_client(): - client = ProductServiceAsyncClient( - 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" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = ProductServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = ProductServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = ProductServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = ProductServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProductServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ProductServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProductServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ProductServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProductServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ProductServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ProductServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ProductServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ProductServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ProductServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ProductServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py deleted file mode 100644 index 1060de11..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py +++ /dev/null @@ -1,1547 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.search_service import SearchServiceAsyncClient -from google.cloud.retail_v2alpha.services.search_service import SearchServiceClient -from google.cloud.retail_v2alpha.services.search_service import pagers -from google.cloud.retail_v2alpha.services.search_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SearchServiceClient._get_default_mtls_endpoint(None) is None - assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SearchServiceGrpcTransport, "grpc"), - (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_search_service_client_get_transport_class(): - transport = SearchServiceClient.get_transport_class() - available_transports = [ - transports.SearchServiceGrpcTransport, - ] - assert transport in available_transports - - transport = SearchServiceClient.get_transport_class("grpc") - assert transport == transports.SearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SearchServiceClient, SearchServiceAsyncClient -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SearchServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - search_service.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - - -def test_search_field_headers(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = search_service.SearchResponse() - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_field_headers_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_search_pager(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('placement', ''), - )), - ) - pager = client.search(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_async_pager(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, - ) - -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_search_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_search_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport() - adc.assert_called_once() - - -def test_search_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SearchServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - transports.SearchServiceRestTransport, - ], -) -def test_search_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SearchServiceGrpcTransport, grpc_helpers), - (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_search_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_no_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_with_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_branch_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = SearchServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = SearchServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = SearchServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = SearchServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py deleted file mode 100644 index 8cfe1d67..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py +++ /dev/null @@ -1,3330 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.serving_config_service import ServingConfigServiceAsyncClient -from google.cloud.retail_v2alpha.services.serving_config_service import ServingConfigServiceClient -from google.cloud.retail_v2alpha.services.serving_config_service import pagers -from google.cloud.retail_v2alpha.services.serving_config_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ServingConfigServiceClient._get_default_mtls_endpoint(None) is None - assert ServingConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServingConfigServiceClient, "grpc"), - (ServingConfigServiceAsyncClient, "grpc_asyncio"), -]) -def test_serving_config_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ServingConfigServiceGrpcTransport, "grpc"), - (transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_serving_config_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", [ - (ServingConfigServiceClient, "grpc"), - (ServingConfigServiceAsyncClient, "grpc_asyncio"), -]) -def test_serving_config_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_serving_config_service_client_get_transport_class(): - transport = ServingConfigServiceClient.get_transport_class() - available_transports = [ - transports.ServingConfigServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ServingConfigServiceClient.get_transport_class("grpc") - assert transport == transports.ServingConfigServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -def test_serving_config_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(ServingConfigServiceClient, '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(ServingConfigServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "true"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "false"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_serving_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ServingConfigServiceClient, ServingConfigServiceAsyncClient -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -def test_serving_config_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_serving_config_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_serving_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_serving_config_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ServingConfigServiceClient( - 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", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_serving_config_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.CreateServingConfigRequest, - dict, -]) -def test_create_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_create_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.create_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - -@pytest.mark.asyncio -async def test_create_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.CreateServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_create_serving_config_async_from_dict(): - await test_create_serving_config_async(request_type=dict) - - -def test_create_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.CreateServingConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.CreateServingConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_serving_config( - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].serving_config - mock_val = gcr_serving_config.ServingConfig(name='name_value') - assert arg == mock_val - arg = args[0].serving_config_id - mock_val = 'serving_config_id_value' - assert arg == mock_val - - -def test_create_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.CreateServingConfigRequest(), - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_serving_config( - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].serving_config - mock_val = gcr_serving_config.ServingConfig(name='name_value') - assert arg == mock_val - arg = args[0].serving_config_id - mock_val = 'serving_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.CreateServingConfigRequest(), - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.DeleteServingConfigRequest, - dict, -]) -def test_delete_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.delete_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - -@pytest.mark.asyncio -async def test_delete_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.DeleteServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_serving_config_async_from_dict(): - await test_delete_serving_config_async(request_type=dict) - - -def test_delete_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.DeleteServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__call__') as call: - call.return_value = None - client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.DeleteServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__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_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.DeleteServingConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__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_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.DeleteServingConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.UpdateServingConfigRequest, - dict, -]) -def test_update_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_update_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.update_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - -@pytest.mark.asyncio -async def test_update_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.UpdateServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_update_serving_config_async_from_dict(): - await test_update_serving_config_async(request_type=dict) - - -def test_update_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.UpdateServingConfigRequest() - - request.serving_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.UpdateServingConfigRequest() - - request.serving_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config.name=name_value', - ) in kw['metadata'] - - -def test_update_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_serving_config( - serving_config=gcr_serving_config.ServingConfig(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].serving_config - mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_serving_config( - serving_config=gcr_serving_config.ServingConfig(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].serving_config - mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.GetServingConfigRequest, - dict, -]) -def test_get_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_get_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.get_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - -@pytest.mark.asyncio -async def test_get_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.GetServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_get_serving_config_async_from_dict(): - await test_get_serving_config_async(request_type=dict) - - -def test_get_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.GetServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - call.return_value = serving_config.ServingConfig() - client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.GetServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) - await client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.GetServingConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.GetServingConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.ListServingConfigsRequest, - dict, -]) -def test_list_serving_configs(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_serving_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_configs), - '__call__') as call: - client.list_serving_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - -@pytest.mark.asyncio -async def test_list_serving_configs_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.ListServingConfigsRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_serving_configs_async_from_dict(): - await test_list_serving_configs_async(request_type=dict) - - -def test_list_serving_configs_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.ListServingConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - call.return_value = serving_config_service.ListServingConfigsResponse() - client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_serving_configs_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.ListServingConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) - await client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_serving_configs_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_serving_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_serving_configs_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_serving_configs_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_serving_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_serving_configs_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent='parent_value', - ) - - -def test_list_serving_configs_pager(transport_name: str = "grpc"): - client = ServingConfigServiceClient( - 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_serving_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_serving_configs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, serving_config.ServingConfig) - for i in results) -def test_list_serving_configs_pages(transport_name: str = "grpc"): - client = ServingConfigServiceClient( - 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_serving_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_serving_configs(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_serving_configs_async_pager(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_serving_configs(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, serving_config.ServingConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_serving_configs_async_pages(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_serving_configs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - serving_config_service.AddControlRequest, - dict, -]) -def test_add_control(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_add_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - client.add_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - -@pytest.mark.asyncio -async def test_add_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.AddControlRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_add_control_async_from_dict(): - await test_add_control_async(request_type=dict) - - -def test_add_control_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.AddControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_control_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.AddControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_add_control_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.add_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - - -def test_add_control_flattened_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_control( - serving_config_service.AddControlRequest(), - serving_config='serving_config_value', - ) - -@pytest.mark.asyncio -async def test_add_control_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.add_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_control_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_control( - serving_config_service.AddControlRequest(), - serving_config='serving_config_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.RemoveControlRequest, - dict, -]) -def test_remove_control(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_remove_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - client.remove_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - -@pytest.mark.asyncio -async def test_remove_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.RemoveControlRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_remove_control_async_from_dict(): - await test_remove_control_async(request_type=dict) - - -def test_remove_control_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.RemoveControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_control_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.RemoveControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_remove_control_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.remove_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - - -def test_remove_control_flattened_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config='serving_config_value', - ) - -@pytest.mark.asyncio -async def test_remove_control_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.remove_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_control_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config='serving_config_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ServingConfigServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ServingConfigServiceClient.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 = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ServingConfigServiceGrpcTransport, - ) - -def test_serving_config_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ServingConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_serving_config_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ServingConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_serving_config', - 'delete_serving_config', - 'update_serving_config', - 'get_serving_config', - 'list_serving_configs', - 'add_control', - 'remove_control', - ) - 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_serving_config_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.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServingConfigServiceTransport( - 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_serving_config_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.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServingConfigServiceTransport() - adc.assert_called_once() - - -def test_serving_config_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) - ServingConfigServiceClient() - 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.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - ], -) -def test_serving_config_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.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - transports.ServingConfigServiceRestTransport, - ], -) -def test_serving_config_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.ServingConfigServiceGrpcTransport, grpc_helpers), - (transports.ServingConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_serving_config_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_serving_config_service_host_no_port(transport_name): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_serving_config_service_host_with_port(transport_name): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_serving_config_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServingConfigServiceGrpcTransport( - 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_serving_config_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( - 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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = ServingConfigServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = ServingConfigServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - serving_config = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, serving_config=serving_config, ) - actual = ServingConfigServiceClient.serving_config_path(project, location, catalog, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "serving_config": "clam", - } - path = ServingConfigServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ServingConfigServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ServingConfigServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ServingConfigServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ServingConfigServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ServingConfigServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ServingConfigServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ServingConfigServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ServingConfigServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.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 = ServingConfigServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ServingConfigServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.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.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ServingConfigServiceClient.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 = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ServingConfigServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ServingConfigServiceClient( - 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", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py deleted file mode 100644 index 358ae900..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py +++ /dev/null @@ -1,2039 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.retail_v2alpha.services.user_event_service import UserEventServiceClient -from google.cloud.retail_v2alpha.services.user_event_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, UserEventServiceAsyncClient -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - ) - response = client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = user_event.UserEvent() - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) - await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeUserEventsRequest, - dict, -]) -def test_purge_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - -@pytest.mark.asyncio -async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_user_events_async_from_dict(): - await test_purge_user_events_async(request_type=dict) - - -def test_purge_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_purge_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.RejoinUserEventsRequest, - dict, -]) -def test_rejoin_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_rejoin_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - -@pytest.mark.asyncio -async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_rejoin_user_events_async_from_dict(): - await test_rejoin_user_events_async(request_type=dict) - - -def test_rejoin_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_rejoin_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'purge_user_events', - 'import_user_events', - 'rejoin_user_events', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_user_event_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_user_event_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -def test_user_event_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - UserEventServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, - ], -) -def test_user_event_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_no_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_with_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = UserEventServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = UserEventServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_product_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - product = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - "branch": "whelk", - "product": "octopus", - } - path = UserEventServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/.coveragerc b/owl-bot-staging/v2beta/.coveragerc deleted file mode 100644 index a8b114f0..00000000 --- a/owl-bot-staging/v2beta/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/retail/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2beta/.flake8 b/owl-bot-staging/v2beta/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v2beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2beta/MANIFEST.in b/owl-bot-staging/v2beta/MANIFEST.in deleted file mode 100644 index 43074617..00000000 --- a/owl-bot-staging/v2beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/retail *.py -recursive-include google/cloud/retail_v2beta *.py diff --git a/owl-bot-staging/v2beta/README.rst b/owl-bot-staging/v2beta/README.rst deleted file mode 100644 index cb039760..00000000 --- a/owl-bot-staging/v2beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Retail API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Retail API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2beta/docs/conf.py b/owl-bot-staging/v2beta/docs/conf.py deleted file mode 100644 index 5be9eb4b..00000000 --- a/owl-bot-staging/v2beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-retail documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-retail" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-retail-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-retail.tex", - u"google-cloud-retail Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-retail", - u"Google Cloud Retail Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-retail", - u"google-cloud-retail Documentation", - author, - "google-cloud-retail", - "GAPIC library for Google Cloud Retail API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2beta/docs/index.rst b/owl-bot-staging/v2beta/docs/index.rst deleted file mode 100644 index fd60fc85..00000000 --- a/owl-bot-staging/v2beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - retail_v2beta/services - retail_v2beta/types diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst deleted file mode 100644 index 3a7c19e6..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CatalogService --------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.catalog_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.catalog_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst deleted file mode 100644 index 1f6782ed..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CompletionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2beta.services.completion_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst deleted file mode 100644 index 86cfcba1..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ControlService --------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.control_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.control_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst deleted file mode 100644 index 903c951d..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -PredictionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2beta.services.prediction_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst deleted file mode 100644 index 489daa22..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ProductService --------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.product_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.product_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst deleted file mode 100644 index 591f5c86..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SearchService -------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst deleted file mode 100644 index 04251720..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst +++ /dev/null @@ -1,13 +0,0 @@ -Services for Google Cloud Retail v2beta API -=========================================== -.. toctree:: - :maxdepth: 2 - - catalog_service - completion_service - control_service - prediction_service - product_service - search_service - serving_config_service - user_event_service diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst deleted file mode 100644 index c074749c..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ServingConfigService --------------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.serving_config_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.serving_config_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst deleted file mode 100644 index ae17ce43..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Retail v2beta API -======================================== - -.. automodule:: google.cloud.retail_v2beta.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst deleted file mode 100644 index 11ab3794..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.user_event_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/google/cloud/retail/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail/__init__.py deleted file mode 100644 index 07f795e3..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail/__init__.py +++ /dev/null @@ -1,275 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.retail_v2beta.services.catalog_service.client import CatalogServiceClient -from google.cloud.retail_v2beta.services.catalog_service.async_client import CatalogServiceAsyncClient -from google.cloud.retail_v2beta.services.completion_service.client import CompletionServiceClient -from google.cloud.retail_v2beta.services.completion_service.async_client import CompletionServiceAsyncClient -from google.cloud.retail_v2beta.services.control_service.client import ControlServiceClient -from google.cloud.retail_v2beta.services.control_service.async_client import ControlServiceAsyncClient -from google.cloud.retail_v2beta.services.prediction_service.client import PredictionServiceClient -from google.cloud.retail_v2beta.services.prediction_service.async_client import PredictionServiceAsyncClient -from google.cloud.retail_v2beta.services.product_service.client import ProductServiceClient -from google.cloud.retail_v2beta.services.product_service.async_client import ProductServiceAsyncClient -from google.cloud.retail_v2beta.services.search_service.client import SearchServiceClient -from google.cloud.retail_v2beta.services.search_service.async_client import SearchServiceAsyncClient -from google.cloud.retail_v2beta.services.serving_config_service.client import ServingConfigServiceClient -from google.cloud.retail_v2beta.services.serving_config_service.async_client import ServingConfigServiceAsyncClient -from google.cloud.retail_v2beta.services.user_event_service.client import UserEventServiceClient -from google.cloud.retail_v2beta.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.retail_v2beta.types.catalog import AttributesConfig -from google.cloud.retail_v2beta.types.catalog import Catalog -from google.cloud.retail_v2beta.types.catalog import CatalogAttribute -from google.cloud.retail_v2beta.types.catalog import CompletionConfig -from google.cloud.retail_v2beta.types.catalog import MerchantCenterLink -from google.cloud.retail_v2beta.types.catalog import MerchantCenterLinkingConfig -from google.cloud.retail_v2beta.types.catalog import ProductLevelConfig -from google.cloud.retail_v2beta.types.catalog_service import AddCatalogAttributeRequest -from google.cloud.retail_v2beta.types.catalog_service import GetAttributesConfigRequest -from google.cloud.retail_v2beta.types.catalog_service import GetCompletionConfigRequest -from google.cloud.retail_v2beta.types.catalog_service import GetDefaultBranchRequest -from google.cloud.retail_v2beta.types.catalog_service import GetDefaultBranchResponse -from google.cloud.retail_v2beta.types.catalog_service import ListCatalogsRequest -from google.cloud.retail_v2beta.types.catalog_service import ListCatalogsResponse -from google.cloud.retail_v2beta.types.catalog_service import RemoveCatalogAttributeRequest -from google.cloud.retail_v2beta.types.catalog_service import ReplaceCatalogAttributeRequest -from google.cloud.retail_v2beta.types.catalog_service import SetDefaultBranchRequest -from google.cloud.retail_v2beta.types.catalog_service import UpdateAttributesConfigRequest -from google.cloud.retail_v2beta.types.catalog_service import UpdateCatalogRequest -from google.cloud.retail_v2beta.types.catalog_service import UpdateCompletionConfigRequest -from google.cloud.retail_v2beta.types.common import Audience -from google.cloud.retail_v2beta.types.common import ColorInfo -from google.cloud.retail_v2beta.types.common import Condition -from google.cloud.retail_v2beta.types.common import CustomAttribute -from google.cloud.retail_v2beta.types.common import FulfillmentInfo -from google.cloud.retail_v2beta.types.common import Image -from google.cloud.retail_v2beta.types.common import Interval -from google.cloud.retail_v2beta.types.common import LocalInventory -from google.cloud.retail_v2beta.types.common import PriceInfo -from google.cloud.retail_v2beta.types.common import Rating -from google.cloud.retail_v2beta.types.common import Rule -from google.cloud.retail_v2beta.types.common import UserInfo -from google.cloud.retail_v2beta.types.common import AttributeConfigLevel -from google.cloud.retail_v2beta.types.common import SearchSolutionUseCase -from google.cloud.retail_v2beta.types.common import SolutionType -from google.cloud.retail_v2beta.types.completion_service import CompleteQueryRequest -from google.cloud.retail_v2beta.types.completion_service import CompleteQueryResponse -from google.cloud.retail_v2beta.types.control import Control -from google.cloud.retail_v2beta.types.control_service import CreateControlRequest -from google.cloud.retail_v2beta.types.control_service import DeleteControlRequest -from google.cloud.retail_v2beta.types.control_service import GetControlRequest -from google.cloud.retail_v2beta.types.control_service import ListControlsRequest -from google.cloud.retail_v2beta.types.control_service import ListControlsResponse -from google.cloud.retail_v2beta.types.control_service import UpdateControlRequest -from google.cloud.retail_v2beta.types.export_config import ExportErrorsConfig -from google.cloud.retail_v2beta.types.export_config import ExportMetadata -from google.cloud.retail_v2beta.types.export_config import ExportProductsResponse -from google.cloud.retail_v2beta.types.export_config import ExportUserEventsResponse -from google.cloud.retail_v2beta.types.import_config import BigQuerySource -from google.cloud.retail_v2beta.types.import_config import CompletionDataInputConfig -from google.cloud.retail_v2beta.types.import_config import GcsSource -from google.cloud.retail_v2beta.types.import_config import ImportCompletionDataRequest -from google.cloud.retail_v2beta.types.import_config import ImportCompletionDataResponse -from google.cloud.retail_v2beta.types.import_config import ImportErrorsConfig -from google.cloud.retail_v2beta.types.import_config import ImportMetadata -from google.cloud.retail_v2beta.types.import_config import ImportProductsRequest -from google.cloud.retail_v2beta.types.import_config import ImportProductsResponse -from google.cloud.retail_v2beta.types.import_config import ImportUserEventsRequest -from google.cloud.retail_v2beta.types.import_config import ImportUserEventsResponse -from google.cloud.retail_v2beta.types.import_config import ProductInlineSource -from google.cloud.retail_v2beta.types.import_config import ProductInputConfig -from google.cloud.retail_v2beta.types.import_config import UserEventImportSummary -from google.cloud.retail_v2beta.types.import_config import UserEventInlineSource -from google.cloud.retail_v2beta.types.import_config import UserEventInputConfig -from google.cloud.retail_v2beta.types.prediction_service import PredictRequest -from google.cloud.retail_v2beta.types.prediction_service import PredictResponse -from google.cloud.retail_v2beta.types.product import Product -from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesMetadata -from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesRequest -from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesResponse -from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesMetadata -from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesRequest -from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesResponse -from google.cloud.retail_v2beta.types.product_service import CreateProductRequest -from google.cloud.retail_v2beta.types.product_service import DeleteProductRequest -from google.cloud.retail_v2beta.types.product_service import GetProductRequest -from google.cloud.retail_v2beta.types.product_service import ListProductsRequest -from google.cloud.retail_v2beta.types.product_service import ListProductsResponse -from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesMetadata -from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesRequest -from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesResponse -from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesMetadata -from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesRequest -from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesResponse -from google.cloud.retail_v2beta.types.product_service import SetInventoryMetadata -from google.cloud.retail_v2beta.types.product_service import SetInventoryRequest -from google.cloud.retail_v2beta.types.product_service import SetInventoryResponse -from google.cloud.retail_v2beta.types.product_service import UpdateProductRequest -from google.cloud.retail_v2beta.types.promotion import Promotion -from google.cloud.retail_v2beta.types.purge_config import PurgeMetadata -from google.cloud.retail_v2beta.types.purge_config import PurgeUserEventsRequest -from google.cloud.retail_v2beta.types.purge_config import PurgeUserEventsResponse -from google.cloud.retail_v2beta.types.search_service import SearchRequest -from google.cloud.retail_v2beta.types.search_service import SearchResponse -from google.cloud.retail_v2beta.types.serving_config import ServingConfig -from google.cloud.retail_v2beta.types.serving_config_service import AddControlRequest -from google.cloud.retail_v2beta.types.serving_config_service import CreateServingConfigRequest -from google.cloud.retail_v2beta.types.serving_config_service import DeleteServingConfigRequest -from google.cloud.retail_v2beta.types.serving_config_service import GetServingConfigRequest -from google.cloud.retail_v2beta.types.serving_config_service import ListServingConfigsRequest -from google.cloud.retail_v2beta.types.serving_config_service import ListServingConfigsResponse -from google.cloud.retail_v2beta.types.serving_config_service import RemoveControlRequest -from google.cloud.retail_v2beta.types.serving_config_service import UpdateServingConfigRequest -from google.cloud.retail_v2beta.types.user_event import CompletionDetail -from google.cloud.retail_v2beta.types.user_event import ProductDetail -from google.cloud.retail_v2beta.types.user_event import PurchaseTransaction -from google.cloud.retail_v2beta.types.user_event import UserEvent -from google.cloud.retail_v2beta.types.user_event_service import CollectUserEventRequest -from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsMetadata -from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsRequest -from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsResponse -from google.cloud.retail_v2beta.types.user_event_service import WriteUserEventRequest - -__all__ = ('CatalogServiceClient', - 'CatalogServiceAsyncClient', - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', - 'ControlServiceClient', - 'ControlServiceAsyncClient', - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', - 'ProductServiceClient', - 'ProductServiceAsyncClient', - 'SearchServiceClient', - 'SearchServiceAsyncClient', - 'ServingConfigServiceClient', - 'ServingConfigServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'AttributesConfig', - 'Catalog', - 'CatalogAttribute', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'ProductLevelConfig', - 'AddCatalogAttributeRequest', - 'GetAttributesConfigRequest', - 'GetCompletionConfigRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - 'SetDefaultBranchRequest', - 'UpdateAttributesConfigRequest', - 'UpdateCatalogRequest', - 'UpdateCompletionConfigRequest', - 'Audience', - 'ColorInfo', - 'Condition', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'Rule', - 'UserInfo', - 'AttributeConfigLevel', - 'SearchSolutionUseCase', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Control', - 'CreateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - 'UpdateControlRequest', - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'ServingConfig', - 'AddControlRequest', - 'CreateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'RemoveControlRequest', - 'UpdateServingConfigRequest', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail/py.typed b/owl-bot-staging/v2beta/google/cloud/retail/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py deleted file mode 100644 index 3ad83ab4..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py +++ /dev/null @@ -1,276 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.catalog_service import CatalogServiceClient -from .services.catalog_service import CatalogServiceAsyncClient -from .services.completion_service import CompletionServiceClient -from .services.completion_service import CompletionServiceAsyncClient -from .services.control_service import ControlServiceClient -from .services.control_service import ControlServiceAsyncClient -from .services.prediction_service import PredictionServiceClient -from .services.prediction_service import PredictionServiceAsyncClient -from .services.product_service import ProductServiceClient -from .services.product_service import ProductServiceAsyncClient -from .services.search_service import SearchServiceClient -from .services.search_service import SearchServiceAsyncClient -from .services.serving_config_service import ServingConfigServiceClient -from .services.serving_config_service import ServingConfigServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.catalog import AttributesConfig -from .types.catalog import Catalog -from .types.catalog import CatalogAttribute -from .types.catalog import CompletionConfig -from .types.catalog import MerchantCenterLink -from .types.catalog import MerchantCenterLinkingConfig -from .types.catalog import ProductLevelConfig -from .types.catalog_service import AddCatalogAttributeRequest -from .types.catalog_service import GetAttributesConfigRequest -from .types.catalog_service import GetCompletionConfigRequest -from .types.catalog_service import GetDefaultBranchRequest -from .types.catalog_service import GetDefaultBranchResponse -from .types.catalog_service import ListCatalogsRequest -from .types.catalog_service import ListCatalogsResponse -from .types.catalog_service import RemoveCatalogAttributeRequest -from .types.catalog_service import ReplaceCatalogAttributeRequest -from .types.catalog_service import SetDefaultBranchRequest -from .types.catalog_service import UpdateAttributesConfigRequest -from .types.catalog_service import UpdateCatalogRequest -from .types.catalog_service import UpdateCompletionConfigRequest -from .types.common import Audience -from .types.common import ColorInfo -from .types.common import Condition -from .types.common import CustomAttribute -from .types.common import FulfillmentInfo -from .types.common import Image -from .types.common import Interval -from .types.common import LocalInventory -from .types.common import PriceInfo -from .types.common import Rating -from .types.common import Rule -from .types.common import UserInfo -from .types.common import AttributeConfigLevel -from .types.common import SearchSolutionUseCase -from .types.common import SolutionType -from .types.completion_service import CompleteQueryRequest -from .types.completion_service import CompleteQueryResponse -from .types.control import Control -from .types.control_service import CreateControlRequest -from .types.control_service import DeleteControlRequest -from .types.control_service import GetControlRequest -from .types.control_service import ListControlsRequest -from .types.control_service import ListControlsResponse -from .types.control_service import UpdateControlRequest -from .types.export_config import ExportErrorsConfig -from .types.export_config import ExportMetadata -from .types.export_config import ExportProductsResponse -from .types.export_config import ExportUserEventsResponse -from .types.import_config import BigQuerySource -from .types.import_config import CompletionDataInputConfig -from .types.import_config import GcsSource -from .types.import_config import ImportCompletionDataRequest -from .types.import_config import ImportCompletionDataResponse -from .types.import_config import ImportErrorsConfig -from .types.import_config import ImportMetadata -from .types.import_config import ImportProductsRequest -from .types.import_config import ImportProductsResponse -from .types.import_config import ImportUserEventsRequest -from .types.import_config import ImportUserEventsResponse -from .types.import_config import ProductInlineSource -from .types.import_config import ProductInputConfig -from .types.import_config import UserEventImportSummary -from .types.import_config import UserEventInlineSource -from .types.import_config import UserEventInputConfig -from .types.prediction_service import PredictRequest -from .types.prediction_service import PredictResponse -from .types.product import Product -from .types.product_service import AddFulfillmentPlacesMetadata -from .types.product_service import AddFulfillmentPlacesRequest -from .types.product_service import AddFulfillmentPlacesResponse -from .types.product_service import AddLocalInventoriesMetadata -from .types.product_service import AddLocalInventoriesRequest -from .types.product_service import AddLocalInventoriesResponse -from .types.product_service import CreateProductRequest -from .types.product_service import DeleteProductRequest -from .types.product_service import GetProductRequest -from .types.product_service import ListProductsRequest -from .types.product_service import ListProductsResponse -from .types.product_service import RemoveFulfillmentPlacesMetadata -from .types.product_service import RemoveFulfillmentPlacesRequest -from .types.product_service import RemoveFulfillmentPlacesResponse -from .types.product_service import RemoveLocalInventoriesMetadata -from .types.product_service import RemoveLocalInventoriesRequest -from .types.product_service import RemoveLocalInventoriesResponse -from .types.product_service import SetInventoryMetadata -from .types.product_service import SetInventoryRequest -from .types.product_service import SetInventoryResponse -from .types.product_service import UpdateProductRequest -from .types.promotion import Promotion -from .types.purge_config import PurgeMetadata -from .types.purge_config import PurgeUserEventsRequest -from .types.purge_config import PurgeUserEventsResponse -from .types.search_service import SearchRequest -from .types.search_service import SearchResponse -from .types.serving_config import ServingConfig -from .types.serving_config_service import AddControlRequest -from .types.serving_config_service import CreateServingConfigRequest -from .types.serving_config_service import DeleteServingConfigRequest -from .types.serving_config_service import GetServingConfigRequest -from .types.serving_config_service import ListServingConfigsRequest -from .types.serving_config_service import ListServingConfigsResponse -from .types.serving_config_service import RemoveControlRequest -from .types.serving_config_service import UpdateServingConfigRequest -from .types.user_event import CompletionDetail -from .types.user_event import ProductDetail -from .types.user_event import PurchaseTransaction -from .types.user_event import UserEvent -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import RejoinUserEventsMetadata -from .types.user_event_service import RejoinUserEventsRequest -from .types.user_event_service import RejoinUserEventsResponse -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CatalogServiceAsyncClient', - 'CompletionServiceAsyncClient', - 'ControlServiceAsyncClient', - 'PredictionServiceAsyncClient', - 'ProductServiceAsyncClient', - 'SearchServiceAsyncClient', - 'ServingConfigServiceAsyncClient', - 'UserEventServiceAsyncClient', -'AddCatalogAttributeRequest', -'AddControlRequest', -'AddFulfillmentPlacesMetadata', -'AddFulfillmentPlacesRequest', -'AddFulfillmentPlacesResponse', -'AddLocalInventoriesMetadata', -'AddLocalInventoriesRequest', -'AddLocalInventoriesResponse', -'AttributeConfigLevel', -'AttributesConfig', -'Audience', -'BigQuerySource', -'Catalog', -'CatalogAttribute', -'CatalogServiceClient', -'CollectUserEventRequest', -'ColorInfo', -'CompleteQueryRequest', -'CompleteQueryResponse', -'CompletionConfig', -'CompletionDataInputConfig', -'CompletionDetail', -'CompletionServiceClient', -'Condition', -'Control', -'ControlServiceClient', -'CreateControlRequest', -'CreateProductRequest', -'CreateServingConfigRequest', -'CustomAttribute', -'DeleteControlRequest', -'DeleteProductRequest', -'DeleteServingConfigRequest', -'ExportErrorsConfig', -'ExportMetadata', -'ExportProductsResponse', -'ExportUserEventsResponse', -'FulfillmentInfo', -'GcsSource', -'GetAttributesConfigRequest', -'GetCompletionConfigRequest', -'GetControlRequest', -'GetDefaultBranchRequest', -'GetDefaultBranchResponse', -'GetProductRequest', -'GetServingConfigRequest', -'Image', -'ImportCompletionDataRequest', -'ImportCompletionDataResponse', -'ImportErrorsConfig', -'ImportMetadata', -'ImportProductsRequest', -'ImportProductsResponse', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'Interval', -'ListCatalogsRequest', -'ListCatalogsResponse', -'ListControlsRequest', -'ListControlsResponse', -'ListProductsRequest', -'ListProductsResponse', -'ListServingConfigsRequest', -'ListServingConfigsResponse', -'LocalInventory', -'MerchantCenterLink', -'MerchantCenterLinkingConfig', -'PredictRequest', -'PredictResponse', -'PredictionServiceClient', -'PriceInfo', -'Product', -'ProductDetail', -'ProductInlineSource', -'ProductInputConfig', -'ProductLevelConfig', -'ProductServiceClient', -'Promotion', -'PurchaseTransaction', -'PurgeMetadata', -'PurgeUserEventsRequest', -'PurgeUserEventsResponse', -'Rating', -'RejoinUserEventsMetadata', -'RejoinUserEventsRequest', -'RejoinUserEventsResponse', -'RemoveCatalogAttributeRequest', -'RemoveControlRequest', -'RemoveFulfillmentPlacesMetadata', -'RemoveFulfillmentPlacesRequest', -'RemoveFulfillmentPlacesResponse', -'RemoveLocalInventoriesMetadata', -'RemoveLocalInventoriesRequest', -'RemoveLocalInventoriesResponse', -'ReplaceCatalogAttributeRequest', -'Rule', -'SearchRequest', -'SearchResponse', -'SearchServiceClient', -'SearchSolutionUseCase', -'ServingConfig', -'ServingConfigServiceClient', -'SetDefaultBranchRequest', -'SetInventoryMetadata', -'SetInventoryRequest', -'SetInventoryResponse', -'SolutionType', -'UpdateAttributesConfigRequest', -'UpdateCatalogRequest', -'UpdateCompletionConfigRequest', -'UpdateControlRequest', -'UpdateProductRequest', -'UpdateServingConfigRequest', -'UserEvent', -'UserEventImportSummary', -'UserEventInlineSource', -'UserEventInputConfig', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json deleted file mode 100644 index bf3205b9..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json +++ /dev/null @@ -1,551 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.retail_v2beta", - "protoPackage": "google.cloud.retail.v2beta", - "schema": "1.0", - "services": { - "CatalogService": { - "clients": { - "grpc": { - "libraryClient": "CatalogServiceClient", - "rpcs": { - "AddCatalogAttribute": { - "methods": [ - "add_catalog_attribute" - ] - }, - "GetAttributesConfig": { - "methods": [ - "get_attributes_config" - ] - }, - "GetCompletionConfig": { - "methods": [ - "get_completion_config" - ] - }, - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "RemoveCatalogAttribute": { - "methods": [ - "remove_catalog_attribute" - ] - }, - "ReplaceCatalogAttribute": { - "methods": [ - "replace_catalog_attribute" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateAttributesConfig": { - "methods": [ - "update_attributes_config" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - }, - "UpdateCompletionConfig": { - "methods": [ - "update_completion_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CatalogServiceAsyncClient", - "rpcs": { - "AddCatalogAttribute": { - "methods": [ - "add_catalog_attribute" - ] - }, - "GetAttributesConfig": { - "methods": [ - "get_attributes_config" - ] - }, - "GetCompletionConfig": { - "methods": [ - "get_completion_config" - ] - }, - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "RemoveCatalogAttribute": { - "methods": [ - "remove_catalog_attribute" - ] - }, - "ReplaceCatalogAttribute": { - "methods": [ - "replace_catalog_attribute" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateAttributesConfig": { - "methods": [ - "update_attributes_config" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - }, - "UpdateCompletionConfig": { - "methods": [ - "update_completion_config" - ] - } - } - } - } - }, - "CompletionService": { - "clients": { - "grpc": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CompletionServiceAsyncClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - } - } - }, - "ControlService": { - "clients": { - "grpc": { - "libraryClient": "ControlServiceClient", - "rpcs": { - "CreateControl": { - "methods": [ - "create_control" - ] - }, - "DeleteControl": { - "methods": [ - "delete_control" - ] - }, - "GetControl": { - "methods": [ - "get_control" - ] - }, - "ListControls": { - "methods": [ - "list_controls" - ] - }, - "UpdateControl": { - "methods": [ - "update_control" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ControlServiceAsyncClient", - "rpcs": { - "CreateControl": { - "methods": [ - "create_control" - ] - }, - "DeleteControl": { - "methods": [ - "delete_control" - ] - }, - "GetControl": { - "methods": [ - "get_control" - ] - }, - "ListControls": { - "methods": [ - "list_controls" - ] - }, - "UpdateControl": { - "methods": [ - "update_control" - ] - } - } - } - } - }, - "PredictionService": { - "clients": { - "grpc": { - "libraryClient": "PredictionServiceClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PredictionServiceAsyncClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - } - } - }, - "ProductService": { - "clients": { - "grpc": { - "libraryClient": "ProductServiceClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProductServiceAsyncClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - } - } - }, - "SearchService": { - "clients": { - "grpc": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SearchServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - }, - "ServingConfigService": { - "clients": { - "grpc": { - "libraryClient": "ServingConfigServiceClient", - "rpcs": { - "AddControl": { - "methods": [ - "add_control" - ] - }, - "CreateServingConfig": { - "methods": [ - "create_serving_config" - ] - }, - "DeleteServingConfig": { - "methods": [ - "delete_serving_config" - ] - }, - "GetServingConfig": { - "methods": [ - "get_serving_config" - ] - }, - "ListServingConfigs": { - "methods": [ - "list_serving_configs" - ] - }, - "RemoveControl": { - "methods": [ - "remove_control" - ] - }, - "UpdateServingConfig": { - "methods": [ - "update_serving_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ServingConfigServiceAsyncClient", - "rpcs": { - "AddControl": { - "methods": [ - "add_control" - ] - }, - "CreateServingConfig": { - "methods": [ - "create_serving_config" - ] - }, - "DeleteServingConfig": { - "methods": [ - "delete_serving_config" - ] - }, - "GetServingConfig": { - "methods": [ - "get_serving_config" - ] - }, - "ListServingConfigs": { - "methods": [ - "list_serving_configs" - ] - }, - "RemoveControl": { - "methods": [ - "remove_control" - ] - }, - "UpdateServingConfig": { - "methods": [ - "update_serving_config" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py deleted file mode 100644 index d276b897..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CatalogServiceClient -from .async_client import CatalogServiceAsyncClient - -__all__ = ( - 'CatalogServiceClient', - 'CatalogServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py deleted file mode 100644 index dfff033b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py +++ /dev/null @@ -1,1350 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.catalog_service import pagers -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport -from .client import CatalogServiceClient - - -class CatalogServiceAsyncClient: - """Service for managing catalog configuration.""" - - _client: CatalogServiceClient - - DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT - - attributes_config_path = staticmethod(CatalogServiceClient.attributes_config_path) - parse_attributes_config_path = staticmethod(CatalogServiceClient.parse_attributes_config_path) - branch_path = staticmethod(CatalogServiceClient.branch_path) - parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) - catalog_path = staticmethod(CatalogServiceClient.catalog_path) - parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) - completion_config_path = staticmethod(CatalogServiceClient.completion_config_path) - parse_completion_config_path = staticmethod(CatalogServiceClient.parse_completion_config_path) - common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CatalogServiceClient.common_project_path) - parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) - common_location_path = staticmethod(CatalogServiceClient.common_location_path) - parse_common_location_path = staticmethod(CatalogServiceClient.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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CatalogServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsAsyncPager: - r"""Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_list_catalogs(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - parent (:class:`str`): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2beta.Catalog]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.retail_v2beta.services.catalog_service.pagers.ListCatalogsAsyncPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.ListCatalogsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_catalogs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCatalogsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_catalog(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2beta.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2beta.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] - method. - catalog (:class:`google.cloud.retail_v2beta.types.Catalog`): - Required. The - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2beta.Catalog], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Catalog][google.cloud.retail.v2beta.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCatalogRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_catalog, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_set_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (:class:`str`): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.SetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (:class:`str`): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # 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_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_completion_config(self, - request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Gets a - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] - method. - name (:class:`str`): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - - 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.retail_v2beta.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetCompletionConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_completion_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_completion_config(self, - request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, - *, - completion_config: catalog.CompletionConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Updates the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - completion_config = retail_v2beta.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2beta.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = await client.update_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] - method. - completion_config (:class:`google.cloud.retail_v2beta.types.CompletionConfig`): - Required. The - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``completion_config`` 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 - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([completion_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCompletionConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if completion_config is not None: - request.completion_config = completion_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_completion_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("completion_config.name", request.completion_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_attributes_config(self, - request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Gets an - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] - method. - name (:class:`str`): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - - 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.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetAttributesConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_attributes_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_attributes_config(self, - request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, - *, - attributes_config: catalog.AttributesConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Updates the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - attributes_config = retail_v2beta.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2beta.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = await client.update_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] - method. - attributes_config (:class:`google.cloud.retail_v2beta.types.AttributesConfig`): - Required. The - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. - - This corresponds to the ``attributes_config`` 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 - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([attributes_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateAttributesConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attributes_config is not None: - request.attributes_config = attributes_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_attributes_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config.name", request.attributes_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def add_catalog_attribute(self, - request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Adds the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_add_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.AddCatalogAttributeRequest(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.add_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def remove_catalog_attribute(self, - request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Removes the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = await client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.RemoveCatalogAttributeRequest(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.remove_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def replace_catalog_attribute(self, - request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Replaces the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.ReplaceCatalogAttributeRequest(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.replace_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py deleted file mode 100644 index c95200de..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py +++ /dev/null @@ -1,1580 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.catalog_service import pagers -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CatalogServiceGrpcTransport -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -class CatalogServiceClientMeta(type): - """Metaclass for the CatalogService 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[CatalogServiceTransport]] - _transport_registry["grpc"] = CatalogServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CatalogServiceTransport]: - """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): - """Service for managing catalog configuration.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CatalogServiceClient: 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: - CatalogServiceClient: 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) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def attributes_config_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified attributes_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_attributes_config_path(path: str) -> Dict[str,str]: - """Parses a attributes_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/attributesConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def completion_config_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified completion_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_completion_config_path(path: str) -> Dict[str,str]: - """Parses a completion_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/completionConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CatalogServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CatalogServiceTransport): - # transport is a CatalogServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsPager: - r"""Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_list_catalogs(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2beta.Catalog]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.retail_v2beta.services.catalog_service.pagers.ListCatalogsPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ListCatalogsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ListCatalogsRequest): - request = catalog_service.ListCatalogsRequest(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_catalogs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCatalogsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_catalog(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2beta.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2beta.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] - method. - catalog (google.cloud.retail_v2beta.types.Catalog): - Required. The - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2beta.Catalog], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Catalog][google.cloud.retail.v2beta.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCatalogRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCatalogRequest): - request = catalog_service.UpdateCatalogRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - 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_catalog] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_set_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.SetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.SetDefaultBranchRequest): - request = catalog_service.SetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetDefaultBranchRequest): - request = catalog_service.GetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_completion_config(self, - request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Gets a - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] - method. - name (str): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - - 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.retail_v2beta.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetCompletionConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetCompletionConfigRequest): - request = catalog_service.GetCompletionConfigRequest(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_completion_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_completion_config(self, - request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, - *, - completion_config: catalog.CompletionConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Updates the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - completion_config = retail_v2beta.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2beta.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = client.update_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] - method. - completion_config (google.cloud.retail_v2beta.types.CompletionConfig): - Required. The - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``completion_config`` 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 - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([completion_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCompletionConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCompletionConfigRequest): - request = catalog_service.UpdateCompletionConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if completion_config is not None: - request.completion_config = completion_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_completion_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("completion_config.name", request.completion_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_attributes_config(self, - request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Gets an - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] - method. - name (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - - 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.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetAttributesConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetAttributesConfigRequest): - request = catalog_service.GetAttributesConfigRequest(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_attributes_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_attributes_config(self, - request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, - *, - attributes_config: catalog.AttributesConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Updates the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - attributes_config = retail_v2beta.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2beta.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = client.update_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] - method. - attributes_config (google.cloud.retail_v2beta.types.AttributesConfig): - Required. The - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. - - This corresponds to the ``attributes_config`` 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 - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([attributes_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateAttributesConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateAttributesConfigRequest): - request = catalog_service.UpdateAttributesConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attributes_config is not None: - request.attributes_config = attributes_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_attributes_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config.name", request.attributes_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def add_catalog_attribute(self, - request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Adds the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_add_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.AddCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.AddCatalogAttributeRequest): - request = catalog_service.AddCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def remove_catalog_attribute(self, - request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Removes the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.RemoveCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.RemoveCatalogAttributeRequest): - request = catalog_service.RemoveCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def replace_catalog_attribute(self, - request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Replaces the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ReplaceCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ReplaceCatalogAttributeRequest): - request = catalog_service.ReplaceCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.replace_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py deleted file mode 100644 index 0ca25546..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog_service - - -class ListCatalogsPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` - 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[..., catalog_service.ListCatalogsResponse], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2beta.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - for page in self.pages: - yield from page.catalogs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCatalogsAsyncPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` - 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[catalog_service.ListCatalogsResponse]], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2beta.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - async def async_generator(): - async for page in self.pages: - for response in page.catalogs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py deleted file mode 100644 index 0cffa336..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CatalogServiceTransport -from .grpc import CatalogServiceGrpcTransport -from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] -_transport_registry['grpc'] = CatalogServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport - -__all__ = ( - 'CatalogServiceTransport', - 'CatalogServiceGrpcTransport', - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py deleted file mode 100644 index 90964f49..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py +++ /dev/null @@ -1,297 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CatalogServiceTransport(abc.ABC): - """Abstract transport class for CatalogService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_catalogs: gapic_v1.method.wrap_method( - self.list_catalogs, - default_timeout=None, - client_info=client_info, - ), - self.update_catalog: gapic_v1.method.wrap_method( - self.update_catalog, - default_timeout=None, - client_info=client_info, - ), - self.set_default_branch: gapic_v1.method.wrap_method( - self.set_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_default_branch: gapic_v1.method.wrap_method( - self.get_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_completion_config: gapic_v1.method.wrap_method( - self.get_completion_config, - default_timeout=None, - client_info=client_info, - ), - self.update_completion_config: gapic_v1.method.wrap_method( - self.update_completion_config, - default_timeout=None, - client_info=client_info, - ), - self.get_attributes_config: gapic_v1.method.wrap_method( - self.get_attributes_config, - default_timeout=None, - client_info=client_info, - ), - self.update_attributes_config: gapic_v1.method.wrap_method( - self.update_attributes_config, - default_timeout=None, - client_info=client_info, - ), - self.add_catalog_attribute: gapic_v1.method.wrap_method( - self.add_catalog_attribute, - default_timeout=None, - client_info=client_info, - ), - self.remove_catalog_attribute: gapic_v1.method.wrap_method( - self.remove_catalog_attribute, - default_timeout=None, - client_info=client_info, - ), - self.replace_catalog_attribute: gapic_v1.method.wrap_method( - self.replace_catalog_attribute, - 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Union[ - catalog_service.ListCatalogsResponse, - Awaitable[catalog_service.ListCatalogsResponse] - ]]: - raise NotImplementedError() - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Union[ - gcr_catalog.Catalog, - Awaitable[gcr_catalog.Catalog] - ]]: - raise NotImplementedError() - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Union[ - catalog_service.GetDefaultBranchResponse, - Awaitable[catalog_service.GetDefaultBranchResponse] - ]]: - raise NotImplementedError() - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - Union[ - catalog.CompletionConfig, - Awaitable[catalog.CompletionConfig] - ]]: - raise NotImplementedError() - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - Union[ - catalog.CompletionConfig, - Awaitable[catalog.CompletionConfig] - ]]: - raise NotImplementedError() - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CatalogServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py deleted file mode 100644 index 9ae369d1..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py +++ /dev/null @@ -1,600 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO - - -class CatalogServiceGrpcTransport(CatalogServiceTransport): - """gRPC backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - catalog_service.ListCatalogsResponse]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - ~.ListCatalogsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - gcr_catalog.Catalog]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - ~.Catalog]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - empty_pb2.Empty]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - ~.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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - catalog_service.GetDefaultBranchResponse]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - ~.GetDefaultBranchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - catalog.CompletionConfig]: - r"""Return a callable for the get completion config method over gRPC. - - Gets a - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. - - Returns: - Callable[[~.GetCompletionConfigRequest], - ~.CompletionConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetCompletionConfig', - request_serializer=catalog_service.GetCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['get_completion_config'] - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - catalog.CompletionConfig]: - r"""Return a callable for the update completion config method over gRPC. - - Updates the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. - - Returns: - Callable[[~.UpdateCompletionConfigRequest], - ~.CompletionConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateCompletionConfig', - request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['update_completion_config'] - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - catalog.AttributesConfig]: - r"""Return a callable for the get attributes config method over gRPC. - - Gets an - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - Returns: - Callable[[~.GetAttributesConfigRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetAttributesConfig', - request_serializer=catalog_service.GetAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['get_attributes_config'] - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - catalog.AttributesConfig]: - r"""Return a callable for the update attributes config method over gRPC. - - Updates the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - Returns: - Callable[[~.UpdateAttributesConfigRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateAttributesConfig', - request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['update_attributes_config'] - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the add catalog attribute method over gRPC. - - Adds the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.AddCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_catalog_attribute' not in self._stubs: - self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/AddCatalogAttribute', - request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['add_catalog_attribute'] - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the remove catalog attribute method over gRPC. - - Removes the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.RemoveCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_catalog_attribute' not in self._stubs: - self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/RemoveCatalogAttribute', - request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['remove_catalog_attribute'] - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the replace catalog attribute method over gRPC. - - Replaces the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.ReplaceCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_catalog_attribute' not in self._stubs: - self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/ReplaceCatalogAttribute', - request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['replace_catalog_attribute'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CatalogServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py deleted file mode 100644 index 37eaea4b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,599 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CatalogServiceGrpcTransport - - -class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): - """gRPC AsyncIO backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Awaitable[catalog_service.ListCatalogsResponse]]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - Awaitable[~.ListCatalogsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Awaitable[gcr_catalog.Catalog]]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - Awaitable[~.Catalog]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - 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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Awaitable[catalog_service.GetDefaultBranchResponse]]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - Awaitable[~.GetDefaultBranchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - Awaitable[catalog.CompletionConfig]]: - r"""Return a callable for the get completion config method over gRPC. - - Gets a - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. - - Returns: - Callable[[~.GetCompletionConfigRequest], - Awaitable[~.CompletionConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetCompletionConfig', - request_serializer=catalog_service.GetCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['get_completion_config'] - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - Awaitable[catalog.CompletionConfig]]: - r"""Return a callable for the update completion config method over gRPC. - - Updates the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. - - Returns: - Callable[[~.UpdateCompletionConfigRequest], - Awaitable[~.CompletionConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateCompletionConfig', - request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['update_completion_config'] - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the get attributes config method over gRPC. - - Gets an - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - Returns: - Callable[[~.GetAttributesConfigRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetAttributesConfig', - request_serializer=catalog_service.GetAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['get_attributes_config'] - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the update attributes config method over gRPC. - - Updates the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - Returns: - Callable[[~.UpdateAttributesConfigRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateAttributesConfig', - request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['update_attributes_config'] - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the add catalog attribute method over gRPC. - - Adds the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.AddCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_catalog_attribute' not in self._stubs: - self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/AddCatalogAttribute', - request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['add_catalog_attribute'] - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the remove catalog attribute method over gRPC. - - Removes the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.RemoveCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_catalog_attribute' not in self._stubs: - self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/RemoveCatalogAttribute', - request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['remove_catalog_attribute'] - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the replace catalog attribute method over gRPC. - - Replaces the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.ReplaceCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_catalog_attribute' not in self._stubs: - self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/ReplaceCatalogAttribute', - request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['replace_catalog_attribute'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py deleted file mode 100644 index b8af95bd..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CompletionServiceClient -from .async_client import CompletionServiceAsyncClient - -__all__ = ( - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py deleted file mode 100644 index 66c91320..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py +++ /dev/null @@ -1,391 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .client import CompletionServiceClient - - -class CompletionServiceAsyncClient: - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: CompletionServiceClient - - DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(CompletionServiceClient.catalog_path) - parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) - common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CompletionServiceClient.common_project_path) - parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) - common_location_path = staticmethod(CompletionServiceClient.common_location_path) - parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CompletionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_complete_query(): - # Create a client - client = retail_v2beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.complete_query, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_import_completion_data(): - # Create a client - client = retail_v2beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2beta.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. - 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. - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_completion_data, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py deleted file mode 100644 index 5766b6b2..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py +++ /dev/null @@ -1,593 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CompletionServiceGrpcTransport -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -class CompletionServiceClientMeta(type): - """Metaclass for the CompletionService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] - _transport_registry["grpc"] = CompletionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CompletionServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class CompletionServiceClient(metaclass=CompletionServiceClientMeta): - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CompletionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CompletionServiceTransport): - # transport is a CompletionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_complete_query(): - # Create a client - client = retail_v2beta.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a completion_service.CompleteQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, completion_service.CompleteQueryRequest): - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_import_completion_data(): - # Create a client - client = retail_v2beta.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2beta.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. - 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. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportCompletionDataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportCompletionDataRequest): - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_completion_data] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py deleted file mode 100644 index a0c9542f..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CompletionServiceTransport -from .grpc import CompletionServiceGrpcTransport -from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] -_transport_registry['grpc'] = CompletionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport - -__all__ = ( - 'CompletionServiceTransport', - 'CompletionServiceGrpcTransport', - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py deleted file mode 100644 index 6a5d8425..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py +++ /dev/null @@ -1,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CompletionServiceTransport(abc.ABC): - """Abstract transport class for CompletionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.complete_query: gapic_v1.method.wrap_method( - self.complete_query, - default_timeout=None, - client_info=client_info, - ), - self.import_completion_data: gapic_v1.method.wrap_method( - self.import_completion_data, - 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Union[ - completion_service.CompleteQueryResponse, - Awaitable[completion_service.CompleteQueryResponse] - ]]: - raise NotImplementedError() - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CompletionServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py deleted file mode 100644 index d3ee0929..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py +++ /dev/null @@ -1,325 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO - - -class CompletionServiceGrpcTransport(CompletionServiceTransport): - """gRPC backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - ~.CompleteQueryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - operations_pb2.Operation]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CompletionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py deleted file mode 100644 index 56463003..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,324 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CompletionServiceGrpcTransport - - -class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): - """gRPC AsyncIO backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Awaitable[completion_service.CompleteQueryResponse]]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - Awaitable[~.CompleteQueryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - 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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py deleted file mode 100644 index e9a7be2f..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ControlServiceClient -from .async_client import ControlServiceAsyncClient - -__all__ = ( - 'ControlServiceClient', - 'ControlServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py deleted file mode 100644 index 5d3cfeb7..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py +++ /dev/null @@ -1,742 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.control_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.cloud.retail_v2beta.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport -from .client import ControlServiceClient - - -class ControlServiceAsyncClient: - """Service for modifying Control.""" - - _client: ControlServiceClient - - DEFAULT_ENDPOINT = ControlServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ControlServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(ControlServiceClient.catalog_path) - parse_catalog_path = staticmethod(ControlServiceClient.parse_catalog_path) - control_path = staticmethod(ControlServiceClient.control_path) - parse_control_path = staticmethod(ControlServiceClient.parse_control_path) - common_billing_account_path = staticmethod(ControlServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ControlServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ControlServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ControlServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ControlServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ControlServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ControlServiceClient.common_project_path) - parse_common_project_path = staticmethod(ControlServiceClient.parse_common_project_path) - common_location_path = staticmethod(ControlServiceClient.common_location_path) - parse_common_location_path = staticmethod(ControlServiceClient.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: - ControlServiceAsyncClient: The constructed client. - """ - return ControlServiceClient.from_service_account_info.__func__(ControlServiceAsyncClient, 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: - ControlServiceAsyncClient: The constructed client. - """ - return ControlServiceClient.from_service_account_file.__func__(ControlServiceAsyncClient, 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 variabel 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 ControlServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ControlServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ControlServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ControlServiceClient).get_transport_class, type(ControlServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ControlServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the control service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ControlServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ControlServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_control(self, - request: Union[control_service.CreateControlRequest, dict] = None, - *, - parent: str = None, - control: gcr_control.Control = None, - control_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Creates a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_create_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = await client.create_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateControlRequest, dict]): - The request object. Request for CreateControl method. - parent (:class:`str`): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control (:class:`google.cloud.retail_v2beta.types.Control`): - Required. The Control to create. - This corresponds to the ``control`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control_id (:class:`str`): - Required. The ID to use for the Control, which will - become the final component of the Control's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``control_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.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, control, control_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.CreateControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if control is not None: - request.control = control - if control_id is not None: - request.control_id = control_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_control(self, - request: Union[control_service.DeleteControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_delete_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteControlRequest( - name="name_value", - ) - - # Make the request - await client.delete_control(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteControlRequest, dict]): - The request object. Request for DeleteControl method. - name (:class:`str`): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.DeleteControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_control(self, - request: Union[control_service.UpdateControlRequest, dict] = None, - *, - control: gcr_control.Control = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Updates a Control. - - [Control][google.cloud.retail.v2beta.Control] cannot be set to a - different oneof field, if so an INVALID_ARGUMENT is returned. If - the [Control][google.cloud.retail.v2beta.Control] to delete does - not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateControlRequest( - control=control, - ) - - # Make the request - response = await client.update_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateControlRequest, dict]): - The request object. Request for UpdateControl method. - control (:class:`google.cloud.retail_v2beta.types.Control`): - Required. The Control to update. - This corresponds to the ``control`` 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 - [Control][google.cloud.retail.v2beta.Control] to update. - The following are NOT supported: - - - [Control.name][google.cloud.retail.v2beta.Control.name] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([control, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.UpdateControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if control is not None: - request.control = control - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("control.name", request.control.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_control(self, - request: Union[control_service.GetControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> control.Control: - r"""Gets a Control. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetControlRequest( - name="name_value", - ) - - # Make the request - response = await client.get_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetControlRequest, dict]): - The request object. Request for GetControl method. - name (:class:`str`): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.GetControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_controls(self, - request: Union[control_service.ListControlsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListControlsAsyncPager: - r"""Lists all Controls linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_list_controls(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListControlsRequest, dict]): - The request object. Request for ListControls method. - parent (:class:`str`): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.control_service.pagers.ListControlsAsyncPager: - Response for ListControls method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.ListControlsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_controls, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListControlsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ControlServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py deleted file mode 100644 index fbad615b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py +++ /dev/null @@ -1,951 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.control_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.cloud.retail_v2beta.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ControlServiceGrpcTransport -from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport - - -class ControlServiceClientMeta(type): - """Metaclass for the ControlService 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[ControlServiceTransport]] - _transport_registry["grpc"] = ControlServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ControlServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ControlServiceTransport]: - """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 ControlServiceClient(metaclass=ControlServiceClientMeta): - """Service for modifying Control.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ControlServiceClient: 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: - ControlServiceClient: 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) -> ControlServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ControlServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def control_path(project: str,location: str,catalog: str,control: str,) -> str: - """Returns a fully-qualified control string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) - - @staticmethod - def parse_control_path(path: str) -> Dict[str,str]: - """Parses a control path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/controls/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ControlServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the control service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ControlServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ControlServiceTransport): - # transport is a ControlServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_control(self, - request: Union[control_service.CreateControlRequest, dict] = None, - *, - parent: str = None, - control: gcr_control.Control = None, - control_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Creates a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_create_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = client.create_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateControlRequest, dict]): - The request object. Request for CreateControl method. - parent (str): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control (google.cloud.retail_v2beta.types.Control): - Required. The Control to create. - This corresponds to the ``control`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control_id (str): - Required. The ID to use for the Control, which will - become the final component of the Control's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``control_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.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, control, control_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.CreateControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.CreateControlRequest): - request = control_service.CreateControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if control is not None: - request.control = control - if control_id is not None: - request.control_id = control_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_control(self, - request: Union[control_service.DeleteControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_delete_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteControlRequest( - name="name_value", - ) - - # Make the request - client.delete_control(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteControlRequest, dict]): - The request object. Request for DeleteControl method. - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.DeleteControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.DeleteControlRequest): - request = control_service.DeleteControlRequest(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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_control(self, - request: Union[control_service.UpdateControlRequest, dict] = None, - *, - control: gcr_control.Control = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Updates a Control. - - [Control][google.cloud.retail.v2beta.Control] cannot be set to a - different oneof field, if so an INVALID_ARGUMENT is returned. If - the [Control][google.cloud.retail.v2beta.Control] to delete does - not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateControlRequest( - control=control, - ) - - # Make the request - response = client.update_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateControlRequest, dict]): - The request object. Request for UpdateControl method. - control (google.cloud.retail_v2beta.types.Control): - Required. The Control to update. - This corresponds to the ``control`` 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 - [Control][google.cloud.retail.v2beta.Control] to update. - The following are NOT supported: - - - [Control.name][google.cloud.retail.v2beta.Control.name] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([control, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.UpdateControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.UpdateControlRequest): - request = control_service.UpdateControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if control is not None: - request.control = control - 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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("control.name", request.control.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_control(self, - request: Union[control_service.GetControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> control.Control: - r"""Gets a Control. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetControlRequest( - name="name_value", - ) - - # Make the request - response = client.get_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetControlRequest, dict]): - The request object. Request for GetControl method. - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.GetControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.GetControlRequest): - request = control_service.GetControlRequest(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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_controls(self, - request: Union[control_service.ListControlsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListControlsPager: - r"""Lists all Controls linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_list_controls(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListControlsRequest, dict]): - The request object. Request for ListControls method. - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.control_service.pagers.ListControlsPager: - Response for ListControls method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.ListControlsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.ListControlsRequest): - request = control_service.ListControlsRequest(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_controls] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListControlsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ControlServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py deleted file mode 100644 index f51a3970..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control_service - - -class ListControlsPager: - """A pager for iterating through ``list_controls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListControlsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``controls`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListControls`` requests and continue to iterate - through the ``controls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListControlsResponse` - 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[..., control_service.ListControlsResponse], - request: control_service.ListControlsRequest, - response: control_service.ListControlsResponse, - *, - 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.retail_v2beta.types.ListControlsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListControlsResponse): - 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 = control_service.ListControlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[control_service.ListControlsResponse]: - 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[control.Control]: - for page in self.pages: - yield from page.controls - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListControlsAsyncPager: - """A pager for iterating through ``list_controls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListControlsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``controls`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListControls`` requests and continue to iterate - through the ``controls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListControlsResponse` - 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[control_service.ListControlsResponse]], - request: control_service.ListControlsRequest, - response: control_service.ListControlsResponse, - *, - 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.retail_v2beta.types.ListControlsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListControlsResponse): - 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 = control_service.ListControlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[control_service.ListControlsResponse]: - 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[control.Control]: - async def async_generator(): - async for page in self.pages: - for response in page.controls: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py deleted file mode 100644 index 3622876b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ControlServiceTransport -from .grpc import ControlServiceGrpcTransport -from .grpc_asyncio import ControlServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ControlServiceTransport]] -_transport_registry['grpc'] = ControlServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ControlServiceGrpcAsyncIOTransport - -__all__ = ( - 'ControlServiceTransport', - 'ControlServiceGrpcTransport', - 'ControlServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py deleted file mode 100644 index 2424eb4a..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py +++ /dev/null @@ -1,213 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ControlServiceTransport(abc.ABC): - """Abstract transport class for ControlService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_control: gapic_v1.method.wrap_method( - self.create_control, - default_timeout=None, - client_info=client_info, - ), - self.delete_control: gapic_v1.method.wrap_method( - self.delete_control, - default_timeout=None, - client_info=client_info, - ), - self.update_control: gapic_v1.method.wrap_method( - self.update_control, - default_timeout=None, - client_info=client_info, - ), - self.get_control: gapic_v1.method.wrap_method( - self.get_control, - default_timeout=None, - client_info=client_info, - ), - self.list_controls: gapic_v1.method.wrap_method( - self.list_controls, - 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 create_control(self) -> Callable[ - [control_service.CreateControlRequest], - Union[ - gcr_control.Control, - Awaitable[gcr_control.Control] - ]]: - raise NotImplementedError() - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - Union[ - gcr_control.Control, - Awaitable[gcr_control.Control] - ]]: - raise NotImplementedError() - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - Union[ - control.Control, - Awaitable[control.Control] - ]]: - raise NotImplementedError() - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - Union[ - control_service.ListControlsResponse, - Awaitable[control_service.ListControlsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ControlServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py deleted file mode 100644 index 64b13dfb..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py +++ /dev/null @@ -1,382 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO - - -class ControlServiceGrpcTransport(ControlServiceTransport): - """gRPC backend transport for ControlService. - - Service for modifying Control. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_control(self) -> Callable[ - [control_service.CreateControlRequest], - gcr_control.Control]: - r"""Return a callable for the create control method over gRPC. - - Creates a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['create_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/CreateControl', - request_serializer=control_service.CreateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['create_control'] - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete control method over gRPC. - - Deletes a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteControlRequest], - ~.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_control' not in self._stubs: - self._stubs['delete_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/DeleteControl', - request_serializer=control_service.DeleteControlRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_control'] - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - gcr_control.Control]: - r"""Return a callable for the update control method over gRPC. - - Updates a Control. - - [Control][google.cloud.retail.v2beta.Control] cannot be set to a - different oneof field, if so an INVALID_ARGUMENT is returned. If - the [Control][google.cloud.retail.v2beta.Control] to delete does - not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.UpdateControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['update_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/UpdateControl', - request_serializer=control_service.UpdateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['update_control'] - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - control.Control]: - r"""Return a callable for the get control method over gRPC. - - Gets a Control. - - Returns: - Callable[[~.GetControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['get_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/GetControl', - request_serializer=control_service.GetControlRequest.serialize, - response_deserializer=control.Control.deserialize, - ) - return self._stubs['get_control'] - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - control_service.ListControlsResponse]: - r"""Return a callable for the list controls method over gRPC. - - Lists all Controls linked to this catalog. - - Returns: - Callable[[~.ListControlsRequest], - ~.ListControlsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_controls' not in self._stubs: - self._stubs['list_controls'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/ListControls', - request_serializer=control_service.ListControlsRequest.serialize, - response_deserializer=control_service.ListControlsResponse.deserialize, - ) - return self._stubs['list_controls'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ControlServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py deleted file mode 100644 index 701a8de1..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,381 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ControlServiceGrpcTransport - - -class ControlServiceGrpcAsyncIOTransport(ControlServiceTransport): - """gRPC AsyncIO backend transport for ControlService. - - Service for modifying Control. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_control(self) -> Callable[ - [control_service.CreateControlRequest], - Awaitable[gcr_control.Control]]: - r"""Return a callable for the create control method over gRPC. - - Creates a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['create_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/CreateControl', - request_serializer=control_service.CreateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['create_control'] - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete control method over gRPC. - - Deletes a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteControlRequest], - 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_control' not in self._stubs: - self._stubs['delete_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/DeleteControl', - request_serializer=control_service.DeleteControlRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_control'] - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - Awaitable[gcr_control.Control]]: - r"""Return a callable for the update control method over gRPC. - - Updates a Control. - - [Control][google.cloud.retail.v2beta.Control] cannot be set to a - different oneof field, if so an INVALID_ARGUMENT is returned. If - the [Control][google.cloud.retail.v2beta.Control] to delete does - not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.UpdateControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['update_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/UpdateControl', - request_serializer=control_service.UpdateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['update_control'] - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - Awaitable[control.Control]]: - r"""Return a callable for the get control method over gRPC. - - Gets a Control. - - Returns: - Callable[[~.GetControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['get_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/GetControl', - request_serializer=control_service.GetControlRequest.serialize, - response_deserializer=control.Control.deserialize, - ) - return self._stubs['get_control'] - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - Awaitable[control_service.ListControlsResponse]]: - r"""Return a callable for the list controls method over gRPC. - - Lists all Controls linked to this catalog. - - Returns: - Callable[[~.ListControlsRequest], - Awaitable[~.ListControlsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_controls' not in self._stubs: - self._stubs['list_controls'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/ListControls', - request_serializer=control_service.ListControlsRequest.serialize, - response_deserializer=control_service.ListControlsResponse.deserialize, - ) - return self._stubs['list_controls'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ControlServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py deleted file mode 100644 index 7c079c80..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import PredictionServiceClient -from .async_client import PredictionServiceAsyncClient - -__all__ = ( - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py deleted file mode 100644 index d8a1a148..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py +++ /dev/null @@ -1,279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport -from .client import PredictionServiceClient - - -class PredictionServiceAsyncClient: - """Service for making recommendation prediction.""" - - _client: PredictionServiceClient - - DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT - - product_path = staticmethod(PredictionServiceClient.product_path) - parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) - common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(PredictionServiceClient.common_project_path) - parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) - common_location_path = staticmethod(PredictionServiceClient.common_location_path) - parse_common_location_path = staticmethod(PredictionServiceClient.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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PredictionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_predict(): - # Create a client - client = retail_v2beta.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - request = prediction_service.PredictRequest(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.predict, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py deleted file mode 100644 index 6eb343ca..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py +++ /dev/null @@ -1,480 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PredictionServiceGrpcTransport -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -class PredictionServiceClientMeta(type): - """Metaclass for the PredictionService 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[PredictionServiceTransport]] - _transport_registry["grpc"] = PredictionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PredictionServiceTransport]: - """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): - """Service for making recommendation prediction.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PredictionServiceClient: 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: - PredictionServiceClient: 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) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, PredictionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, PredictionServiceTransport): - # transport is a PredictionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_predict(): - # Create a client - client = retail_v2beta.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a prediction_service.PredictRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_service.PredictRequest): - request = prediction_service.PredictRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.predict] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py deleted file mode 100644 index bb65c664..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PredictionServiceTransport -from .grpc import PredictionServiceGrpcTransport -from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] -_transport_registry['grpc'] = PredictionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport - -__all__ = ( - 'PredictionServiceTransport', - 'PredictionServiceGrpcTransport', - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py deleted file mode 100644 index 12f65a6c..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PredictionServiceTransport(abc.ABC): - """Abstract transport class for PredictionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.predict: gapic_v1.method.wrap_method( - self.predict, - 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - Union[ - prediction_service.PredictResponse, - Awaitable[prediction_service.PredictResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PredictionServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py deleted file mode 100644 index 98c69839..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py +++ /dev/null @@ -1,264 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO - - -class PredictionServiceGrpcTransport(PredictionServiceTransport): - """gRPC backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - prediction_service.PredictResponse]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - ~.PredictResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PredictionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py deleted file mode 100644 index 11fce51c..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import PredictionServiceGrpcTransport - - -class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): - """gRPC AsyncIO backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def predict(self) -> Callable[ - [prediction_service.PredictRequest], - Awaitable[prediction_service.PredictResponse]]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - Awaitable[~.PredictResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py deleted file mode 100644 index 0fa6330a..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ProductServiceClient -from .async_client import ProductServiceAsyncClient - -__all__ = ( - 'ProductServiceClient', - 'ProductServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py deleted file mode 100644 index 493936e0..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py +++ /dev/null @@ -1,1692 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.services.product_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.cloud.retail_v2beta.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport -from .client import ProductServiceClient - - -class ProductServiceAsyncClient: - """Service for ingesting [Product][google.cloud.retail.v2beta.Product] - information of the customer's website. - """ - - _client: ProductServiceClient - - DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(ProductServiceClient.branch_path) - parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) - product_path = staticmethod(ProductServiceClient.product_path) - parse_product_path = staticmethod(ProductServiceClient.parse_product_path) - common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProductServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProductServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ProductServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) - common_location_path = staticmethod(ProductServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProductServiceClient.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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ProductServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ProductServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_create_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (:class:`str`): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (:class:`google.cloud.retail_v2beta.types.Product`): - Required. The - [Product][google.cloud.retail.v2beta.Product] to create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (:class:`str`): - Required. The ID to use for the - [Product][google.cloud.retail.v2beta.Product], which - will become the final component of the - [Product.name][google.cloud.retail.v2beta.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This field must be unique among all - [Product][google.cloud.retail.v2beta.Product]s with the - same - [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.CreateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the requested - [Product][google.cloud.retail.v2beta.Product] 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.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.GetProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsAsyncPager: - r"""Gets a list of [Product][google.cloud.retail.v2beta.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_list_products(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - parent (:class:`str`): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2beta.Product]s under - this branch, regardless of whether or not this branch - exists, a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.product_service.pagers.ListProductsAsyncPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.ListProductsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_products, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProductsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (:class:`google.cloud.retail_v2beta.types.Product`): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2beta.Product] to update. - The immutable and output only fields are NOT supported. - If not set, all supported fields (the fields that are - neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.UpdateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_delete_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2beta.Product] to - delete can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product] member nor - a - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] with more - than one - [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2beta.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.DeleteProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2beta.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2beta.Product]s to be - successfully updated. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_import_products(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2beta.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2beta.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_set_inventory(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2beta.Product() - inventory.title = "title_value" - - request = retail_v2beta.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (:class:`google.cloud.retail_v2beta.types.Product`): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product] named in - [Product.name][google.cloud.retail.v2beta.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2beta.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2beta.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.SetInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_inventory, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - async def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [AddFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_add_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [AddLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_remove_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py deleted file mode 100644 index fa4ba1f6..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py +++ /dev/null @@ -1,1895 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.services.product_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.cloud.retail_v2beta.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProductServiceGrpcTransport -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -class ProductServiceClientMeta(type): - """Metaclass for the ProductService 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[ProductServiceTransport]] - _transport_registry["grpc"] = ProductServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ProductServiceTransport]: - """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 ProductServiceClient(metaclass=ProductServiceClientMeta): - """Service for ingesting [Product][google.cloud.retail.v2beta.Product] - information of the customer's website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProductServiceClient: 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: - ProductServiceClient: 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) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProductServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ProductServiceTransport): - # transport is a ProductServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_create_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (google.cloud.retail_v2beta.types.Product): - Required. The - [Product][google.cloud.retail.v2beta.Product] to create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2beta.Product], which - will become the final component of the - [Product.name][google.cloud.retail.v2beta.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This field must be unique among all - [Product][google.cloud.retail.v2beta.Product]s with the - same - [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.CreateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.CreateProductRequest): - request = product_service.CreateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the requested - [Product][google.cloud.retail.v2beta.Product] 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.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.GetProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.GetProductRequest): - request = product_service.GetProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsPager: - r"""Gets a list of [Product][google.cloud.retail.v2beta.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_list_products(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2beta.Product]s under - this branch, regardless of whether or not this branch - exists, a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.product_service.pagers.ListProductsPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.ListProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.ListProductsRequest): - request = product_service.ListProductsRequest(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_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProductsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (google.cloud.retail_v2beta.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2beta.Product] to update. - The immutable and output only fields are NOT supported. - If not set, all supported fields (the fields that are - neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.UpdateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.UpdateProductRequest): - request = product_service.UpdateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - 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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_delete_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2beta.Product] to - delete can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product] member nor - a - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] with more - than one - [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2beta.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.DeleteProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.DeleteProductRequest): - request = product_service.DeleteProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2beta.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2beta.Product]s to be - successfully updated. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_import_products(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2beta.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportProductsRequest): - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2beta.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_set_inventory(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2beta.Product() - inventory.title = "title_value" - - request = retail_v2beta.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (google.cloud.retail_v2beta.types.Product): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product] named in - [Product.name][google.cloud.retail.v2beta.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2beta.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2beta.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.SetInventoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.SetInventoryRequest): - request = product_service.SetInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_add_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [AddFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddFulfillmentPlacesRequest): - request = product_service.AddFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): - request = product_service.RemoveFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_add_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [AddLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddLocalInventoriesRequest): - request = product_service.AddLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_remove_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveLocalInventoriesRequest): - request = product_service.RemoveLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py deleted file mode 100644 index 552c2bfa..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product_service - - -class ListProductsPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListProductsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListProductsResponse` - 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[..., product_service.ListProductsResponse], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2beta.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[product_service.ListProductsResponse]: - 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[product.Product]: - for page in self.pages: - yield from page.products - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProductsAsyncPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListProductsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListProductsResponse` - 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[product_service.ListProductsResponse]], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2beta.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: - 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[product.Product]: - async def async_generator(): - async for page in self.pages: - for response in page.products: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py deleted file mode 100644 index db824dec..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ProductServiceTransport -from .grpc import ProductServiceGrpcTransport -from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] -_transport_registry['grpc'] = ProductServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport - -__all__ = ( - 'ProductServiceTransport', - 'ProductServiceGrpcTransport', - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py deleted file mode 100644 index 325ba99e..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py +++ /dev/null @@ -1,312 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ProductServiceTransport(abc.ABC): - """Abstract transport class for ProductService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_product: gapic_v1.method.wrap_method( - self.create_product, - default_timeout=None, - client_info=client_info, - ), - self.get_product: gapic_v1.method.wrap_method( - self.get_product, - default_timeout=None, - client_info=client_info, - ), - self.list_products: gapic_v1.method.wrap_method( - self.list_products, - default_timeout=None, - client_info=client_info, - ), - self.update_product: gapic_v1.method.wrap_method( - self.update_product, - default_timeout=None, - client_info=client_info, - ), - self.delete_product: gapic_v1.method.wrap_method( - self.delete_product, - default_timeout=None, - client_info=client_info, - ), - self.import_products: gapic_v1.method.wrap_method( - self.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.set_inventory: gapic_v1.method.wrap_method( - self.set_inventory, - default_timeout=None, - client_info=client_info, - ), - self.add_fulfillment_places: gapic_v1.method.wrap_method( - self.add_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.remove_fulfillment_places: gapic_v1.method.wrap_method( - self.remove_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.add_local_inventories: gapic_v1.method.wrap_method( - self.add_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.remove_local_inventories: gapic_v1.method.wrap_method( - self.remove_local_inventories, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Union[ - product.Product, - Awaitable[product.Product] - ]]: - raise NotImplementedError() - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Union[ - product_service.ListProductsResponse, - Awaitable[product_service.ListProductsResponse] - ]]: - raise NotImplementedError() - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ProductServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py deleted file mode 100644 index 8df65e63..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py +++ /dev/null @@ -1,680 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO - - -class ProductServiceGrpcTransport(ProductServiceTransport): - """gRPC backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2beta.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - gcr_product.Product]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.CreateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - product.Product]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.GetProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - product_service.ListProductsResponse]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2beta.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - ~.ListProductsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - gcr_product.Product]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - ~.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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2beta.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2beta.Product]s to be - successfully updated. - - Returns: - Callable[[~.ImportProductsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - operations_pb2.Operation]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2beta.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProductServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py deleted file mode 100644 index 9ccfc3ee..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,679 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ProductServiceGrpcTransport - - -class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): - """gRPC AsyncIO backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2beta.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.CreateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Awaitable[product.Product]]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.GetProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Awaitable[product_service.ListProductsResponse]]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2beta.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - Awaitable[~.ListProductsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - 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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2beta.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2beta.Product]s to be - successfully updated. - - Returns: - Callable[[~.ImportProductsRequest], - 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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2beta.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - 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 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - 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 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - 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 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - 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 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py deleted file mode 100644 index 2f63fc22..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SearchServiceClient -from .async_client import SearchServiceAsyncClient - -__all__ = ( - 'SearchServiceClient', - 'SearchServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py deleted file mode 100644 index 4943cff9..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.search_service import pagers -from google.cloud.retail_v2beta.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .client import SearchServiceClient - - -class SearchServiceAsyncClient: - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: SearchServiceClient - - DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(SearchServiceClient.branch_path) - parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) - product_path = staticmethod(SearchServiceClient.product_path) - parse_product_path = staticmethod(SearchServiceClient.parse_product_path) - common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(SearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SearchServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAsyncPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_search(): - # Create a client - client = retail_v2beta.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.search_service.pagers.SearchAsyncPager: - Response message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py deleted file mode 100644 index 7c944320..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py +++ /dev/null @@ -1,513 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.search_service import pagers -from google.cloud.retail_v2beta.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SearchServiceGrpcTransport -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -class SearchServiceClientMeta(type): - """Metaclass for the SearchService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] - _transport_registry["grpc"] = SearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SearchServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SearchServiceClient(metaclass=SearchServiceClientMeta): - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SearchServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SearchServiceTransport): - # transport is a SearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_search(): - # Create a client - client = retail_v2beta.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.search_service.pagers.SearchPager: - Response message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a search_service.SearchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, search_service.SearchRequest): - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py deleted file mode 100644 index 6ff03162..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import search_service - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., search_service.SearchResponse], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2beta.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[search_service.SearchResponse]], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2beta.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py deleted file mode 100644 index 7917cd1d..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SearchServiceTransport -from .grpc import SearchServiceGrpcTransport -from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] -_transport_registry['grpc'] = SearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport - -__all__ = ( - 'SearchServiceTransport', - 'SearchServiceGrpcTransport', - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py deleted file mode 100644 index c084a7f1..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import search_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class SearchServiceTransport(abc.ABC): - """Abstract transport class for SearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search: gapic_v1.method.wrap_method( - self.search, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Union[ - search_service.SearchResponse, - Awaitable[search_service.SearchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SearchServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py deleted file mode 100644 index 74a10421..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py +++ /dev/null @@ -1,270 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO - - -class SearchServiceGrpcTransport(SearchServiceTransport): - """gRPC backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py deleted file mode 100644 index 3dfd4aa1..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SearchServiceGrpcTransport - - -class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): - """gRPC AsyncIO backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Awaitable[search_service.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py deleted file mode 100644 index d1a0a023..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ServingConfigServiceClient -from .async_client import ServingConfigServiceAsyncClient - -__all__ = ( - 'ServingConfigServiceClient', - 'ServingConfigServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py deleted file mode 100644 index cfdace1d..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py +++ /dev/null @@ -1,954 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.serving_config_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport -from .client import ServingConfigServiceClient - - -class ServingConfigServiceAsyncClient: - """Service for modifying ServingConfig.""" - - _client: ServingConfigServiceClient - - DEFAULT_ENDPOINT = ServingConfigServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ServingConfigServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(ServingConfigServiceClient.catalog_path) - parse_catalog_path = staticmethod(ServingConfigServiceClient.parse_catalog_path) - serving_config_path = staticmethod(ServingConfigServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(ServingConfigServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(ServingConfigServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ServingConfigServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ServingConfigServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ServingConfigServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ServingConfigServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ServingConfigServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ServingConfigServiceClient.common_project_path) - parse_common_project_path = staticmethod(ServingConfigServiceClient.parse_common_project_path) - common_location_path = staticmethod(ServingConfigServiceClient.common_location_path) - parse_common_location_path = staticmethod(ServingConfigServiceClient.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: - ServingConfigServiceAsyncClient: The constructed client. - """ - return ServingConfigServiceClient.from_service_account_info.__func__(ServingConfigServiceAsyncClient, 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: - ServingConfigServiceAsyncClient: The constructed client. - """ - return ServingConfigServiceClient.from_service_account_file.__func__(ServingConfigServiceAsyncClient, 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 variabel 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 ServingConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ServingConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ServingConfigServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ServingConfigServiceClient).get_transport_class, type(ServingConfigServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ServingConfigServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the serving config service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ServingConfigServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ServingConfigServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_serving_config(self, - request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, - *, - parent: str = None, - serving_config: gcr_serving_config.ServingConfig = None, - serving_config_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_create_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = await client.create_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateServingConfigRequest, dict]): - The request object. Request for CreateServingConfig - method. - parent (:class:`str`): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config (:class:`google.cloud.retail_v2beta.types.ServingConfig`): - Required. The ServingConfig to - create. - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config_id (:class:`str`): - Required. The ID to use for the ServingConfig, which - will become the final component of the ServingConfig's - resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``serving_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, serving_config, serving_config_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.CreateServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if serving_config is not None: - request.serving_config = serving_config - if serving_config_id is not None: - request.serving_config_id = serving_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_serving_config(self, - request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_delete_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_serving_config(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteServingConfigRequest, dict]): - The request object. Request for DeleteServingConfig - method. - name (:class:`str`): - Required. The resource name of the ServingConfig to - delete. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.DeleteServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_serving_config(self, - request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, - *, - serving_config: gcr_serving_config.ServingConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Updates a ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = await client.update_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateServingConfigRequest, dict]): - The request object. Request for UpdateServingConfig - method. - serving_config (:class:`google.cloud.retail_v2beta.types.ServingConfig`): - Required. The ServingConfig to - update. - - This corresponds to the ``serving_config`` 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 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.UpdateServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config.name", request.serving_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_serving_config(self, - request: Union[serving_config_service.GetServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> serving_config.ServingConfig: - r"""Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetServingConfigRequest, dict]): - The request object. Request for GetServingConfig method. - name (:class:`str`): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.GetServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_serving_configs(self, - request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServingConfigsAsyncPager: - r"""Lists all ServingConfigs linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_list_serving_configs(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListServingConfigsRequest, dict]): - The request object. Request for ListServingConfigs - method. - parent (:class:`str`): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager: - Response for ListServingConfigs - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.ListServingConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_serving_configs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListServingConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def add_control(self, - request: Union[serving_config_service.AddControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_add_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.add_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddControlRequest, dict]): - The request object. Request for AddControl method. - serving_config (:class:`str`): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.AddControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def remove_control(self, - request: Union[serving_config_service.RemoveControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_remove_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.remove_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveControlRequest, dict]): - The request object. Request for RemoveControl method. - serving_config (:class:`str`): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.RemoveControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServingConfigServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py deleted file mode 100644 index bca31abe..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py +++ /dev/null @@ -1,1163 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.serving_config_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ServingConfigServiceGrpcTransport -from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport - - -class ServingConfigServiceClientMeta(type): - """Metaclass for the ServingConfigService 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[ServingConfigServiceTransport]] - _transport_registry["grpc"] = ServingConfigServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ServingConfigServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ServingConfigServiceTransport]: - """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 ServingConfigServiceClient(metaclass=ServingConfigServiceClientMeta): - """Service for modifying ServingConfig.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServingConfigServiceClient: 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: - ServingConfigServiceClient: 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) -> ServingConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ServingConfigServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,catalog: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ServingConfigServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the serving config service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ServingConfigServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ServingConfigServiceTransport): - # transport is a ServingConfigServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_serving_config(self, - request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, - *, - parent: str = None, - serving_config: gcr_serving_config.ServingConfig = None, - serving_config_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_create_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = client.create_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateServingConfigRequest, dict]): - The request object. Request for CreateServingConfig - method. - parent (str): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config (google.cloud.retail_v2beta.types.ServingConfig): - Required. The ServingConfig to - create. - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config_id (str): - Required. The ID to use for the ServingConfig, which - will become the final component of the ServingConfig's - resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``serving_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, serving_config, serving_config_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.CreateServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.CreateServingConfigRequest): - request = serving_config_service.CreateServingConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if serving_config is not None: - request.serving_config = serving_config - if serving_config_id is not None: - request.serving_config_id = serving_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_serving_config(self, - request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_delete_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_serving_config(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteServingConfigRequest, dict]): - The request object. Request for DeleteServingConfig - method. - name (str): - Required. The resource name of the ServingConfig to - delete. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.DeleteServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.DeleteServingConfigRequest): - request = serving_config_service.DeleteServingConfigRequest(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_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_serving_config(self, - request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, - *, - serving_config: gcr_serving_config.ServingConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Updates a ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = client.update_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateServingConfigRequest, dict]): - The request object. Request for UpdateServingConfig - method. - serving_config (google.cloud.retail_v2beta.types.ServingConfig): - Required. The ServingConfig to - update. - - This corresponds to the ``serving_config`` 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 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.UpdateServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.UpdateServingConfigRequest): - request = serving_config_service.UpdateServingConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config.name", request.serving_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_serving_config(self, - request: Union[serving_config_service.GetServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> serving_config.ServingConfig: - r"""Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetServingConfigRequest, dict]): - The request object. Request for GetServingConfig method. - name (str): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.GetServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.GetServingConfigRequest): - request = serving_config_service.GetServingConfigRequest(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_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_serving_configs(self, - request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServingConfigsPager: - r"""Lists all ServingConfigs linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_list_serving_configs(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListServingConfigsRequest, dict]): - The request object. Request for ListServingConfigs - method. - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsPager: - Response for ListServingConfigs - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.ListServingConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.ListServingConfigsRequest): - request = serving_config_service.ListServingConfigsRequest(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_serving_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListServingConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def add_control(self, - request: Union[serving_config_service.AddControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_add_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.add_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddControlRequest, dict]): - The request object. Request for AddControl method. - serving_config (str): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.AddControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.AddControlRequest): - request = serving_config_service.AddControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def remove_control(self, - request: Union[serving_config_service.RemoveControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_remove_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.remove_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveControlRequest, dict]): - The request object. Request for RemoveControl method. - serving_config (str): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.RemoveControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.RemoveControlRequest): - request = serving_config_service.RemoveControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServingConfigServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py deleted file mode 100644 index a45bf88c..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config_service - - -class ListServingConfigsPager: - """A pager for iterating through ``list_serving_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``serving_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServingConfigs`` requests and continue to iterate - through the ``serving_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` - 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[..., serving_config_service.ListServingConfigsResponse], - request: serving_config_service.ListServingConfigsRequest, - response: serving_config_service.ListServingConfigsResponse, - *, - 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.retail_v2beta.types.ListServingConfigsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListServingConfigsResponse): - 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 = serving_config_service.ListServingConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[serving_config_service.ListServingConfigsResponse]: - 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[serving_config.ServingConfig]: - for page in self.pages: - yield from page.serving_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServingConfigsAsyncPager: - """A pager for iterating through ``list_serving_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``serving_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServingConfigs`` requests and continue to iterate - through the ``serving_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` - 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[serving_config_service.ListServingConfigsResponse]], - request: serving_config_service.ListServingConfigsRequest, - response: serving_config_service.ListServingConfigsResponse, - *, - 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.retail_v2beta.types.ListServingConfigsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListServingConfigsResponse): - 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 = serving_config_service.ListServingConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[serving_config_service.ListServingConfigsResponse]: - 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[serving_config.ServingConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.serving_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py deleted file mode 100644 index 3726ac83..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ServingConfigServiceTransport -from .grpc import ServingConfigServiceGrpcTransport -from .grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ServingConfigServiceTransport]] -_transport_registry['grpc'] = ServingConfigServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ServingConfigServiceGrpcAsyncIOTransport - -__all__ = ( - 'ServingConfigServiceTransport', - 'ServingConfigServiceGrpcTransport', - 'ServingConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py deleted file mode 100644 index b8fc6e2b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ServingConfigServiceTransport(abc.ABC): - """Abstract transport class for ServingConfigService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_serving_config: gapic_v1.method.wrap_method( - self.create_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_serving_config: gapic_v1.method.wrap_method( - self.delete_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.update_serving_config: gapic_v1.method.wrap_method( - self.update_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.get_serving_config: gapic_v1.method.wrap_method( - self.get_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.list_serving_configs: gapic_v1.method.wrap_method( - self.list_serving_configs, - default_timeout=None, - client_info=client_info, - ), - self.add_control: gapic_v1.method.wrap_method( - self.add_control, - default_timeout=None, - client_info=client_info, - ), - self.remove_control: gapic_v1.method.wrap_method( - self.remove_control, - 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 create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - Union[ - serving_config.ServingConfig, - Awaitable[serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - Union[ - serving_config_service.ListServingConfigsResponse, - Awaitable[serving_config_service.ListServingConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ServingConfigServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py deleted file mode 100644 index 309a486a..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py +++ /dev/null @@ -1,440 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO - - -class ServingConfigServiceGrpcTransport(ServingConfigServiceTransport): - """gRPC backend transport for ServingConfigService. - - Service for modifying ServingConfig. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the create serving config method over gRPC. - - Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - Returns: - Callable[[~.CreateServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/CreateServingConfig', - request_serializer=serving_config_service.CreateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['create_serving_config'] - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete serving config method over gRPC. - - Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.DeleteServingConfigRequest], - ~.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_serving_config' not in self._stubs: - self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/DeleteServingConfig', - request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_serving_config'] - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the update serving config method over gRPC. - - Updates a ServingConfig. - - Returns: - Callable[[~.UpdateServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/UpdateServingConfig', - request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['update_serving_config'] - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - serving_config.ServingConfig]: - r"""Return a callable for the get serving config method over gRPC. - - Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.GetServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/GetServingConfig', - request_serializer=serving_config_service.GetServingConfigRequest.serialize, - response_deserializer=serving_config.ServingConfig.deserialize, - ) - return self._stubs['get_serving_config'] - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - serving_config_service.ListServingConfigsResponse]: - r"""Return a callable for the list serving configs method over gRPC. - - Lists all ServingConfigs linked to this catalog. - - Returns: - Callable[[~.ListServingConfigsRequest], - ~.ListServingConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: - self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/ListServingConfigs', - request_serializer=serving_config_service.ListServingConfigsRequest.serialize, - response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, - ) - return self._stubs['list_serving_configs'] - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the add control method over gRPC. - - Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - Returns: - Callable[[~.AddControlRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_control' not in self._stubs: - self._stubs['add_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/AddControl', - request_serializer=serving_config_service.AddControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['add_control'] - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the remove control method over gRPC. - - Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - Returns: - Callable[[~.RemoveControlRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_control' not in self._stubs: - self._stubs['remove_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/RemoveControl', - request_serializer=serving_config_service.RemoveControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['remove_control'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ServingConfigServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py deleted file mode 100644 index 3cd75655..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,439 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ServingConfigServiceGrpcTransport - - -class ServingConfigServiceGrpcAsyncIOTransport(ServingConfigServiceTransport): - """gRPC AsyncIO backend transport for ServingConfigService. - - Service for modifying ServingConfig. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the create serving config method over gRPC. - - Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - Returns: - Callable[[~.CreateServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/CreateServingConfig', - request_serializer=serving_config_service.CreateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['create_serving_config'] - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete serving config method over gRPC. - - Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.DeleteServingConfigRequest], - 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_serving_config' not in self._stubs: - self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/DeleteServingConfig', - request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_serving_config'] - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the update serving config method over gRPC. - - Updates a ServingConfig. - - Returns: - Callable[[~.UpdateServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/UpdateServingConfig', - request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['update_serving_config'] - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - Awaitable[serving_config.ServingConfig]]: - r"""Return a callable for the get serving config method over gRPC. - - Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.GetServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/GetServingConfig', - request_serializer=serving_config_service.GetServingConfigRequest.serialize, - response_deserializer=serving_config.ServingConfig.deserialize, - ) - return self._stubs['get_serving_config'] - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - Awaitable[serving_config_service.ListServingConfigsResponse]]: - r"""Return a callable for the list serving configs method over gRPC. - - Lists all ServingConfigs linked to this catalog. - - Returns: - Callable[[~.ListServingConfigsRequest], - Awaitable[~.ListServingConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: - self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/ListServingConfigs', - request_serializer=serving_config_service.ListServingConfigsRequest.serialize, - response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, - ) - return self._stubs['list_serving_configs'] - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the add control method over gRPC. - - Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - Returns: - Callable[[~.AddControlRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_control' not in self._stubs: - self._stubs['add_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/AddControl', - request_serializer=serving_config_service.AddControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['add_control'] - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the remove control method over gRPC. - - Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - Returns: - Callable[[~.RemoveControlRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_control' not in self._stubs: - self._stubs['remove_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/RemoveControl', - request_serializer=serving_config_service.RemoveControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['remove_control'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ServingConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py deleted file mode 100644 index 5f5171c1..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py deleted file mode 100644 index 24cdc934..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py +++ /dev/null @@ -1,730 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on the customer - website. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(UserEventServiceClient.catalog_path) - parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) - product_path = staticmethod(UserEventServiceClient.product_path) - parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_write_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_collect_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_purge_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_import_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2beta.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_rejoin_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py deleted file mode 100644 index a57e4e27..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py +++ /dev/null @@ -1,930 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[UserEventServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on the customer - website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_write_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_collect_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_purge_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeUserEventsRequest): - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_import_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2beta.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportUserEventsRequest): - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_rejoin_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.RejoinUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.RejoinUserEventsRequest): - request = user_event_service.RejoinUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py deleted file mode 100644 index f53ee5d7..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py deleted file mode 100644 index bf9e4cfe..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py +++ /dev/null @@ -1,235 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_timeout=None, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_timeout=None, - client_info=client_info, - ), - self.purge_user_events: gapic_v1.method.wrap_method( - self.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.rejoin_user_events: gapic_v1.method.wrap_method( - self.rejoin_user_events, - 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 write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - user_event.UserEvent, - Awaitable[user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py deleted file mode 100644 index 098839e0..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index 7fbcb123..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - 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 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py deleted file mode 100644 index 62477503..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py +++ /dev/null @@ -1,278 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .catalog import ( - AttributesConfig, - Catalog, - CatalogAttribute, - CompletionConfig, - MerchantCenterLink, - MerchantCenterLinkingConfig, - ProductLevelConfig, -) -from .catalog_service import ( - AddCatalogAttributeRequest, - GetAttributesConfigRequest, - GetCompletionConfigRequest, - GetDefaultBranchRequest, - GetDefaultBranchResponse, - ListCatalogsRequest, - ListCatalogsResponse, - RemoveCatalogAttributeRequest, - ReplaceCatalogAttributeRequest, - SetDefaultBranchRequest, - UpdateAttributesConfigRequest, - UpdateCatalogRequest, - UpdateCompletionConfigRequest, -) -from .common import ( - Audience, - ColorInfo, - Condition, - CustomAttribute, - FulfillmentInfo, - Image, - Interval, - LocalInventory, - PriceInfo, - Rating, - Rule, - UserInfo, - AttributeConfigLevel, - SearchSolutionUseCase, - SolutionType, -) -from .completion_service import ( - CompleteQueryRequest, - CompleteQueryResponse, -) -from .control import ( - Control, -) -from .control_service import ( - CreateControlRequest, - DeleteControlRequest, - GetControlRequest, - ListControlsRequest, - ListControlsResponse, - UpdateControlRequest, -) -from .export_config import ( - ExportErrorsConfig, - ExportMetadata, - ExportProductsResponse, - ExportUserEventsResponse, -) -from .import_config import ( - BigQuerySource, - CompletionDataInputConfig, - GcsSource, - ImportCompletionDataRequest, - ImportCompletionDataResponse, - ImportErrorsConfig, - ImportMetadata, - ImportProductsRequest, - ImportProductsResponse, - ImportUserEventsRequest, - ImportUserEventsResponse, - ProductInlineSource, - ProductInputConfig, - UserEventImportSummary, - UserEventInlineSource, - UserEventInputConfig, -) -from .prediction_service import ( - PredictRequest, - PredictResponse, -) -from .product import ( - Product, -) -from .product_service import ( - AddFulfillmentPlacesMetadata, - AddFulfillmentPlacesRequest, - AddFulfillmentPlacesResponse, - AddLocalInventoriesMetadata, - AddLocalInventoriesRequest, - AddLocalInventoriesResponse, - CreateProductRequest, - DeleteProductRequest, - GetProductRequest, - ListProductsRequest, - ListProductsResponse, - RemoveFulfillmentPlacesMetadata, - RemoveFulfillmentPlacesRequest, - RemoveFulfillmentPlacesResponse, - RemoveLocalInventoriesMetadata, - RemoveLocalInventoriesRequest, - RemoveLocalInventoriesResponse, - SetInventoryMetadata, - SetInventoryRequest, - SetInventoryResponse, - UpdateProductRequest, -) -from .promotion import ( - Promotion, -) -from .purge_config import ( - PurgeMetadata, - PurgeUserEventsRequest, - PurgeUserEventsResponse, -) -from .search_service import ( - SearchRequest, - SearchResponse, -) -from .serving_config import ( - ServingConfig, -) -from .serving_config_service import ( - AddControlRequest, - CreateServingConfigRequest, - DeleteServingConfigRequest, - GetServingConfigRequest, - ListServingConfigsRequest, - ListServingConfigsResponse, - RemoveControlRequest, - UpdateServingConfigRequest, -) -from .user_event import ( - CompletionDetail, - ProductDetail, - PurchaseTransaction, - UserEvent, -) -from .user_event_service import ( - CollectUserEventRequest, - RejoinUserEventsMetadata, - RejoinUserEventsRequest, - RejoinUserEventsResponse, - WriteUserEventRequest, -) - -__all__ = ( - 'AttributesConfig', - 'Catalog', - 'CatalogAttribute', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'ProductLevelConfig', - 'AddCatalogAttributeRequest', - 'GetAttributesConfigRequest', - 'GetCompletionConfigRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - 'SetDefaultBranchRequest', - 'UpdateAttributesConfigRequest', - 'UpdateCatalogRequest', - 'UpdateCompletionConfigRequest', - 'Audience', - 'ColorInfo', - 'Condition', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'Rule', - 'UserInfo', - 'AttributeConfigLevel', - 'SearchSolutionUseCase', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Control', - 'CreateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - 'UpdateControlRequest', - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'ServingConfig', - 'AddControlRequest', - 'CreateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'RemoveControlRequest', - 'UpdateServingConfigRequest', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py deleted file mode 100644 index 8398213f..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py +++ /dev/null @@ -1,528 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'ProductLevelConfig', - 'CatalogAttribute', - 'AttributesConfig', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'Catalog', - }, -) - - -class ProductLevelConfig(proto.Message): - r"""Configures what level the product should be uploaded with - regards to how users will be send events and how predictions - will be made. - - Attributes: - ingestion_product_type (str): - The type of [Product][google.cloud.retail.v2beta.Product]s - allowed to be ingested into the catalog. Acceptable values - are: - - - ``primary`` (default): You can ingest - [Product][google.cloud.retail.v2beta.Product]s of all - types. When ingesting a - [Product][google.cloud.retail.v2beta.Product], its type - will default to - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - if unset. - - ``variant``: You can only ingest - [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s. This - means - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] - cannot be empty. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``variant`` and - [merchant_center_product_id_field][google.cloud.retail.v2beta.ProductLevelConfig.merchant_center_product_id_field] - is ``itemGroupId``, an INVALID_ARGUMENT error is returned. - - See `Using product - levels `__ - for more details. - merchant_center_product_id_field (str): - Which field of `Merchant Center - Product `__ - should be imported as - [Product.id][google.cloud.retail.v2beta.Product.id]. - Acceptable values are: - - - ``offerId`` (default): Import ``offerId`` as the product - ID. - - ``itemGroupId``: Import ``itemGroupId`` as the product - ID. Notice that Retail API will choose one item from the - ones with the same ``itemGroupId``, and use it to - represent the item group. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``itemGroupId`` and - [ingestion_product_type][google.cloud.retail.v2beta.ProductLevelConfig.ingestion_product_type] - is ``variant``, an INVALID_ARGUMENT error is returned. - - See `Using product - levels `__ - for more details. - """ - - ingestion_product_type = proto.Field( - proto.STRING, - number=1, - ) - merchant_center_product_id_field = proto.Field( - proto.STRING, - number=2, - ) - - -class CatalogAttribute(proto.Message): - r"""Catalog level attribute config for an attribute. For example, - if customers want to enable/disable facet for a specific - attribute. - - Attributes: - key (str): - Required. Attribute name. For example: ``color``, - ``brands``, ``attributes.custom_attribute``, such as - ``attributes.xyz``. - in_use (bool): - Output only. Indicates whether this attribute has been used - by any products. ``True`` if at least one - [Product][google.cloud.retail.v2beta.Product] is using this - attribute in - [Product.attributes][google.cloud.retail.v2beta.Product.attributes]. - Otherwise, this field is ``False``. - - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - can be pre-loaded by using [AddCatalogAttribute][], - [ImportCatalogAttributes][], or [UpdateAttributesConfig][] - APIs. This field is ``False`` for pre-loaded - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s. - - Only - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s - that are not in use by products can be deleted. - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s - that are in use by products cannot be deleted; however, - their configuration properties will reset to default values - upon removal request. - - After catalog changes, it takes about 10 minutes for this - field to update. - type_ (google.cloud.retail_v2beta.types.CatalogAttribute.AttributeType): - Output only. The type of this attribute. This is derived - from the attribute in - [Product.attributes][google.cloud.retail.v2beta.Product.attributes]. - indexable_option (google.cloud.retail_v2beta.types.CatalogAttribute.IndexableOption): - When - [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] - is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if INDEXABLE_ENABLED - attribute values are indexed so that it can be filtered, - faceted, or boosted in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - dynamic_facetable_option (google.cloud.retail_v2beta.types.CatalogAttribute.DynamicFacetableOption): - If DYNAMIC_FACETABLE_ENABLED, attribute values are available - for dynamic facet. Could only be DYNAMIC_FACETABLE_DISABLED - if - [CatalogAttribute.indexable_option][google.cloud.retail.v2beta.CatalogAttribute.indexable_option] - is INDEXABLE_DISABLED. Otherwise, an INVALID_ARGUMENT error - is returned. - searchable_option (google.cloud.retail_v2beta.types.CatalogAttribute.SearchableOption): - When - [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] - is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if SEARCHABLE_ENABLED, - attribute values are searchable by text queries in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - If SEARCHABLE_ENABLED but attribute type is numerical, - attribute values will not be searchable by text queries in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - as there are no text values associated to numerical - attributes. - """ - class AttributeType(proto.Enum): - r"""The type of an attribute.""" - UNKNOWN = 0 - TEXTUAL = 1 - NUMERICAL = 2 - - class IndexableOption(proto.Enum): - r"""The status of the indexable option of a catalog attribute.""" - INDEXABLE_OPTION_UNSPECIFIED = 0 - INDEXABLE_ENABLED = 1 - INDEXABLE_DISABLED = 2 - - class DynamicFacetableOption(proto.Enum): - r"""The status of the dynamic facetable option of a catalog - attribute. - """ - DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 - DYNAMIC_FACETABLE_ENABLED = 1 - DYNAMIC_FACETABLE_DISABLED = 2 - - class SearchableOption(proto.Enum): - r"""The status of the searchable option of a catalog attribute.""" - SEARCHABLE_OPTION_UNSPECIFIED = 0 - SEARCHABLE_ENABLED = 1 - SEARCHABLE_DISABLED = 2 - - key = proto.Field( - proto.STRING, - number=1, - ) - in_use = proto.Field( - proto.BOOL, - number=9, - ) - type_ = proto.Field( - proto.ENUM, - number=10, - enum=AttributeType, - ) - indexable_option = proto.Field( - proto.ENUM, - number=5, - enum=IndexableOption, - ) - dynamic_facetable_option = proto.Field( - proto.ENUM, - number=6, - enum=DynamicFacetableOption, - ) - searchable_option = proto.Field( - proto.ENUM, - number=7, - enum=SearchableOption, - ) - - -class AttributesConfig(proto.Message): - r"""Catalog level attribute config. - - Attributes: - name (str): - Required. Immutable. The fully qualified resource name of - the attribute config. Format: - ``projects/*/locations/*/catalogs/*/attributesConfig`` - catalog_attributes (Mapping[str, google.cloud.retail_v2beta.types.CatalogAttribute]): - Enable attribute(s) config at catalog level. For example, - indexable, dynamic_facetable, or searchable for each - attribute. - - The key is catalog attribute's name. For example: ``color``, - ``brands``, ``attributes.custom_attribute``, such as - ``attributes.xyz``. - - The maximum number of catalog attributes allowed in a - request is 1000. - attribute_config_level (google.cloud.retail_v2beta.types.AttributeConfigLevel): - Output only. The - [AttributeConfigLevel][google.cloud.retail.v2beta.AttributeConfigLevel] - used for this catalog. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - catalog_attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='CatalogAttribute', - ) - attribute_config_level = proto.Field( - proto.ENUM, - number=3, - enum=common.AttributeConfigLevel, - ) - - -class CompletionConfig(proto.Message): - r"""Catalog level autocomplete config for customers to customize - autocomplete feature's settings. - - Attributes: - name (str): - Required. Immutable. Fully qualified name - ``projects/*/locations/*/catalogs/*/completionConfig`` - matching_order (str): - Specifies the matching order for autocomplete suggestions, - e.g., a query consisting of 'sh' with 'out-of-order' - specified would suggest "women's shoes", whereas a query of - 'red s' with 'exact-prefix' specified would suggest "red - shoes". Currently supported values: - - - 'out-of-order' - - 'exact-prefix' - - Default value: 'exact-prefix'. - max_suggestions (int): - The maximum number of autocomplete - suggestions returned per term. The maximum - allowed max suggestions is 20. Default value is - 20. If left unset or set to 0, then will - fallback to default value. - min_prefix_length (int): - The minimum number of characters needed to be - typed in order to get suggestions. Default value - is 2. If left unset or set to 0, then will - fallback to default value. - auto_learning (bool): - If set to true, the auto learning function is enabled. Auto - learning uses user data to generate suggestions using ML - techniques. Default value is false. Only after enabling auto - learning can users use ``cloud-retail`` data in - [CompleteQueryRequest][google.cloud.retail.v2beta.CompleteQueryRequest]. - suggestions_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the - autocomplete phrases uploaded by the customer. - last_suggestions_import_operation (str): - Output only. Name of the LRO corresponding to the latest - suggestion terms list import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - denylist_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the / - autocomplete denylist phrases uploaded by the - customer. - last_denylist_import_operation (str): - Output only. LRO corresponding to the latest denylist - import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - allowlist_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the - autocomplete allowlist phrases uploaded by the - customer. - last_allowlist_import_operation (str): - Output only. LRO corresponding to the latest allowlist - import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - matching_order = proto.Field( - proto.STRING, - number=2, - ) - max_suggestions = proto.Field( - proto.INT32, - number=3, - ) - min_prefix_length = proto.Field( - proto.INT32, - number=4, - ) - auto_learning = proto.Field( - proto.BOOL, - number=11, - ) - suggestions_input_config = proto.Field( - proto.MESSAGE, - number=5, - message=import_config.CompletionDataInputConfig, - ) - last_suggestions_import_operation = proto.Field( - proto.STRING, - number=6, - ) - denylist_input_config = proto.Field( - proto.MESSAGE, - number=7, - message=import_config.CompletionDataInputConfig, - ) - last_denylist_import_operation = proto.Field( - proto.STRING, - number=8, - ) - allowlist_input_config = proto.Field( - proto.MESSAGE, - number=9, - message=import_config.CompletionDataInputConfig, - ) - last_allowlist_import_operation = proto.Field( - proto.STRING, - number=10, - ) - - -class MerchantCenterLink(proto.Message): - r"""Represents a link between a Merchant Center account and a - branch. Once a link is established, products from the linked - merchant center account will be streamed to the linked branch. - - Attributes: - merchant_center_account_id (int): - Required. The linked `Merchant center account - id `__. - The account must be a standalone account or a sub-account of - a MCA. - branch_id (str): - The branch id (e.g. 0/1/2) within this catalog that products - from merchant_center_account_id are streamed to. When - updating this field, an empty value will use the currently - configured default branch. However, changing the default - branch later on won't change the linked branch here. - - A single branch id can only have one linked merchant center - account id. - destinations (Sequence[str]): - String representing the destination to import for, all if - left empty. List of possible values can be found here. - [https://support.google.com/merchants/answer/7501026] List - of allowed string values: "Shopping_ads", - "Buy_on_google_listings", "Display_ads", "Local_inventory - \_ads", "Free_listings", "Free_local_listings" NOTE: The - string values are case sensitive. - region_code (str): - Region code of offers to accept. 2-letter Uppercase ISO - 3166-1 alpha-2 code. List of values can be found - `here `__ - under the ``region`` tag. If left blank no region filtering - will be performed. - - Example value: ``US``. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. ISO - 639-1. - - This specifies the language of offers in Merchant Center - that will be accepted. If empty no language filtering will - be performed. - - Example value: ``en``. - """ - - merchant_center_account_id = proto.Field( - proto.INT64, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - destinations = proto.RepeatedField( - proto.STRING, - number=3, - ) - region_code = proto.Field( - proto.STRING, - number=4, - ) - language_code = proto.Field( - proto.STRING, - number=5, - ) - - -class MerchantCenterLinkingConfig(proto.Message): - r"""Configures Merchant Center linking. - Links contained in the config will be used to sync data from a - Merchant Center account to a Cloud Retail branch. - - Attributes: - links (Sequence[google.cloud.retail_v2beta.types.MerchantCenterLink]): - Links between Merchant Center accounts and - branches. - """ - - links = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='MerchantCenterLink', - ) - - -class Catalog(proto.Message): - r"""The catalog configuration. - - Attributes: - name (str): - Required. Immutable. The fully qualified - resource name of the catalog. - display_name (str): - Required. Immutable. The catalog display name. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - product_level_config (google.cloud.retail_v2beta.types.ProductLevelConfig): - Required. The product level configuration. - merchant_center_linking_config (google.cloud.retail_v2beta.types.MerchantCenterLinkingConfig): - The Merchant Center linking configuration. - Once a link is added, the data stream from - Merchant Center to Cloud Retail will be enabled - automatically. The requester must have access to - the merchant center account in order to make - changes to this field. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - product_level_config = proto.Field( - proto.MESSAGE, - number=4, - message='ProductLevelConfig', - ) - merchant_center_linking_config = proto.Field( - proto.MESSAGE, - number=6, - message='MerchantCenterLinkingConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py deleted file mode 100644 index c49ba005..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py +++ /dev/null @@ -1,453 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'UpdateCatalogRequest', - 'SetDefaultBranchRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'GetCompletionConfigRequest', - 'UpdateCompletionConfigRequest', - 'GetAttributesConfigRequest', - 'UpdateAttributesConfigRequest', - 'AddCatalogAttributeRequest', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - }, -) - - -class ListCatalogsRequest(proto.Message): - r"""Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - - Attributes: - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2beta.Catalog]s under this - location, regardless of whether or not this location exists, - a PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of - [Catalog][google.cloud.retail.v2beta.Catalog]s to return. If - unspecified, defaults to 50. The maximum allowed value is - 1000. Values above 1000 will be coerced to 1000. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [ListCatalogsResponse.next_page_token][google.cloud.retail.v2beta.ListCatalogsResponse.next_page_token], - received from a previous - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListCatalogsResponse(proto.Message): - r"""Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - - Attributes: - catalogs (Sequence[google.cloud.retail_v2beta.types.Catalog]): - All the customer's - [Catalog][google.cloud.retail.v2beta.Catalog]s. - next_page_token (str): - A token that can be sent as - [ListCatalogsRequest.page_token][google.cloud.retail.v2beta.ListCatalogsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - catalogs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateCatalogRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] - method. - - Attributes: - catalog (google.cloud.retail_v2beta.types.Catalog): - Required. The [Catalog][google.cloud.retail.v2beta.Catalog] - to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2beta.Catalog], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2beta.Catalog] 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 - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - catalog = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class SetDefaultBranchRequest(proto.Message): - r"""Request message to set a specified branch as new default_branch. - - Attributes: - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - branch_id (str): - The final component of the resource name of a branch. - - This field must be one of "0", "1" or "2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If there are no sufficient active products in the targeted - branch and - [force][google.cloud.retail.v2beta.SetDefaultBranchRequest.force] - is not set, a FAILED_PRECONDITION error is returned. - note (str): - Some note on this request, this can be retrieved by - [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch] - before next valid default branch set occurs. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - force (bool): - If set to true, it permits switching to a branch with - [branch_id][google.cloud.retail.v2beta.SetDefaultBranchRequest.branch_id] - even if it has no sufficient active products. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - force = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetDefaultBranchRequest(proto.Message): - r"""Request message to show which branch is currently the default - branch. - - Attributes: - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - - -class GetDefaultBranchResponse(proto.Message): - r"""Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. - - Attributes: - branch (str): - Full resource name of the branch id currently - set as default branch. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when this branch is set to default. - note (str): - This corresponds to - [SetDefaultBranchRequest.note][google.cloud.retail.v2beta.SetDefaultBranchRequest.note] - field, when this branch was set as default. - """ - - branch = proto.Field( - proto.STRING, - number=1, - ) - set_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - - -class GetCompletionConfigRequest(proto.Message): - r"""Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] - method. - - Attributes: - name (str): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateCompletionConfigRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] - method. - - Attributes: - completion_config (google.cloud.retail_v2beta.types.CompletionConfig): - Required. The - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - 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 - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - """ - - completion_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.CompletionConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetAttributesConfigRequest(proto.Message): - r"""Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] - method. - - Attributes: - name (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateAttributesConfigRequest(proto.Message): - r"""Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] - method. - - Attributes: - attributes_config (google.cloud.retail_v2beta.types.AttributesConfig): - Required. The - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - """ - - attributes_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.AttributesConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class AddCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - catalog_attribute (google.cloud.retail_v2beta.types.CatalogAttribute): - Required. The - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - catalog_attribute = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_catalog.CatalogAttribute, - ) - - -class RemoveCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - key (str): - Required. The attribute name key of the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - key = proto.Field( - proto.STRING, - number=2, - ) - - -class ReplaceCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - catalog_attribute (google.cloud.retail_v2beta.types.CatalogAttribute): - Required. The updated - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to update. The following are NOT supported: - - - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key] - - If not set, all supported fields are updated. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - catalog_attribute = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_catalog.CatalogAttribute, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py deleted file mode 100644 index c40843c0..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py +++ /dev/null @@ -1,1178 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'AttributeConfigLevel', - 'SolutionType', - 'SearchSolutionUseCase', - 'Condition', - 'Rule', - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'LocalInventory', - }, -) - - -class AttributeConfigLevel(proto.Enum): - r"""At which level we offer configuration for attributes.""" - ATTRIBUTE_CONFIG_LEVEL_UNSPECIFIED = 0 - PRODUCT_LEVEL_ATTRIBUTE_CONFIG = 1 - CATALOG_LEVEL_ATTRIBUTE_CONFIG = 2 - - -class SolutionType(proto.Enum): - r"""The type of solution.""" - SOLUTION_TYPE_UNSPECIFIED = 0 - SOLUTION_TYPE_RECOMMENDATION = 1 - SOLUTION_TYPE_SEARCH = 2 - - -class SearchSolutionUseCase(proto.Enum): - r"""The use case of Cloud Retail Search.""" - SEARCH_SOLUTION_USE_CASE_UNSPECIFIED = 0 - SEARCH_SOLUTION_USE_CASE_SEARCH = 1 - SEARCH_SOLUTION_USE_CASE_BROWSE = 2 - - -class Condition(proto.Message): - r"""Metadata that is used to define a condition that triggers an action. - A valid condition must specify at least one of 'query_terms' or - 'products_filter'. If multiple fields are specified, the condition - is met if all the fields are satisfied e.g. if a set of query terms - and product_filter are set, then only items matching the - product_filter for requests with a query matching the query terms - wil get boosted. - - Attributes: - query_terms (Sequence[google.cloud.retail_v2beta.types.Condition.QueryTerm]): - A list (up to 10 entries) of terms to match - the query on. If not specified, match all - queries. If many query terms are specified, the - condition is matched if any of the terms is a - match (i.e. using the OR operator). - active_time_range (Sequence[google.cloud.retail_v2beta.types.Condition.TimeRange]): - Range of time(s) specifying when Condition is - active. Condition true if any time range - matches. - """ - - class QueryTerm(proto.Message): - r"""Query terms that we want to match on. - - Attributes: - value (str): - The value of the term to match on. - Value cannot be empty. - Value can have at most 3 terms if specified as a - partial match. Each space separated string is - considered as one term. Example) "a b c" is 3 - terms and allowed, " a b c d" is 4 terms and not - allowed for partial match. - full_match (bool): - Whether this is supposed to be a full or - partial match. - """ - - value = proto.Field( - proto.STRING, - number=1, - ) - full_match = proto.Field( - proto.BOOL, - number=2, - ) - - class TimeRange(proto.Message): - r"""Used for time-dependent conditions. - Example: Want to have rule applied for week long sale. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start of time range. Range is inclusive. - end_time (google.protobuf.timestamp_pb2.Timestamp): - End of time range. Range is inclusive. - """ - - start_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - query_terms = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=QueryTerm, - ) - active_time_range = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=TimeRange, - ) - - -class Rule(proto.Message): - r"""A rule is a condition-action pair - - - A condition defines when a rule is to be triggered. - - An action specifies what occurs on that trigger. Currently only - boost rules are supported. Currently only supported by the search - endpoint. - - 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: - boost_action (google.cloud.retail_v2beta.types.Rule.BoostAction): - A boost action. - - This field is a member of `oneof`_ ``action``. - redirect_action (google.cloud.retail_v2beta.types.Rule.RedirectAction): - Redirects a shopper to a specific page. - - This field is a member of `oneof`_ ``action``. - oneway_synonyms_action (google.cloud.retail_v2beta.types.Rule.OnewaySynonymsAction): - Treats specific term as a synonym with a - group of terms. Group of terms will not be - treated as synonyms with the specific term. - - This field is a member of `oneof`_ ``action``. - do_not_associate_action (google.cloud.retail_v2beta.types.Rule.DoNotAssociateAction): - Prevents term from being associated with - other terms. - - This field is a member of `oneof`_ ``action``. - replacement_action (google.cloud.retail_v2beta.types.Rule.ReplacementAction): - Replaces specific terms in the query. - - This field is a member of `oneof`_ ``action``. - ignore_action (google.cloud.retail_v2beta.types.Rule.IgnoreAction): - Ignores specific terms from query during - search. - - This field is a member of `oneof`_ ``action``. - filter_action (google.cloud.retail_v2beta.types.Rule.FilterAction): - Filters results. - - This field is a member of `oneof`_ ``action``. - twoway_synonyms_action (google.cloud.retail_v2beta.types.Rule.TwowaySynonymsAction): - Treats a set of terms as synonyms of one - another. - - This field is a member of `oneof`_ ``action``. - condition (google.cloud.retail_v2beta.types.Condition): - Required. The condition that triggers the - rule. If the condition is empty, the rule will - always apply. - """ - - class BoostAction(proto.Message): - r"""A boost action to apply to results matching condition - specified above. - - Attributes: - boost (float): - Strength of the condition boost, which must be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - products_filter (str): - The filter can have a max size of 5000 characters. An - expression which specifies which products to apply an action - to. The syntax and supported fields are the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": *(id: - ANY("product_1", "product_2"))* *AND* *(colorFamilies: - ANY("Red", "Blue"))* - """ - - boost = proto.Field( - proto.FLOAT, - number=1, - ) - products_filter = proto.Field( - proto.STRING, - number=2, - ) - - class FilterAction(proto.Message): - r"""- Rule Condition: - - - No [Condition][query_terms] provided is a global match. - - 1 or more [Condition][query_terms] provided is combined with - OR operator. - - - Action Input: The request query and filter that will be applied - to the retrieved products, in addition to any filters already - provided with the SearchRequest. The AND operator is used to - combine the query's existing filters with the filter rule(s). - NOTE: May result in 0 results when filters conflict. - - Action Result: Filters the returned objects to be ONLY those that - passed the filter. - - Attributes: - filter (str): - A filter to apply on the matching condition results. - Supported features: - - - [filter][google.cloud.retail.v2beta.Rule.FilterAction.filter] - must be set. - - Filter syntax is identical to - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter]. - See more details at the Retail Search `user - guide `__. - - To filter products with product ID "product_1" or - "product_2", and color "Red" or "Blue": *(id: - ANY("product_1", "product_2"))* *AND* *(colorFamilies: - ANY("Red", "Blue"))* - """ - - filter = proto.Field( - proto.STRING, - number=1, - ) - - class RedirectAction(proto.Message): - r"""Redirects a shopper to a specific page. - - - Rule Condition: - - - Must specify [Condition][query_terms]. - - - Action Input: Request Query - - Action Result: Redirects shopper to provided uri. - - Attributes: - redirect_uri (str): - URL must have length equal or less than 2000 - characters. - """ - - redirect_uri = proto.Field( - proto.STRING, - number=1, - ) - - class TwowaySynonymsAction(proto.Message): - r"""Creates a set of terms that will be treated as synonyms of each - other. Example: synonyms of "sneakers" and "shoes". - - - "sneakers" will use a synonym of "shoes". - - "shoes" will use a synonym of "sneakers". - - Attributes: - synonyms (Sequence[str]): - Defines a set of synonyms. - Can specify up to 100 synonyms. - Must specify at least 2 synonyms. - """ - - synonyms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class OnewaySynonymsAction(proto.Message): - r"""Maps a set of terms to a set of synonyms. Set of synonyms will be - treated as synonyms of each query term only. ``query_terms`` will - not be treated as synonyms of each other. Example: "sneakers" will - use a synonym of "shoes". "shoes" will not use a synonym of - "sneakers". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. - Will treat synonyms as their synonyms. - Not themselves synonyms of the synonyms. - Can specify up to 100 terms. - synonyms (Sequence[str]): - Defines a set of synonyms. - Cannot contain duplicates. - Can specify up to 100 synonyms. - oneway_terms (Sequence[str]): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=3, - ) - synonyms = proto.RepeatedField( - proto.STRING, - number=4, - ) - oneway_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class DoNotAssociateAction(proto.Message): - r"""Prevents ``query_term`` from being associated with specified terms - during search. Example: Don't associate "gShoe" and "cheap". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. Will not consider - do_not_associate_terms for search if in search query. Can - specify up to 100 terms. - do_not_associate_terms (Sequence[str]): - Cannot contain duplicates or the query term. - Can specify up to 100 terms. - terms (Sequence[str]): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - do_not_associate_terms = proto.RepeatedField( - proto.STRING, - number=3, - ) - terms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class ReplacementAction(proto.Message): - r"""Replaces a term in the query. Multiple replacement candidates can be - specified. All ``query_terms`` will be replaced with the replacement - term. Example: Replace "gShoe" with "google shoe". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. - Will be replaced by replacement term. - Can specify up to 100 terms. - replacement_term (str): - Term that will be used for replacement. - term (str): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - replacement_term = proto.Field( - proto.STRING, - number=3, - ) - term = proto.Field( - proto.STRING, - number=1, - ) - - class IgnoreAction(proto.Message): - r"""Prevents a term in the query from being used in search. - Example: Don't search for "shoddy". - - Attributes: - ignore_terms (Sequence[str]): - Terms to ignore in the search query. - """ - - ignore_terms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - boost_action = proto.Field( - proto.MESSAGE, - number=2, - oneof='action', - message=BoostAction, - ) - redirect_action = proto.Field( - proto.MESSAGE, - number=3, - oneof='action', - message=RedirectAction, - ) - oneway_synonyms_action = proto.Field( - proto.MESSAGE, - number=6, - oneof='action', - message=OnewaySynonymsAction, - ) - do_not_associate_action = proto.Field( - proto.MESSAGE, - number=7, - oneof='action', - message=DoNotAssociateAction, - ) - replacement_action = proto.Field( - proto.MESSAGE, - number=8, - oneof='action', - message=ReplacementAction, - ) - ignore_action = proto.Field( - proto.MESSAGE, - number=9, - oneof='action', - message=IgnoreAction, - ) - filter_action = proto.Field( - proto.MESSAGE, - number=10, - oneof='action', - message=FilterAction, - ) - twoway_synonyms_action = proto.Field( - proto.MESSAGE, - number=11, - oneof='action', - message=TwowaySynonymsAction, - ) - condition = proto.Field( - proto.MESSAGE, - number=1, - message='Condition', - ) - - -class Audience(proto.Message): - r"""An intended audience of the - [Product][google.cloud.retail.v2beta.Product] for whom it's sold. - - Attributes: - genders (Sequence[str]): - The genders of the audience. Strongly encouraged to use the - standard values: "male", "female", "unisex". - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `gender `__. - Schema.org property - `Product.audience.suggestedGender `__. - age_groups (Sequence[str]): - The age groups of the audience. Strongly encouraged to use - the standard values: "newborn" (up to 3 months old), - "infant" (3–12 months old), "toddler" (1–5 years old), - "kids" (5–13 years old), "adult" (typically teens or older). - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `age_group `__. - Schema.org property - `Product.audience.suggestedMinAge `__ - and - `Product.audience.suggestedMaxAge `__. - """ - - genders = proto.RepeatedField( - proto.STRING, - number=1, - ) - age_groups = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class ColorInfo(proto.Message): - r"""The color information of a - [Product][google.cloud.retail.v2beta.Product]. - - Attributes: - color_families (Sequence[str]): - The standard color families. Strongly recommended to use the - following standard color groups: "Red", "Pink", "Orange", - "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", - "White", "Gray", "Black" and "Mixed". Normally it is - expected to have only 1 color family. May consider using - single "Mixed" instead of multiple values. - - A maximum of 5 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - colors (Sequence[str]): - The color display names, which may be different from - standard color family names, such as the color aliases used - in the website frontend. Normally it is expected to have - only 1 color. May consider using single "Mixed" instead of - multiple values. - - A maximum of 25 colors are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - """ - - color_families = proto.RepeatedField( - proto.STRING, - number=1, - ) - colors = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class CustomAttribute(proto.Message): - r"""A custom attribute that is not explicitly modeled in - [Product][google.cloud.retail.v2beta.Product]. - - Attributes: - text (Sequence[str]): - The textual values of this custom attribute. For example, - ``["yellow", "green"]`` when the key is "color". - - Empty string is not allowed. Otherwise, an INVALID_ARGUMENT - error is returned. - - Exactly one of - [text][google.cloud.retail.v2beta.CustomAttribute.text] or - [numbers][google.cloud.retail.v2beta.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - numbers (Sequence[float]): - The numerical values of this custom attribute. For example, - ``[2.3, 15.4]`` when the key is "lengths_cm". - - Exactly one of - [text][google.cloud.retail.v2beta.CustomAttribute.text] or - [numbers][google.cloud.retail.v2beta.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - searchable (bool): - This field will only be used when - [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] - of the [Catalog][google.cloud.retail.v2beta.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are searchable by text queries in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2beta.UserEvent]. - - Only set if type - [text][google.cloud.retail.v2beta.CustomAttribute.text] is - set. Otherwise, a INVALID_ARGUMENT error is returned. - - This field is a member of `oneof`_ ``_searchable``. - indexable (bool): - This field will only be used when - [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] - of the [Catalog][google.cloud.retail.v2beta.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are indexed, so that it can be filtered, faceted or - boosted in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2beta.UserEvent]. - - See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter], - [SearchRequest.facet_specs][google.cloud.retail.v2beta.SearchRequest.facet_specs] - and - [SearchRequest.boost_spec][google.cloud.retail.v2beta.SearchRequest.boost_spec] - for more details. - - This field is a member of `oneof`_ ``_indexable``. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - numbers = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - searchable = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - indexable = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - -class FulfillmentInfo(proto.Message): - r"""Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - Attributes: - type_ (str): - The fulfillment type, including commonly used types (such as - pickup in store and same day delivery), and custom types. - Customers have to map custom types to their display names - before rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - place_ids (Sequence[str]): - The IDs for this - [type][google.cloud.retail.v2beta.FulfillmentInfo.type], - such as the store IDs for - [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2beta.FulfillmentInfo.type] - or the region IDs for - [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2beta.FulfillmentInfo.type]. - - A maximum of 3000 values are allowed. Each value must be a - string with a length limit of 30 characters, matching the - pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". - Otherwise, an INVALID_ARGUMENT error is returned. - """ - - type_ = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class Image(proto.Message): - r"""[Product][google.cloud.retail.v2beta.Product] image. Recommendations - AI and Retail Search do not use product images to improve prediction - and search results. However, product images can be returned in - results, and are shown in prediction or search previews in the - console. - - Attributes: - uri (str): - Required. URI of the image. - - This field must be a valid UTF-8 encoded URI with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - height (int): - Height of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - width (int): - Width of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - height = proto.Field( - proto.INT32, - number=2, - ) - width = proto.Field( - proto.INT32, - number=3, - ) - - -class Interval(proto.Message): - r"""A floating point interval. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - minimum (float): - Inclusive lower bound. - - This field is a member of `oneof`_ ``min``. - exclusive_minimum (float): - Exclusive lower bound. - - This field is a member of `oneof`_ ``min``. - maximum (float): - Inclusive upper bound. - - This field is a member of `oneof`_ ``max``. - exclusive_maximum (float): - Exclusive upper bound. - - This field is a member of `oneof`_ ``max``. - """ - - minimum = proto.Field( - proto.DOUBLE, - number=1, - oneof='min', - ) - exclusive_minimum = proto.Field( - proto.DOUBLE, - number=2, - oneof='min', - ) - maximum = proto.Field( - proto.DOUBLE, - number=3, - oneof='max', - ) - exclusive_maximum = proto.Field( - proto.DOUBLE, - number=4, - oneof='max', - ) - - -class PriceInfo(proto.Message): - r"""The price information of a - [Product][google.cloud.retail.v2beta.Product]. - - Attributes: - currency_code (str): - The 3-letter currency code defined in `ISO - 4217 `__. - - If this field is an unrecognizable currency code, an - INVALID_ARGUMENT error is returned. - - The - [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s with the same - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] - must share the same - [currency_code][google.cloud.retail.v2beta.PriceInfo.currency_code]. - Otherwise, a FAILED_PRECONDITION error is returned. - price (float): - Price of the product. - - Google Merchant Center property - `price `__. - Schema.org property - `Offer.price `__. - original_price (float): - Price of the product without any discount. If zero, by - default set to be the - [price][google.cloud.retail.v2beta.PriceInfo.price]. - cost (float): - The costs associated with the sale of a particular product. - Used for gross profit reporting. - - - Profit = - [price][google.cloud.retail.v2beta.PriceInfo.price] - - [cost][google.cloud.retail.v2beta.PriceInfo.cost] - - Google Merchant Center property - `cost_of_goods_sold `__. - price_effective_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2beta.PriceInfo.price] starts - to be effective. This can be set as a future timestamp, and - the [price][google.cloud.retail.v2beta.PriceInfo.price] is - only used for search after - [price_effective_time][google.cloud.retail.v2beta.PriceInfo.price_effective_time]. - If so, the - [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - is used before - [price_effective_time][google.cloud.retail.v2beta.PriceInfo.price_effective_time]. - - Do not set if - [price][google.cloud.retail.v2beta.PriceInfo.price] is - always effective because it will cause additional latency - during search. - price_expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2beta.PriceInfo.price] stops to - be effective. The - [price][google.cloud.retail.v2beta.PriceInfo.price] is used - for search before - [price_expire_time][google.cloud.retail.v2beta.PriceInfo.price_expire_time]. - If this field is set, the - [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - is used after - [price_expire_time][google.cloud.retail.v2beta.PriceInfo.price_expire_time]. - - Do not set if - [price][google.cloud.retail.v2beta.PriceInfo.price] is - always effective because it will cause additional latency - during search. - price_range (google.cloud.retail_v2beta.types.PriceInfo.PriceRange): - Output only. The price range of all the child - [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s grouped - together on the - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]. Only - populated for - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct]. - Do not set this field in API requests. - """ - - class PriceRange(proto.Message): - r"""The price range of all - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. - - Attributes: - price (google.cloud.retail_v2beta.types.Interval): - The inclusive - [Product.pricing_info.price][google.cloud.retail.v2beta.PriceInfo.price] - interval of all - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] having the - same - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. - original_price (google.cloud.retail_v2beta.types.Interval): - The inclusive - [Product.pricing_info.original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - internal of all - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] having the - same - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. - """ - - price = proto.Field( - proto.MESSAGE, - number=1, - message='Interval', - ) - original_price = proto.Field( - proto.MESSAGE, - number=2, - message='Interval', - ) - - currency_code = proto.Field( - proto.STRING, - number=1, - ) - price = proto.Field( - proto.FLOAT, - number=2, - ) - original_price = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - price_effective_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - price_expire_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - price_range = proto.Field( - proto.MESSAGE, - number=7, - message=PriceRange, - ) - - -class Rating(proto.Message): - r"""The rating of a [Product][google.cloud.retail.v2beta.Product]. - - Attributes: - rating_count (int): - The total number of ratings. This value is independent of - the value of - [rating_histogram][google.cloud.retail.v2beta.Rating.rating_histogram]. - - This value must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - average_rating (float): - The average rating of the - [Product][google.cloud.retail.v2beta.Product]. - - The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT - error is returned. - rating_histogram (Sequence[int]): - List of rating counts per rating value (index = rating - 1). - The list is empty if there is no rating. If the list is - non-empty, its size is always 5. Otherwise, an - INVALID_ARGUMENT error is returned. - - For example, [41, 14, 13, 47, 303]. It means that the - [Product][google.cloud.retail.v2beta.Product] got 41 ratings - with 1 star, 14 ratings with 2 star, and so on. - """ - - rating_count = proto.Field( - proto.INT32, - number=1, - ) - average_rating = proto.Field( - proto.FLOAT, - number=2, - ) - rating_histogram = proto.RepeatedField( - proto.INT32, - number=3, - ) - - -class UserInfo(proto.Message): - r"""Information of an end user. - - Attributes: - user_id (str): - Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. - - Always use a hashed value for this ID. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - ip_address (str): - The end user's IP address. This field is used to extract - location information for personalization. - - This field must be either an IPv4 address (e.g. - "104.133.9.80") or an IPv6 address (e.g. - "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an - INVALID_ARGUMENT error is returned. - - This should not be set when: - - - setting - [SearchRequest.user_info][google.cloud.retail.v2beta.SearchRequest.user_info]. - - using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2beta.UserInfo.direct_user_request] - is set. - user_agent (str): - User agent as included in the HTTP header. Required for - getting - [SearchResponse.sponsored_results][google.cloud.retail.v2beta.SearchResponse.sponsored_results]. - - The field must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This should not be set when using the client side event - reporting with GTM or JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2beta.UserInfo.direct_user_request] - is set. - direct_user_request (bool): - True if the request is made directly from the end user, in - which case the - [ip_address][google.cloud.retail.v2beta.UserInfo.ip_address] - and - [user_agent][google.cloud.retail.v2beta.UserInfo.user_agent] - can be populated from the HTTP request. This flag should be - set only if the API request is made directly from the end - user such as a mobile app (and not if a gateway or a server - is processing and pushing the user events). - - This should not be set when using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent]. - """ - - user_id = proto.Field( - proto.STRING, - number=1, - ) - ip_address = proto.Field( - proto.STRING, - number=2, - ) - user_agent = proto.Field( - proto.STRING, - number=3, - ) - direct_user_request = proto.Field( - proto.BOOL, - number=4, - ) - - -class LocalInventory(proto.Message): - r"""The inventory information at a place (e.g. a store) - identified by a place ID. - - Attributes: - place_id (str): - The place ID for the current set of inventory - information. - price_info (google.cloud.retail_v2beta.types.PriceInfo): - Product price and cost information. - - Google Merchant Center property - `price `__. - attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): - Additional local inventory attributes, for example, store - name, promotion tags, etc. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - At most 30 attributes are allowed. - - The key must be a UTF-8 encoded string with a length - limit of 32 characters. - - The key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis - or KEY_1_LIKE_THIS. - - The attribute values must be of the same type (text or - number). - - Only 1 value is allowed for each attribute. - - For text values, the length limit is 256 UTF-8 - characters. - - The attribute does not support search. The ``searchable`` - field should be unset or set to false. - - The max summed total bytes of custom attribute keys and - values per product is 5MiB. - fulfillment_types (Sequence[str]): - Input only. Supported fulfillment types. Valid fulfillment - type values include commonly used types (such as pickup in - store and same day delivery), and custom types. Customers - have to map custom types to their display names before - rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - All the elements must be distinct. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - place_id = proto.Field( - proto.STRING, - number=1, - ) - price_info = proto.Field( - proto.MESSAGE, - number=2, - message='PriceInfo', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='CustomAttribute', - ) - fulfillment_types = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py deleted file mode 100644 index 47e39772..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'CompleteQueryRequest', - 'CompleteQueryResponse', - }, -) - - -class CompleteQueryRequest(proto.Message): - r"""Auto-complete parameters. - - Attributes: - catalog (str): - Required. Catalog for which the completion is performed. - - Full resource name of catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - query (str): - Required. The query used to generate - suggestions. - The maximum number of allowed characters is 255. - visitor_id (str): - Required field. A unique identifier for tracking visitors. - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - language_codes (Sequence[str]): - The language filters applied to the output suggestions. If - set, it should contain the language of the query. If not - set, suggestions are returned without considering language - restrictions. This is the BCP-47 language code, such as - "en-US" or "sr-Latn". For more information, see `Tags for - Identifying - Languages `__. The - maximum number of language codes is 3. - device_type (str): - The device type context for completion suggestions. It is - useful to apply different suggestions on different device - types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the - suggestions are across all device types. - - Supported formats: - - - ``UNKNOWN_DEVICE_TYPE`` - - - ``DESKTOP`` - - - ``MOBILE`` - - - A customized string starts with ``OTHER_``, e.g. - ``OTHER_IPHONE``. - dataset (str): - Determines which dataset to use for fetching completion. - "user-data" will use the imported dataset through - [CompletionService.ImportCompletionData][google.cloud.retail.v2beta.CompletionService.ImportCompletionData]. - "cloud-retail" will use the dataset generated by cloud - retail based on user events. If leave empty, it will use the - "user-data". - - Current supported values: - - - user-data - - - cloud-retail This option requires additional - allowlisting. Before using cloud-retail, contact Cloud - Retail support team first. - max_suggestions (int): - Completion max suggestions. If left unset or set to 0, then - will fallback to the configured value - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions]. - - The maximum allowed max suggestions is 20. If it is set - higher, it will be capped by 20. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - visitor_id = proto.Field( - proto.STRING, - number=7, - ) - language_codes = proto.RepeatedField( - proto.STRING, - number=3, - ) - device_type = proto.Field( - proto.STRING, - number=4, - ) - dataset = proto.Field( - proto.STRING, - number=6, - ) - max_suggestions = proto.Field( - proto.INT32, - number=5, - ) - - -class CompleteQueryResponse(proto.Message): - r"""Response of the auto-complete query. - - Attributes: - completion_results (Sequence[google.cloud.retail_v2beta.types.CompleteQueryResponse.CompletionResult]): - Results of the matching suggestions. The - result list is ordered and the first result is - top suggestion. - attribution_token (str): - A unique complete token. This should be included in the - [UserEvent.completion_detail][google.cloud.retail.v2beta.UserEvent.completion_detail] - for search events resulting from this completion, which - enables accurate attribution of complete model performance. - recent_search_results (Sequence[google.cloud.retail_v2beta.types.CompleteQueryResponse.RecentSearchResult]): - Matched recent searches of this user. The maximum number of - recent searches is 10. This field is a restricted feature. - Contact Retail Search support team if you are interested in - enabling it. - - This feature is only available when - [CompleteQueryRequest.visitor_id][google.cloud.retail.v2beta.CompleteQueryRequest.visitor_id] - field is set and - [UserEvent][google.cloud.retail.v2beta.UserEvent] is - imported. The recent searches satisfy the follow rules: - - - They are ordered from latest to oldest. - - They are matched with - [CompleteQueryRequest.query][google.cloud.retail.v2beta.CompleteQueryRequest.query] - case insensitively. - - They are transformed to lower cases. - - They are UTF-8 safe. - - Recent searches are deduplicated. More recent searches will - be reserved when duplication happens. - """ - - class CompletionResult(proto.Message): - r"""Resource that represents completion results. - - Attributes: - suggestion (str): - The suggestion for the query. - attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): - Custom attributes for the suggestion term. - - - For "user-data", the attributes are additional custom - attributes ingested through BigQuery. - - For "cloud-retail", the attributes are product attributes - generated by Cloud Retail. - """ - - suggestion = proto.Field( - proto.STRING, - number=1, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=common.CustomAttribute, - ) - - class RecentSearchResult(proto.Message): - r"""Recent search of this user. - - Attributes: - recent_search (str): - The recent search query. - """ - - recent_search = proto.Field( - proto.STRING, - number=1, - ) - - completion_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=CompletionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - recent_search_results = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=RecentSearchResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py deleted file mode 100644 index 0c7cdc3d..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'Control', - }, -) - - -class Control(proto.Message): - r"""Configures dynamic serving time metadata that is used to pre - and post process search/recommendation model results. - - 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: - facet_spec (google.cloud.retail_v2beta.types.SearchRequest.FacetSpec): - A facet specification to perform faceted - search. - - This field is a member of `oneof`_ ``control``. - rule (google.cloud.retail_v2beta.types.Rule): - A rule control - a condition-action pair. - Enacts a set action when the condition is - triggered. For example: Boost "gShoe" when query - full matches "Running Shoes". - - This field is a member of `oneof`_ ``control``. - name (str): - Immutable. Fully qualified name - projects/\ */locations/global/catalogs/*/controls/\* - display_name (str): - Required. The human readable control display name. Used in - Retail UI. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is thrown. - associated_serving_config_ids (Sequence[str]): - Output only. List of serving configuration - ids that that are associated with this control. - Note the association is managed via the - ServingConfig, this is an output only - denormalizeed view. Assumed to be in the same - catalog. - solution_types (Sequence[google.cloud.retail_v2beta.types.SolutionType]): - Required. Immutable. The solution types that the serving - config is used for. Currently we support setting only one - type of solution at creation time. - - Only ``SOLUTION_TYPE_SEARCH`` value is supported at the - moment. If no solution type is provided at creation time, - will default to SOLUTION_TYPE_SEARCH. - """ - - facet_spec = proto.Field( - proto.MESSAGE, - number=3, - oneof='control', - message=search_service.SearchRequest.FacetSpec, - ) - rule = proto.Field( - proto.MESSAGE, - number=4, - oneof='control', - message=common.Rule, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - associated_serving_config_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - solution_types = proto.RepeatedField( - proto.ENUM, - number=6, - enum=common.SolutionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py deleted file mode 100644 index 17120bb5..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py +++ /dev/null @@ -1,197 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import control as gcr_control -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'CreateControlRequest', - 'UpdateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - }, -) - - -class CreateControlRequest(proto.Message): - r"""Request for CreateControl method. - - Attributes: - parent (str): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - control (google.cloud.retail_v2beta.types.Control): - Required. The Control to create. - control_id (str): - Required. The ID to use for the Control, which will become - the final component of the Control's resource name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-_/. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - control = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_control.Control, - ) - control_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateControlRequest(proto.Message): - r"""Request for UpdateControl method. - - Attributes: - control (google.cloud.retail_v2beta.types.Control): - Required. The Control to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Control][google.cloud.retail.v2beta.Control] to update. The - following are NOT supported: - - - [Control.name][google.cloud.retail.v2beta.Control.name] - - If not set or empty, all supported fields are updated. - """ - - control = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_control.Control, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteControlRequest(proto.Message): - r"""Request for DeleteControl method. - - Attributes: - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetControlRequest(proto.Message): - r"""Request for GetControl method. - - Attributes: - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListControlsRequest(proto.Message): - r"""Request for ListControls method. - - Attributes: - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - page_size (int): - Optional. Maximum number of results to - return. If unspecified, defaults to 50. Max - allowed value is 1000. - page_token (str): - Optional. A page token, received from a previous - ``ListControls`` call. Provide this to retrieve the - subsequent page. - filter (str): - Optional. A filter to apply on the list results. Supported - features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2beta.ListControlsRequest.filter] - is unset. - - List controls that are used in a single ServingConfig: - 'serving_config = "boosted_home_page_cvr"' - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListControlsResponse(proto.Message): - r"""Response for ListControls method. - - Attributes: - controls (Sequence[google.cloud.retail_v2beta.types.Control]): - All the Controls for a given catalog. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - controls = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_control.Control, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py deleted file mode 100644 index b020964a..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py +++ /dev/null @@ -1,134 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - }, -) - - -class ExportErrorsConfig(proto.Message): - r"""Configuration of destination for Export related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage path for import errors. This must be an - empty, existing Cloud Storage bucket. Export errors will be - written to a file in this bucket, one per line, as a - JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ExportMetadata(proto.Message): - r"""Metadata related to the progress of the Export operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class ExportProductsResponse(proto.Message): - r"""Response of the ExportProductsRequest. If the long running - operation is done, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2beta.types.ExportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExportErrorsConfig', - ) - - -class ExportUserEventsResponse(proto.Message): - r"""Response of the ExportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2beta.types.ExportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExportErrorsConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py deleted file mode 100644 index a32de943..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py +++ /dev/null @@ -1,691 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import user_event -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'GcsSource', - 'BigQuerySource', - 'ProductInlineSource', - 'UserEventInlineSource', - 'ImportErrorsConfig', - 'ImportProductsRequest', - 'ImportUserEventsRequest', - 'ImportCompletionDataRequest', - 'ProductInputConfig', - 'UserEventInputConfig', - 'CompletionDataInputConfig', - 'ImportMetadata', - 'ImportProductsResponse', - 'ImportUserEventsResponse', - 'UserEventImportSummary', - 'ImportCompletionDataResponse', - }, -) - - -class GcsSource(proto.Message): - r"""Google Cloud Storage location for input content. - format. - - Attributes: - input_uris (Sequence[str]): - Required. Google Cloud Storage URIs to input files. URI can - be up to 2000 characters long. URIs can match the full - object path (for example, - ``gs://bucket/directory/object.json``) or a pattern matching - one or more files, such as ``gs://bucket/directory/*.json``. - A request can contain at most 100 files, and each file can - be up to 2 GB. See `Importing product - information `__ - for the expected file format and setup instructions. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2beta.Product] per line. - Each product must have a valid - [Product.id][google.cloud.retail.v2beta.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2beta.UserEvent] per - line. - - ``user_event_ga360``: Using - https://support.google.com/analytics/answer/3437719. - - Supported values for control imports: - - - 'control' (default): One JSON - [Control][google.cloud.retail.v2beta.Control] per line. - - Supported values for catalog attribute imports: - - - 'catalog_attribute' (default): One CSV - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - per line. - """ - - input_uris = proto.RepeatedField( - proto.STRING, - number=1, - ) - data_schema = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""BigQuery source import data from. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - partition_date (google.type.date_pb2.Date): - BigQuery time partitioned table's \_PARTITIONDATE in - YYYY-MM-DD format. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2beta.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - - This field is a member of `oneof`_ ``partition``. - project_id (str): - The project ID (can be project # or ID) that - the BigQuery source is in with a length limit of - 128 characters. If not specified, inherits the - project ID from the parent request. - dataset_id (str): - Required. The BigQuery data set to copy the - data from with a length limit of 1,024 - characters. - table_id (str): - Required. The BigQuery table to copy the data - from with a length limit of 1,024 characters. - gcs_staging_dir (str): - Intermediate Cloud Storage directory used for - the import with a length limit of 2,000 - characters. Can be specified if one wants to - have the BigQuery export to a specific Cloud - Storage directory. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2beta.Product] per line. - Each product must have a valid - [Product.id][google.cloud.retail.v2beta.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2beta.UserEvent] per - line. - - ``user_event_ga360``: The schema is available here: - https://support.google.com/analytics/answer/3437719. - - ``user_event_ga4``: This feature is in private preview. - Please contact the support team for importing Google - Analytics 4 events. The schema is available here: - https://support.google.com/analytics/answer/7029846. - - Supported values for auto-completion imports: - - - ``suggestions`` (default): One JSON completion suggestion - per line. - - ``denylist``: One JSON deny suggestion per line. - - ``allowlist``: One JSON allow suggestion per line. - """ - - partition_date = proto.Field( - proto.MESSAGE, - number=6, - oneof='partition', - message=date_pb2.Date, - ) - project_id = proto.Field( - proto.STRING, - number=5, - ) - dataset_id = proto.Field( - proto.STRING, - number=1, - ) - table_id = proto.Field( - proto.STRING, - number=2, - ) - gcs_staging_dir = proto.Field( - proto.STRING, - number=3, - ) - data_schema = proto.Field( - proto.STRING, - number=4, - ) - - -class ProductInlineSource(proto.Message): - r"""The inline source for the input config for ImportProducts - method. - - Attributes: - products (Sequence[google.cloud.retail_v2beta.types.Product]): - Required. A list of products to update/create. Each product - must have a valid - [Product.id][google.cloud.retail.v2beta.Product.id]. - Recommended max of 100 items. - """ - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=product.Product, - ) - - -class UserEventInlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (Sequence[google.cloud.retail_v2beta.types.UserEvent]): - Required. A list of user events to import. - Recommended max of 10k items. - """ - - user_events = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - -class ImportErrorsConfig(proto.Message): - r"""Configuration of destination for Import related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage prefix for import errors. This must be - an empty, existing Cloud Storage directory. Import errors - will be written to sharded files in this directory, one per - line, as a JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportProductsRequest(proto.Message): - r"""Request message for Import methods. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` - - If no updateMask is specified, requires products.create - permission. If updateMask is specified, requires - products.update permission. - request_id (str): - Deprecated. This field has no effect. - input_config (google.cloud.retail_v2beta.types.ProductInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - imported 'products' to update. If not set, will - by default update all fields. - reconciliation_mode (google.cloud.retail_v2beta.types.ImportProductsRequest.ReconciliationMode): - The mode of reconciliation between existing products and the - products to be imported. Defaults to - [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2beta.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2beta.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - """ - class ReconciliationMode(proto.Enum): - r"""Indicates how imported products are reconciled with the - existing products created or imported before. - """ - RECONCILIATION_MODE_UNSPECIFIED = 0 - INCREMENTAL = 1 - FULL = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - request_id = proto.Field( - proto.STRING, - number=6, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='ProductInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - reconciliation_mode = proto.Field( - proto.ENUM, - number=5, - enum=ReconciliationMode, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=7, - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog`` - input_config (google.cloud.retail_v2beta.types.UserEventInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. Cannot be set for inline user - event imports. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='UserEventInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - - -class ImportCompletionDataRequest(proto.Message): - r"""Request message for ImportCompletionData methods. - - Attributes: - parent (str): - Required. The catalog which the suggestions dataset belongs - to. - - Format: - ``projects/1234/locations/global/catalogs/default_catalog``. - input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): - Required. The desired input location of the - data. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='CompletionDataInputConfig', - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=3, - ) - - -class ProductInputConfig(proto.Message): - r"""The input config source for products. - - 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: - product_inline_source (google.cloud.retail_v2beta.types.ProductInlineSource): - The Inline source for the input content for - products. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2beta.types.GcsSource): - Google Cloud Storage location for the input - content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - product_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='ProductInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class UserEventInputConfig(proto.Message): - r"""The input config source for user events. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - user_event_inline_source (google.cloud.retail_v2beta.types.UserEventInlineSource): - Required. The Inline source for the input - content for UserEvents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2beta.types.GcsSource): - Required. Google Cloud Storage location for - the input content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): - Required. BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - user_event_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='UserEventInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class CompletionDataInputConfig(proto.Message): - r"""The input config source for completion data. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): - Required. BigQuery input source. - Add the IAM permission "BigQuery Data Viewer" - for - cloud-retail-customer-data-access@system.gserviceaccount.com - before using this feature otherwise an error is - thrown. - - This field is a member of `oneof`_ ``source``. - """ - - big_query_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='BigQuerySource', - ) - - -class ImportMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - request_id (str): - Deprecated. This field is never set. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=3, - ) - failure_count = proto.Field( - proto.INT64, - number=4, - ) - request_id = proto.Field( - proto.STRING, - number=5, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=6, - ) - - -class ImportProductsResponse(proto.Message): - r"""Response of the - [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. - If the long running operation is done, then this message is returned - by the google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - import_summary (google.cloud.retail_v2beta.types.UserEventImportSummary): - Aggregated statistics of user event import - status. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - import_summary = proto.Field( - proto.MESSAGE, - number=3, - message='UserEventImportSummary', - ) - - -class UserEventImportSummary(proto.Message): - r"""A summary of import result. The UserEventImportSummary - summarizes the import status for user events. - - Attributes: - joined_events_count (int): - Count of user events imported with complete - existing catalog information. - unjoined_events_count (int): - Count of user events imported, but with - catalog information not found in the imported - catalog. - """ - - joined_events_count = proto.Field( - proto.INT64, - number=1, - ) - unjoined_events_count = proto.Field( - proto.INT64, - number=2, - ) - - -class ImportCompletionDataResponse(proto.Message): - r"""Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. - 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 (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py deleted file mode 100644 index f31ba819..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import user_event as gcr_user_event -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'PredictRequest', - 'PredictResponse', - }, -) - - -class PredictRequest(proto.Message): - r"""Request message for Predict method. - - Attributes: - placement (str): - Required. Full resource name of the format: - {name=projects/*/locations/global/catalogs/default_catalog/placements/*} - The ID of the Recommendations AI placement. Before you can - request predictions from your model, you must create at - least one placement for it. For more information, see - `Managing - placements `__. - - The full list of available placements can be seen at - https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements - user_event (google.cloud.retail_v2beta.types.UserEvent): - Required. Context about the user, what they - are looking at and what action they took to - trigger the predict request. Note that this user - event detail won't be ingested to userEvent - logs. Thus, a separate userEvent write request - is required for event logging. - page_size (int): - Maximum number of results to return per page. - Set this property to the number of prediction - results needed. If zero, the service will choose - a reasonable default. The maximum allowed value - is 100. Values above 100 will be coerced to 100. - page_token (str): - The previous PredictResponse.next_page_token. - filter (str): - Filter for restricting prediction results with a length - limit of 5,000 characters. Accepts values for tags and the - ``filterOutOfStockItems`` flag. - - - Tag expressions. Restricts predictions to products that - match all of the specified tags. Boolean operators ``OR`` - and ``NOT`` are supported if the expression is enclosed - in parentheses, and must be separated from the tag values - by a space. ``-"tagA"`` is also supported and is - equivalent to ``NOT "tagA"``. Tag values must be double - quoted UTF-8 encoded strings with a size limit of 1,000 - characters. - - Note: "Recently viewed" models don't support tag - filtering at the moment. - - - filterOutOfStockItems. Restricts predictions to products - that do not have a stockState value of OUT_OF_STOCK. - - Examples: - - - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT - "promotional") - - filterOutOfStockItems tag=(-"promotional") - - filterOutOfStockItems - - If your filter blocks all prediction results, the API will - return generic (unfiltered) popular products. If you only - want results strictly matching the filters, set - ``strictFiltering`` to True in ``PredictRequest.params`` to - receive empty results instead. Note that the API will never - return items with storageStatus of "EXPIRED" or "DELETED" - regardless of filter choices. - validate_only (bool): - Use validate only mode for this prediction - query. If set to true, a dummy model will be - used that returns arbitrary products. Note that - the validate only mode should only be used for - testing the API, or if the model is not ready. - params (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional domain specific parameters for the predictions. - - Allowed values: - - - ``returnProduct``: Boolean. If set to true, the - associated product object will be returned in the - ``results.metadata`` field in the prediction response. - - ``returnScore``: Boolean. If set to true, the prediction - 'score' corresponding to each returned product will be - set in the ``results.metadata`` field in the prediction - response. The given 'score' indicates the probability of - an product being clicked/purchased given the user's - context and history. - - ``strictFiltering``: Boolean. True by default. If set to - false, the service will return generic (unfiltered) - popular products instead of empty if your filter blocks - all prediction results. - - ``priceRerankLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of - {'no-price-reranking', 'low-price-reranking', - 'medium-price-reranking', 'high-price-reranking'}. This - gives request-level control and adjusts prediction - results based on product price. - - ``diversityLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of {'no-diversity', - 'low-diversity', 'medium-diversity', 'high-diversity', - 'auto-diversity'}. This gives request-level control and - adjusts prediction results based on product category. - labels (Mapping[str, str]): - The labels applied to a resource must meet the following - requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters, and cannot be empty. Values can - be empty, and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - """ - - placement = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - validate_only = proto.Field( - proto.BOOL, - number=6, - ) - params = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class PredictResponse(proto.Message): - r"""Response message for predict method. - - Attributes: - results (Sequence[google.cloud.retail_v2beta.types.PredictResponse.PredictionResult]): - A list of recommended products. The order - represents the ranking (from the most relevant - product to the least). - attribution_token (str): - A unique attribution token. This should be included in the - [UserEvent][google.cloud.retail.v2beta.UserEvent] logs - resulting from this recommendation, which enables accurate - attribution of recommendation model performance. - missing_ids (Sequence[str]): - IDs of products in the request that were - missing from the inventory. - validate_only (bool): - True if the validateOnly property was set in - the request. - """ - - class PredictionResult(proto.Message): - r"""PredictionResult represents the recommendation prediction - results. - - Attributes: - id (str): - ID of the recommended product - metadata (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional product metadata / annotations. - - Possible values: - - - ``product``: JSON representation of the product. Will be - set if ``returnProduct`` is set to true in - ``PredictRequest.params``. - - ``score``: Prediction score in double value. Will be set - if ``returnScore`` is set to true in - ``PredictRequest.params``. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - metadata = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=PredictionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - missing_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py deleted file mode 100644 index bd0de773..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py +++ /dev/null @@ -1,705 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'Product', - }, -) - - -class Product(proto.Message): - r"""Product captures all metadata information of items to be - recommended or searched. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this product becomes unavailable for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - If it is set, the - [Product][google.cloud.retail.v2beta.Product] is not - available for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - after - [expire_time][google.cloud.retail.v2beta.Product.expire_time]. - However, the product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - [expire_time][google.cloud.retail.v2beta.Product.expire_time] - must be later than - [available_time][google.cloud.retail.v2beta.Product.available_time] - and - [publish_time][google.cloud.retail.v2beta.Product.publish_time], - otherwise an INVALID_ARGUMENT error is thrown. - - Corresponding properties: Google Merchant Center property - `expiration_date `__. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Input only. The TTL (time to live) of the product. - - If it is set, it must be a non-negative value, and - [expire_time][google.cloud.retail.v2beta.Product.expire_time] - is set as current timestamp plus - [ttl][google.cloud.retail.v2beta.Product.ttl]. The derived - [expire_time][google.cloud.retail.v2beta.Product.expire_time] - is returned in the output and - [ttl][google.cloud.retail.v2beta.Product.ttl] is left blank - when retrieving the - [Product][google.cloud.retail.v2beta.Product]. - - If it is set, the product is not available for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - after current timestamp plus - [ttl][google.cloud.retail.v2beta.Product.ttl]. However, the - product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This field is a member of `oneof`_ ``expiration``. - name (str): - Immutable. Full resource name of the product, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. - id (str): - Immutable. [Product][google.cloud.retail.v2beta.Product] - identifier, which is the final component of - [name][google.cloud.retail.v2beta.Product.name]. For - example, this field is "id_1", if - [name][google.cloud.retail.v2beta.Product.name] is - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `id `__. - Schema.org property - `Product.sku `__. - type_ (google.cloud.retail_v2beta.types.Product.Type): - Immutable. The type of the product. Default to - [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2beta.ProductLevelConfig.ingestion_product_type] - if unset. - primary_product_id (str): - Variant group identifier. Must be an - [id][google.cloud.retail.v2beta.Product.id], with the same - parent branch with this product. Otherwise, an error is - thrown. - - For - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]s, this field - can only be empty or set to the same value as - [id][google.cloud.retail.v2beta.Product.id]. - - For VARIANT [Product][google.cloud.retail.v2beta.Product]s, - this field cannot be empty. A maximum of 2,000 products are - allowed to share the same - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `item_group_id `__. - Schema.org property - `Product.inProductGroupWithID `__. - collection_member_ids (Sequence[str]): - The [id][google.cloud.retail.v2beta.Product.id] of the - collection members when - [type][google.cloud.retail.v2beta.Product.type] is - [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION]. - - Non-existent product ids are allowed. The - [type][google.cloud.retail.v2beta.Product.type] of the - members must be either - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - or - [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - otherwise and INVALID_ARGUMENT error is thrown. Should not - set it for other types. A maximum of 1000 values are - allowed. Otherwise, an INVALID_ARGUMENT error is return. - gtin (str): - The Global Trade Item Number (GTIN) of the product. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This field must be a Unigram. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `gtin `__. - Schema.org property - `Product.isbn `__, - `Product.gtin8 `__, - `Product.gtin12 `__, - `Product.gtin13 `__, or - `Product.gtin14 `__. - - If the value is not a valid GTIN, an INVALID_ARGUMENT error - is returned. - categories (Sequence[str]): - Product categories. This field is repeated for supporting - one product belonging to several parallel categories. - Strongly recommended using the full path for better search / - recommendation quality. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - For example, if a shoes product belongs to both ["Shoes & - Accessories" -> "Shoes"] and ["Sports & Fitness" -> - "Athletic Clothing" -> "Shoes"], it could be represented as: - - :: - - "categories": [ - "Shoes & Accessories > Shoes", - "Sports & Fitness > Athletic Clothing > Shoes" - ] - - Must be set for - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] otherwise an - INVALID_ARGUMENT error is returned. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2beta.Product]. Empty values - are not allowed. Each value must be a UTF-8 encoded string - with a length limit of 5,000 characters. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `google_product_category `__. - Schema.org property [Product.category] - (https://schema.org/category). - title (str): - Required. Product title. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `title `__. - Schema.org property - `Product.name `__. - brands (Sequence[str]): - The brands of the product. - - A maximum of 30 brands are allowed. Each brand must be a - UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `brand `__. - Schema.org property - `Product.brand `__. - description (str): - Product description. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `description `__. - Schema.org property - `Product.description `__. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. - - For product prediction, this field is ignored and the model - automatically detects the text language. The - [Product][google.cloud.retail.v2beta.Product] can include - text in different languages, but duplicating - [Product][google.cloud.retail.v2beta.Product]s to provide - text in multiple languages can result in degraded model - performance. - - For product search this field is in use. It defaults to - "en-US" if unset. - attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): - Highly encouraged. Extra product attributes to be included. - For example, for products, this could include the store - name, vendor, style, color, etc. These are very strong - signals for recommendation model, thus we highly recommend - providing the attributes here. - - Features that can take on one of a limited number of - possible values. Two types of features can be set are: - - Textual features. some examples would be the brand/maker of - a product, or country of a customer. Numerical features. - Some examples would be the height/weight of a product, or - age of a customer. - - For example: - ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - Max entries count: 200. - - The key must be a UTF-8 encoded string with a length - limit of 128 characters. - - For indexable attribute, the key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, - ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a - non-empty UTF-8 encoded string with a length limit of 256 - characters. - - For number attributes, at most 400 values are allowed. - tags (Sequence[str]): - Custom tags associated with the product. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2beta.Product]. This value - must be a UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This tag can be used for filtering recommendation results by - passing the tag as part of the - [PredictRequest.filter][google.cloud.retail.v2beta.PredictRequest.filter]. - - Corresponding properties: Google Merchant Center property - `custom_label_0–4 `__. - price_info (google.cloud.retail_v2beta.types.PriceInfo): - Product price and cost information. - - Corresponding properties: Google Merchant Center property - `price `__. - rating (google.cloud.retail_v2beta.types.Rating): - The rating of this product. - available_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this - [Product][google.cloud.retail.v2beta.Product] becomes - available for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - availability (google.cloud.retail_v2beta.types.Product.Availability): - The online availability of the - [Product][google.cloud.retail.v2beta.Product]. Default to - [Availability.IN_STOCK][google.cloud.retail.v2beta.Product.Availability.IN_STOCK]. - - Corresponding properties: Google Merchant Center property - `availability `__. - Schema.org property - `Offer.availability `__. - available_quantity (google.protobuf.wrappers_pb2.Int32Value): - The available quantity of the item. - fulfillment_info (Sequence[google.cloud.retail_v2beta.types.FulfillmentInfo]): - Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - All the elements must have distinct - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type]. - Otherwise, an INVALID_ARGUMENT error is returned. - uri (str): - Canonical URL directly linking to the product detail page. - - It is strongly recommended to provide a valid uri for the - product, otherwise the service performance could be - significantly degraded. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `link `__. - Schema.org property `Offer.url `__. - images (Sequence[google.cloud.retail_v2beta.types.Image]): - Product images for the product. We highly recommend putting - the main image first. - - A maximum of 300 images are allowed. - - Corresponding properties: Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - audience (google.cloud.retail_v2beta.types.Audience): - The target group associated with a given - audience (e.g. male, veterans, car owners, - musicians, etc.) of the product. - color_info (google.cloud.retail_v2beta.types.ColorInfo): - The color of the product. - - Corresponding properties: Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - sizes (Sequence[str]): - The size of the product. To represent different size systems - or size types, consider using this format: - [[[size_system:]size_type:]size_value]. - - For example, in "US:MENS:M", "US" represents size system; - "MENS" represents size type; "M" represents size value. In - "GIRLS:27", size system is empty; "GIRLS" represents size - type; "27" represents size value. In "32 inches", both size - system and size type are empty, while size value is "32 - inches". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2beta.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `size `__, - `size_type `__, - and - `size_system `__. - Schema.org property - `Product.size `__. - materials (Sequence[str]): - The material of the product. For example, "leather", - "wooden". - - A maximum of 20 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 200 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `material `__. - Schema.org property - `Product.material `__. - patterns (Sequence[str]): - The pattern or graphic print of the product. For example, - "striped", "polka dot", "paisley". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2beta.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `pattern `__. - Schema.org property - `Product.pattern `__. - conditions (Sequence[str]): - The condition of the product. Strongly encouraged to use the - standard values: "new", "refurbished", "used". - - A maximum of 1 value is allowed per - [Product][google.cloud.retail.v2beta.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `condition `__. - Schema.org property - `Offer.itemCondition `__. - promotions (Sequence[google.cloud.retail_v2beta.types.Promotion]): - The promotions applied to the product. A maximum of 10 - values are allowed per - [Product][google.cloud.retail.v2beta.Product]. Only - [Promotion.promotion_id][google.cloud.retail.v2beta.Promotion.promotion_id] - will be used, other fields will be ignored if set. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the product is published by the retailer - for the first time, which indicates the freshness of the - products. Note that this field is different from - [available_time][google.cloud.retail.v2beta.Product.available_time], - given it purely describes product freshness regardless of - when it is available on search and recommendation. - retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the - [Product][google.cloud.retail.v2beta.Product]s are returned - in - [SearchResponse][google.cloud.retail.v2beta.SearchResponse]. - - Supported fields for all - [type][google.cloud.retail.v2beta.Product.type]s: - - - [audience][google.cloud.retail.v2beta.Product.audience] - - [availability][google.cloud.retail.v2beta.Product.availability] - - [brands][google.cloud.retail.v2beta.Product.brands] - - [color_info][google.cloud.retail.v2beta.Product.color_info] - - [conditions][google.cloud.retail.v2beta.Product.conditions] - - [gtin][google.cloud.retail.v2beta.Product.gtin] - - [materials][google.cloud.retail.v2beta.Product.materials] - - [name][google.cloud.retail.v2beta.Product.name] - - [patterns][google.cloud.retail.v2beta.Product.patterns] - - [price_info][google.cloud.retail.v2beta.Product.price_info] - - [rating][google.cloud.retail.v2beta.Product.rating] - - [sizes][google.cloud.retail.v2beta.Product.sizes] - - [title][google.cloud.retail.v2beta.Product.title] - - [uri][google.cloud.retail.v2beta.Product.uri] - - Supported fields only for - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION]: - - - [categories][google.cloud.retail.v2beta.Product.categories] - - [description][google.cloud.retail.v2beta.Product.description] - - [images][google.cloud.retail.v2beta.Product.images] - - Supported fields only for - [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT]: - - - Only the first image in - [images][google.cloud.retail.v2beta.Product.images] - - To mark - [attributes][google.cloud.retail.v2beta.Product.attributes] - as retrievable, include paths of the form "attributes.key" - where "key" is the key of a custom attribute, as specified - in - [attributes][google.cloud.retail.v2beta.Product.attributes]. - - For - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION], - the following fields are always returned in - [SearchResponse][google.cloud.retail.v2beta.SearchResponse] - by default: - - - [name][google.cloud.retail.v2beta.Product.name] - - For - [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT], - the following fields are always returned in by default: - - - [name][google.cloud.retail.v2beta.Product.name] - - [color_info][google.cloud.retail.v2beta.Product.color_info] - - Maximum number of paths is 30. Otherwise, an - INVALID_ARGUMENT error is returned. - - Note: Returning more fields in - [SearchResponse][google.cloud.retail.v2beta.SearchResponse] - may increase response payload size and serving latency. - variants (Sequence[google.cloud.retail_v2beta.types.Product]): - Output only. Product variants grouped together on primary - product which share similar product attributes. It's - automatically grouped by - [primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] - for all the product variants. Only populated for - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct]. - Do not set this field in API requests. - """ - class Type(proto.Enum): - r"""The type of this product.""" - TYPE_UNSPECIFIED = 0 - PRIMARY = 1 - VARIANT = 2 - COLLECTION = 3 - - class Availability(proto.Enum): - r"""Product availability. If this field is unspecified, the - product is assumed to be in stock. - """ - AVAILABILITY_UNSPECIFIED = 0 - IN_STOCK = 1 - OUT_OF_STOCK = 2 - PREORDER = 3 - BACKORDER = 4 - - expire_time = proto.Field( - proto.MESSAGE, - number=16, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl = proto.Field( - proto.MESSAGE, - number=17, - oneof='expiration', - message=duration_pb2.Duration, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - type_ = proto.Field( - proto.ENUM, - number=3, - enum=Type, - ) - primary_product_id = proto.Field( - proto.STRING, - number=4, - ) - collection_member_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - gtin = proto.Field( - proto.STRING, - number=6, - ) - categories = proto.RepeatedField( - proto.STRING, - number=7, - ) - title = proto.Field( - proto.STRING, - number=8, - ) - brands = proto.RepeatedField( - proto.STRING, - number=9, - ) - description = proto.Field( - proto.STRING, - number=10, - ) - language_code = proto.Field( - proto.STRING, - number=11, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=12, - message=common.CustomAttribute, - ) - tags = proto.RepeatedField( - proto.STRING, - number=13, - ) - price_info = proto.Field( - proto.MESSAGE, - number=14, - message=common.PriceInfo, - ) - rating = proto.Field( - proto.MESSAGE, - number=15, - message=common.Rating, - ) - available_time = proto.Field( - proto.MESSAGE, - number=18, - message=timestamp_pb2.Timestamp, - ) - availability = proto.Field( - proto.ENUM, - number=19, - enum=Availability, - ) - available_quantity = proto.Field( - proto.MESSAGE, - number=20, - message=wrappers_pb2.Int32Value, - ) - fulfillment_info = proto.RepeatedField( - proto.MESSAGE, - number=21, - message=common.FulfillmentInfo, - ) - uri = proto.Field( - proto.STRING, - number=22, - ) - images = proto.RepeatedField( - proto.MESSAGE, - number=23, - message=common.Image, - ) - audience = proto.Field( - proto.MESSAGE, - number=24, - message=common.Audience, - ) - color_info = proto.Field( - proto.MESSAGE, - number=25, - message=common.ColorInfo, - ) - sizes = proto.RepeatedField( - proto.STRING, - number=26, - ) - materials = proto.RepeatedField( - proto.STRING, - number=27, - ) - patterns = proto.RepeatedField( - proto.STRING, - number=28, - ) - conditions = proto.RepeatedField( - proto.STRING, - number=29, - ) - promotions = proto.RepeatedField( - proto.MESSAGE, - number=34, - message=promotion.Promotion, - ) - publish_time = proto.Field( - proto.MESSAGE, - number=33, - message=timestamp_pb2.Timestamp, - ) - retrievable_fields = proto.Field( - proto.MESSAGE, - number=30, - message=field_mask_pb2.FieldMask, - ) - variants = proto.RepeatedField( - proto.MESSAGE, - number=31, - message='Product', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py deleted file mode 100644 index 06a23d13..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py +++ /dev/null @@ -1,844 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'CreateProductRequest', - 'GetProductRequest', - 'UpdateProductRequest', - 'DeleteProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'SetInventoryRequest', - 'SetInventoryMetadata', - 'SetInventoryResponse', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesResponse', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesResponse', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesResponse', - }, -) - - -class CreateProductRequest(proto.Message): - r"""Request message for [CreateProduct][] method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - product (google.cloud.retail_v2beta.types.Product): - Required. The [Product][google.cloud.retail.v2beta.Product] - to create. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2beta.Product], which will - become the final component of the - [Product.name][google.cloud.retail.v2beta.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2beta.Product]s with the same - [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - product_id = proto.Field( - proto.STRING, - number=3, - ) - - -class GetProductRequest(proto.Message): - r"""Request message for [GetProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested - [Product][google.cloud.retail.v2beta.Product] does not - exist, a NOT_FOUND error is returned. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateProductRequest(proto.Message): - r"""Request message for [UpdateProduct][] method. - - Attributes: - product (google.cloud.retail_v2beta.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Product][google.cloud.retail.v2beta.Product] to update. The - immutable and output only fields are NOT supported. If not - set, all supported fields (the fields that are neither - immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - a new [Product][google.cloud.retail.v2beta.Product] will be - created. In this situation, ``update_mask`` is ignored. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteProductRequest(proto.Message): - r"""Request message for [DeleteProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2beta.Product] to delete - can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] with more than - one - [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2beta.Product] will be - deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProductsRequest(proto.Message): - r"""Request message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - - Attributes: - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list products - under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2beta.Product]s under this - branch, regardless of whether or not this branch exists, a - PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of - [Product][google.cloud.retail.v2beta.Product]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 - [ListProductsResponse.next_page_token][google.cloud.retail.v2beta.ListProductsResponse.next_page_token], - received from a previous - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - filter (str): - A filter to apply on the list results. Supported features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2beta.ListProductsRequest.filter] - is unset. - - List - [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s sharing - the same - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]. For - example: ``primary_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2beta.Product]s - bundled in a - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product]. For - example: ``collection_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2beta.Product]s with - a partibular type. For example: ``type = "PRIMARY"`` - ``type = "VARIANT"`` ``type = "COLLECTION"`` - - If the field is unrecognizable, an INVALID_ARGUMENT error is - returned. - - If the specified - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] or - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product] does not - exist, a NOT_FOUND error is returned. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields of [Product][google.cloud.retail.v2beta.Product] - to return in the responses. If not set or empty, the - following fields are returned: - - - [Product.name][google.cloud.retail.v2beta.Product.name] - - [Product.id][google.cloud.retail.v2beta.Product.id] - - [Product.title][google.cloud.retail.v2beta.Product.title] - - [Product.uri][google.cloud.retail.v2beta.Product.uri] - - [Product.images][google.cloud.retail.v2beta.Product.images] - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.brands][google.cloud.retail.v2beta.Product.brands] - - If "*" is provided, all fields are returned. - [Product.name][google.cloud.retail.v2beta.Product.name] is - always returned no matter what mask is set. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class ListProductsResponse(proto.Message): - r"""Response message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - - Attributes: - products (Sequence[google.cloud.retail_v2beta.types.Product]): - The [Product][google.cloud.retail.v2beta.Product]s. - next_page_token (str): - A token that can be sent as - [ListProductsRequest.page_token][google.cloud.retail.v2beta.ListProductsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class SetInventoryRequest(proto.Message): - r"""Request message for [SetInventory][] method. - - Attributes: - inventory (google.cloud.retail_v2beta.types.Product): - Required. The inventory information to update. The allowable - fields to update are: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product] named in - [Product.name][google.cloud.retail.v2beta.Product.name], - regardless of whether or not it exists, a PERMISSION_DENIED - error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2beta.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting the - last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of fulfillment - types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear in - [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types have - empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following inventory - fields: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - - If a full overwrite of inventory information while ignoring - timestamps is needed, [UpdateProduct][] should be invoked - instead. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2beta.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the request is issued, used to - prevent out-of-order updates on inventory fields - with the last update time recorded. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] with name - [Product.name][google.cloud.retail.v2beta.Product.name] is - not found, the inventory update will still be processed and - retained for at most 1 day until the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - inventory = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - set_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - set_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=4, - ) - - -class SetInventoryMetadata(proto.Message): - r"""Metadata related to the progress of the SetInventory operation. - Currently empty because there is no meaningful metadata populated - from the [SetInventory][] method. - - """ - - -class SetInventoryResponse(proto.Message): - r"""Response of the SetInventoryRequest. Currently empty because there - is no meaningful response populated from the [SetInventory][] - method. - - """ - - -class AddFulfillmentPlacesRequest(proto.Message): - r"""Request message for [AddFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery" to be added for this - [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type]. - Duplicate IDs will be automatically ignored. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If the total number of place IDs exceeds 2000 for this - [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type] - after adding, then the update will be rejected. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - the fulfillment information will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - add_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class AddFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the AddFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [AddFulfillmentPlaces][] method. - - """ - - -class AddFulfillmentPlacesResponse(proto.Message): - r"""Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - - -class AddLocalInventoriesRequest(proto.Message): - r"""Request message for [AddLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - local_inventories (Sequence[google.cloud.retail_v2beta.types.LocalInventory]): - Required. A list of inventory information at - difference places. Each place is identified by - its place ID. At most 3000 inventories are - allowed per request. - add_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided list of - [LocalInventory][google.cloud.retail.v2beta.LocalInventory] - to update. The field is updated to the provided value. - - If a field is set while the place does not have a previous - local inventory, the local inventory at that store is - created. - - If a field is set while the value of that field is not - provided, the original field value, if it exists, is - deleted. - - If the mask is not set or set with empty paths, all - inventory fields will be updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory updates are - issued. Used to prevent out-of-order updates on - local inventory fields. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - the local inventory will still be processed and retained for - at most 1 day and processed once the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - local_inventories = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.LocalInventory, - ) - add_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - add_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=6, - ) - - -class AddLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the AddLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [AddLocalInventories][] method. - - """ - - -class AddLocalInventoriesResponse(proto.Message): - r"""Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesRequest(proto.Message): - r"""Request message for [RemoveLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - place_ids (Sequence[str]): - Required. A list of place IDs to have their - inventory deleted. At most 3000 place IDs are - allowed per request. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory deletions are - issued. Used to prevent out-of-order updates and - deletions on local inventory fields. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - the local inventory removal request will still be processed - and retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class RemoveLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesResponse(proto.Message): - r"""Response of the [RemoveLocalInventories][] API. Currently empty - because there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - - -class RemoveFulfillmentPlacesRequest(proto.Message): - r"""Request message for [RemoveFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2beta.RemoveFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery", to be removed for this - [type][google.cloud.retail.v2beta.RemoveFulfillmentPlacesRequest.type]. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - the fulfillment information will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class RemoveFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveFulfillmentPlaces][] method. - - """ - - -class RemoveFulfillmentPlacesResponse(proto.Message): - r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty - because there is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py deleted file mode 100644 index be192a70..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'Promotion', - }, -) - - -class Promotion(proto.Message): - r"""Promotion information. - - Attributes: - promotion_id (str): - ID of the promotion. For example, "free gift". - - The value must be a UTF-8 encoded string with a length limit - of 128 characters, and match the pattern: - ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or - ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is - returned. - - Google Merchant Center property - `promotion `__. - """ - - promotion_id = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py deleted file mode 100644 index 95c99126..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py +++ /dev/null @@ -1,107 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - }, -) - - -class PurgeMetadata(proto.Message): - r"""Metadata related to the progress of the Purge operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - """ - - -class PurgeUserEventsRequest(proto.Message): - r"""Request message for PurgeUserEvents method. - - Attributes: - parent (str): - Required. The resource name of the catalog under which the - events are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}`` - filter (str): - Required. The filter string to specify the events to be - deleted with a length limit of 5,000 characters. Empty - string filter is not allowed. The eligible fields for - filtering are: - - - ``eventType``: Double quoted - [UserEvent.event_type][google.cloud.retail.v2beta.UserEvent.event_type] - string. - - ``eventTime``: in ISO 8601 "zulu" format. - - ``visitorId``: Double quoted string. Specifying this will - delete all events associated with a visitor. - - ``userId``: Double quoted string. Specifying this will - delete all events associated with a user. - - Examples: - - - Deleting all events in a time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - - Deleting specific eventType in time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` - - Deleting all events for a specific visitor: - ``visitorId = "visitor1024"`` - - The filtering fields are assumed to have an implicit AND. - force (bool): - Actually perform the purge. If ``force`` is set to false, - the method will return the expected purge count without - deleting any user events. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeUserEventsResponse(proto.Message): - r"""Response of the PurgeUserEventsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purged_events_count (int): - The total count of events purged as a result - of the operation. - """ - - purged_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py deleted file mode 100644 index 21447a27..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py +++ /dev/null @@ -1,1074 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'SearchRequest', - 'SearchResponse', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - - Attributes: - placement (str): - Required. The resource name of the search engine placement, - such as - ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` - This field is used to identify the serving configuration - name and the set of models that will be used to make the - search. - branch (str): - The branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - - Use "default_branch" as the branch ID or leave this field - empty, to search products under the default branch. - query (str): - Raw search query. - visitor_id (str): - Required. A unique identifier for tracking visitors. For - example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - This should be the same identifier as - [UserEvent.visitor_id][google.cloud.retail.v2beta.UserEvent.visitor_id]. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2beta.types.UserInfo): - User information. - page_size (int): - Maximum number of - [Product][google.cloud.retail.v2beta.Product]s to return. If - unspecified, defaults to a reasonable value. The maximum - allowed value is 120. Values above 120 will be coerced to - 120. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [SearchResponse.next_page_token][google.cloud.retail.v2beta.SearchResponse.next_page_token], - received from a previous - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - offset (int): - A 0-indexed integer that specifies the current offset (that - is, starting result location, amongst the - [Product][google.cloud.retail.v2beta.Product]s deemed by the - API as relevant) in search results. This field is only - considered if - [page_token][google.cloud.retail.v2beta.SearchRequest.page_token] - is unset. - - If this field is negative, an INVALID_ARGUMENT is returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. Filter expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - canonical_filter (str): - The default filter that is applied when a user performs a - search without checking any filters on the search page. - - The filter applied to every search request when quality - improvement such as query expansion is needed. For example, - if a query does not have enough results, an expanded query - with - [SearchRequest.canonical_filter][google.cloud.retail.v2beta.SearchRequest.canonical_filter] - will be returned as a supplement of the original query. This - field is strongly recommended to achieve high search - quality. - - See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for more details about filter syntax. - order_by (str): - The order in which products are returned. Products can be - ordered by a field in an - [Product][google.cloud.retail.v2beta.Product] object. Leave - it unset if ordered by relevance. OrderBy expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - facet_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.FacetSpec]): - Facet specifications for faceted search. If empty, no facets - are returned. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - dynamic_facet_spec (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec): - Deprecated. Refer to - https://cloud.google.com/retail/docs/configs#dynamic - to enable dynamic facets. Do not set this field. - The specification for dynamically generated - facets. Notice that only textual facets can be - dynamically generated. - boost_spec (google.cloud.retail_v2beta.types.SearchRequest.BoostSpec): - Boost specification to boost certain products. See more - details at this `user - guide `__. - - Notice that if both - [ServingConfig.boost_control_ids][google.cloud.retail.v2beta.ServingConfig.boost_control_ids] - and [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. - query_expansion_spec (google.cloud.retail_v2beta.types.SearchRequest.QueryExpansionSpec): - The query expansion specification that specifies the - conditions under which query expansion will occur. See more - details at this `user - guide `__. - variant_rollup_keys (Sequence[str]): - The keys to fetch and rollup the matching - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s attributes, - [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo] - or - [LocalInventory][google.cloud.retail.v2beta.LocalInventory]s - attributes. The attributes from all the matching - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s or - [LocalInventory][google.cloud.retail.v2beta.LocalInventory]s - are merged and de-duplicated. Notice that rollup attributes - will lead to extra query latency. Maximum number of keys is - 30. - - For - [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], - a fulfillment type and a fulfillment ID must be provided in - the format of "fulfillmentType.fulfillmentId". E.g., in - "pickupInStore.store123", "pickupInStore" is fulfillment - type and "store123" is the store ID. - - Supported keys are: - - - colorFamilies - - price - - originalPrice - - discount - - variantId - - inventory(place_id,price) - - inventory(place_id,original_price) - - inventory(place_id,attributes.key), where key is any key - in the [Product.inventories.attributes][] map. - - attributes.key, where key is any key in the - [Product.attributes][google.cloud.retail.v2beta.Product.attributes] - map. - - pickupInStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "pickup-in-store". - - shipToStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "ship-to-store". - - sameDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "same-day-delivery". - - nextDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "next-day-delivery". - - customFulfillment1.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-1". - - customFulfillment2.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-2". - - customFulfillment3.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-3". - - customFulfillment4.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-4". - - customFulfillment5.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-5". - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. Required for - category navigation queries to achieve good search quality. - The format should be the same as - [UserEvent.page_categories][google.cloud.retail.v2beta.UserEvent.page_categories]; - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - search_mode (google.cloud.retail_v2beta.types.SearchRequest.SearchMode): - The search mode of the search request. If not - specified, a single search request triggers both - product search and faceted search. - personalization_spec (google.cloud.retail_v2beta.types.SearchRequest.PersonalizationSpec): - The specification for personalization. - """ - class SearchMode(proto.Enum): - r"""The search mode of each search request.""" - SEARCH_MODE_UNSPECIFIED = 0 - PRODUCT_SEARCH_ONLY = 1 - FACETED_SEARCH_ONLY = 2 - - class FacetSpec(proto.Message): - r"""A facet specification to perform faceted search. - - Attributes: - facet_key (google.cloud.retail_v2beta.types.SearchRequest.FacetSpec.FacetKey): - Required. The facet key specification. - limit (int): - Maximum of facet values that should be returned for this - facet. If unspecified, defaults to 20. The maximum allowed - value is 300. Values above 300 will be coerced to 300. - - If this field is negative, an INVALID_ARGUMENT is returned. - excluded_filter_keys (Sequence[str]): - List of keys to exclude when faceting. - - By default, - [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] - is not excluded from the filter unless it is listed in this - field. - - For example, suppose there are 100 products with color facet - "Red" and 200 products with color facet "Blue". A query - containing the filter "colorFamilies:ANY("Red")" and have - "colorFamilies" as - [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] - will by default return the "Red" with count 100. - - If this field contains "colorFamilies", then the query - returns both the "Red" with count 100 and "Blue" with count - 200, because the "colorFamilies" key is now excluded from - the filter. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - enable_dynamic_position (bool): - Enables dynamic position for this facet. If set to true, the - position of this facet among all facets in the response is - determined by Google Retail Search. It will be ordered - together with dynamic facets if dynamic facets is enabled. - If set to false, the position of this facet in the response - will be the same as in the request, and it will be ranked - before the facets with dynamic position enable and all - dynamic facets. - - For example, you may always want to have rating facet - returned in the response, but it's not necessarily to always - display the rating facet at the top. In that case, you can - set enable_dynamic_position to true so that the position of - rating facet in response will be determined by Google Retail - Search. - - Another example, assuming you have the following facets in - the request: - - - "rating", enable_dynamic_position = true - - - "price", enable_dynamic_position = false - - - "brands", enable_dynamic_position = false - - And also you have a dynamic facets enable, which will - generate a facet 'gender'. Then the final order of the - facets in the response can be ("price", "brands", "rating", - "gender") or ("price", "brands", "gender", "rating") depends - on how Google Retail Search orders "gender" and "rating" - facets. However, notice that "price" and "brands" will - always be ranked at 1st and 2nd position since their - enable_dynamic_position are false. - """ - - class FacetKey(proto.Message): - r"""Specifies how a facet is computed. - - Attributes: - key (str): - Required. Supported textual and numerical facet keys in - [Product][google.cloud.retail.v2beta.Product] object, over - which the facet values are computed. Facet key is - case-sensitive. - - Allowed facet keys when - [FacetKey.query][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.query] - is not specified: - - - textual_field = - - - "brands" - - "categories" - - "genders" - - "ageGroups" - - "availability" - - "colorFamilies" - - "colors" - - "sizes" - - "materials" - - "patterns" - - "conditions" - - "attributes.key" - - "pickupInStore" - - "shipToStore" - - "sameDayDelivery" - - "nextDayDelivery" - - "customFulfillment1" - - "customFulfillment2" - - "customFulfillment3" - - "customFulfillment4" - - "customFulfillment5" - - "inventory(place_id,attributes.key)" - - - numerical_field = - - - "price" - - "discount" - - "rating" - - "ratingCount" - - "attributes.key" - - "inventory(place_id,price)" - - "inventory(place_id,original_price)" - - "inventory(place_id,attributes.key)". - intervals (Sequence[google.cloud.retail_v2beta.types.Interval]): - Set only if values should be bucketized into - intervals. Must be set for facets with numerical - values. Must not be set for facet with text - values. Maximum number of intervals is 30. - restricted_values (Sequence[str]): - Only get facet for the given restricted values. For example, - when using "pickupInStore" as key and set restricted values - to ["store123", "store456"], only facets for "store123" and - "store456" are returned. Only supported on textual fields - and fulfillments. Maximum is 20. - - Must be set for the fulfillment facet keys: - - - pickupInStore - - - shipToStore - - - sameDayDelivery - - - nextDayDelivery - - - customFulfillment1 - - - customFulfillment2 - - - customFulfillment3 - - - customFulfillment4 - - - customFulfillment5 - prefixes (Sequence[str]): - Only get facet values that start with the - given string prefix. For example, suppose - "categories" has three values "Women > Shoe", - "Women > Dress" and "Men > Shoe". If set - "prefixes" to "Women", the "categories" facet - will give only "Women > Shoe" and "Women > - Dress". Only supported on textual fields. - Maximum is 10. - contains (Sequence[str]): - Only get facet values that contains the given - strings. For example, suppose "categories" has - three values "Women > Shoe", "Women > Dress" and - "Men > Shoe". If set "contains" to "Shoe", the - "categories" facet will give only "Women > Shoe" - and "Men > Shoe". Only supported on textual - fields. Maximum is 10. - order_by (str): - The order in which [Facet.values][] are returned. - - Allowed values are: - - - "count desc", which means order by - [Facet.FacetValue.count][] descending. - - - "value desc", which means order by - [Facet.FacetValue.value][] descending. Only applies to - textual facets. - - If not set, textual values are sorted in `natural - order `__; - numerical intervals are sorted in the order given by - [FacetSpec.FacetKey.intervals][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.intervals]; - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - are sorted in the order given by - [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.restricted_values]. - query (str): - The query that is used to compute facet for the given facet - key. When provided, it will override the default behavior of - facet computation. The query syntax is the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for detail syntax and limitations. Notice that there is no - limitation on - [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] - when query is specified. - - In the response, [FacetValue.value][] will be always "1" and - [FacetValue.count][] will be the number of results that - matches the query. - - For example, you can set a customized facet for - "shipToStore", where - [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] - is "customizedShipToStore", and - [FacetKey.query][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.query] - is "availability: ANY("IN_STOCK") AND shipToStore: - ANY("123")". Then the facet will count the products that are - both in stock and ship to store "123". - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - intervals = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Interval, - ) - restricted_values = proto.RepeatedField( - proto.STRING, - number=3, - ) - prefixes = proto.RepeatedField( - proto.STRING, - number=8, - ) - contains = proto.RepeatedField( - proto.STRING, - number=9, - ) - order_by = proto.Field( - proto.STRING, - number=4, - ) - query = proto.Field( - proto.STRING, - number=5, - ) - - facet_key = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.FacetSpec.FacetKey', - ) - limit = proto.Field( - proto.INT32, - number=2, - ) - excluded_filter_keys = proto.RepeatedField( - proto.STRING, - number=3, - ) - enable_dynamic_position = proto.Field( - proto.BOOL, - number=4, - ) - - class DynamicFacetSpec(proto.Message): - r"""The specifications of dynamically generated facets. - - Attributes: - mode (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec.Mode): - Mode of the DynamicFacet feature. Defaults to - [Mode.DISABLED][google.cloud.retail.v2beta.SearchRequest.DynamicFacetSpec.Mode.DISABLED] - if it's unset. - """ - class Mode(proto.Enum): - r"""Enum to control DynamicFacet mode""" - MODE_UNSPECIFIED = 0 - DISABLED = 1 - ENABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.DynamicFacetSpec.Mode', - ) - - class BoostSpec(proto.Message): - r"""Boost specification to boost certain items. - - Attributes: - condition_boost_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - Condition boost specifications. If a product - matches multiple conditions in the - specifictions, boost scores from these - specifications are all applied and combined in a - non-linear way. Maximum number of specifications - is 10. - skip_boost_spec_validation (bool): - Whether to skip boostspec validation. If this field is set - to true, invalid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] - will be ignored and valid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] - will still be applied. - - This field is a member of `oneof`_ ``_skip_boost_spec_validation``. - """ - - class ConditionBoostSpec(proto.Message): - r"""Boost applies to products which match a condition. - - Attributes: - condition (str): - An expression which specifies a boost condition. The syntax - and supported fields are the same as a filter expression. - See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": - - - (id: ANY("product_1", "product_2")) AND - (colorFamilies: ANY("Red","Blue")) - boost (float): - Strength of the condition boost, which should be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - """ - - condition = proto.Field( - proto.STRING, - number=1, - ) - boost = proto.Field( - proto.FLOAT, - number=2, - ) - - condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - skip_boost_spec_validation = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - - class QueryExpansionSpec(proto.Message): - r"""Specification to determine under which conditions query - expansion should occur. - - Attributes: - condition (google.cloud.retail_v2beta.types.SearchRequest.QueryExpansionSpec.Condition): - The condition under which query expansion should occur. - Default to - [Condition.DISABLED][google.cloud.retail.v2beta.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - pin_unexpanded_results (bool): - Whether to pin unexpanded results. If this - field is set to true, unexpanded products are - always at the top of the search results, - followed by the expanded results. - """ - class Condition(proto.Enum): - r"""Enum describing under which condition query expansion should - occur. - """ - CONDITION_UNSPECIFIED = 0 - DISABLED = 1 - AUTO = 3 - - condition = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.QueryExpansionSpec.Condition', - ) - pin_unexpanded_results = proto.Field( - proto.BOOL, - number=2, - ) - - class PersonalizationSpec(proto.Message): - r"""The specification for personalization. - - Attributes: - mode (google.cloud.retail_v2beta.types.SearchRequest.PersonalizationSpec.Mode): - Defaults to - [Mode.AUTO][google.cloud.retail.v2beta.SearchRequest.PersonalizationSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""The personalization mode of each search request.""" - MODE_UNSPECIFIED = 0 - AUTO = 1 - DISABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.PersonalizationSpec.Mode', - ) - - placement = proto.Field( - proto.STRING, - number=1, - ) - branch = proto.Field( - proto.STRING, - number=2, - ) - query = proto.Field( - proto.STRING, - number=3, - ) - visitor_id = proto.Field( - proto.STRING, - number=4, - ) - user_info = proto.Field( - proto.MESSAGE, - number=5, - message=common.UserInfo, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - offset = proto.Field( - proto.INT32, - number=9, - ) - filter = proto.Field( - proto.STRING, - number=10, - ) - canonical_filter = proto.Field( - proto.STRING, - number=28, - ) - order_by = proto.Field( - proto.STRING, - number=11, - ) - facet_specs = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=FacetSpec, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=21, - message=DynamicFacetSpec, - ) - boost_spec = proto.Field( - proto.MESSAGE, - number=13, - message=BoostSpec, - ) - query_expansion_spec = proto.Field( - proto.MESSAGE, - number=14, - message=QueryExpansionSpec, - ) - variant_rollup_keys = proto.RepeatedField( - proto.STRING, - number=17, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=23, - ) - search_mode = proto.Field( - proto.ENUM, - number=31, - enum=SearchMode, - ) - personalization_spec = proto.Field( - proto.MESSAGE, - number=32, - message=PersonalizationSpec, - ) - - -class SearchResponse(proto.Message): - r"""Response message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - - Attributes: - results (Sequence[google.cloud.retail_v2beta.types.SearchResponse.SearchResult]): - A list of matched items. The order represents - the ranking. - facets (Sequence[google.cloud.retail_v2beta.types.SearchResponse.Facet]): - Results of facets requested by user. - total_size (int): - The estimated total count of matched items irrespective of - pagination. The count of - [results][google.cloud.retail.v2beta.SearchResponse.results] - returned by pagination may be less than the - [total_size][google.cloud.retail.v2beta.SearchResponse.total_size] - that matches. - corrected_query (str): - If spell correction applies, the corrected - query. Otherwise, empty. - attribution_token (str): - A unique search token. This should be included in the - [UserEvent][google.cloud.retail.v2beta.UserEvent] logs - resulting from this search, which enables accurate - attribution of search model performance. - next_page_token (str): - A token that can be sent as - [SearchRequest.page_token][google.cloud.retail.v2beta.SearchRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - query_expansion_info (google.cloud.retail_v2beta.types.SearchResponse.QueryExpansionInfo): - Query expansion information for the returned - results. - redirect_uri (str): - The URI of a customer-defined redirect page. If redirect - action is triggered, no search will be performed, and only - [redirect_uri][google.cloud.retail.v2beta.SearchResponse.redirect_uri] - and - [attribution_token][google.cloud.retail.v2beta.SearchResponse.attribution_token] - will be set in the response. - applied_controls (Sequence[str]): - The fully qualified resource name of applied - `controls `__. - invalid_condition_boost_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - The invalid - [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] - that are not applied during serving. - """ - - class SearchResult(proto.Message): - r"""Represents the search results. - - Attributes: - id (str): - [Product.id][google.cloud.retail.v2beta.Product.id] of the - searched [Product][google.cloud.retail.v2beta.Product]. - product (google.cloud.retail_v2beta.types.Product): - The product data snippet in the search response. Only - [Product.name][google.cloud.retail.v2beta.Product.name] is - guaranteed to be populated. - - [Product.variants][google.cloud.retail.v2beta.Product.variants] - contains the product variants that match the search query. - If there are multiple product variants matching the query, - top 5 most relevant product variants are returned and - ordered by relevancy. - - If relevancy can be deternmined, use - [matching_variant_fields][google.cloud.retail.v2beta.SearchResponse.SearchResult.matching_variant_fields] - to look up matched product variants fields. If relevancy - cannot be determined, e.g. when searching "shoe" all - products in a shoe product can be a match, 5 product - variants are returned but order is meaningless. - matching_variant_count (int): - The count of matched - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s. - matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): - If a - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] matches the - search query, this map indicates which - [Product][google.cloud.retail.v2beta.Product] fields are - matched. The key is the - [Product.name][google.cloud.retail.v2beta.Product.name], the - value is a field mask of the matched - [Product][google.cloud.retail.v2beta.Product] fields. If - matched attributes cannot be determined, this map will be - empty. - - For example, a key "sku1" with field mask - "products.color_info" indicates there is a match between - "sku1" [ColorInfo][google.cloud.retail.v2beta.ColorInfo] and - the query. - variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): - The rollup matching - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] attributes. - The key is one of the - [SearchRequest.variant_rollup_keys][google.cloud.retail.v2beta.SearchRequest.variant_rollup_keys]. - The values are the merged and de-duplicated - [Product][google.cloud.retail.v2beta.Product] attributes. - Notice that the rollup values are respect filter. For - example, when filtering by "colorFamilies:ANY("red")" and - rollup "colorFamilies", only "red" is returned. - - For textual and numerical attributes, the rollup values is a - list of string or double values with type - [google.protobuf.ListValue][google.protobuf.ListValue]. For - example, if there are two variants with colors "red" and - "blue", the rollup values are - - :: - - { key: "colorFamilies" - value { - list_value { - values { string_value: "red" } - values { string_value: "blue" } - } - } - } - - For - [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], - the rollup values is a double value with type - [google.protobuf.Value][google.protobuf.Value]. For example, - ``{key: "pickupInStore.store1" value { number_value: 10 }}`` - means a there are 10 variants in this product are available - in the store "store1". - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - matching_variant_count = proto.Field( - proto.INT32, - number=3, - ) - matching_variant_fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - variant_rollup_values = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - - class Facet(proto.Message): - r"""A facet result. - - Attributes: - key (str): - The key for this facet. E.g., "colorFamilies" - or "price" or "attributes.attr1". - values (Sequence[google.cloud.retail_v2beta.types.SearchResponse.Facet.FacetValue]): - The facet values for this field. - dynamic_facet (bool): - Whether the facet is dynamically generated. - """ - - class FacetValue(proto.Message): - r"""A facet value which contains value names and their count. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Text value of a facet, such as "Black" for - facet "colorFamilies". - - This field is a member of `oneof`_ ``facet_value``. - interval (google.cloud.retail_v2beta.types.Interval): - Interval value for a facet, such as [10, 20) for facet - "price". - - This field is a member of `oneof`_ ``facet_value``. - count (int): - Number of items that have this facet value. - """ - - value = proto.Field( - proto.STRING, - number=1, - oneof='facet_value', - ) - interval = proto.Field( - proto.MESSAGE, - number=2, - oneof='facet_value', - message=common.Interval, - ) - count = proto.Field( - proto.INT64, - number=3, - ) - - key = proto.Field( - proto.STRING, - number=1, - ) - values = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SearchResponse.Facet.FacetValue', - ) - dynamic_facet = proto.Field( - proto.BOOL, - number=3, - ) - - class QueryExpansionInfo(proto.Message): - r"""Information describing query expansion including whether - expansion has occurred. - - Attributes: - expanded_query (bool): - Bool describing whether query expansion has - occurred. - pinned_result_count (int): - Number of pinned results. This field will only be set when - expansion happens and - [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2beta.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] - is set to true. - """ - - expanded_query = proto.Field( - proto.BOOL, - number=1, - ) - pinned_result_count = proto.Field( - proto.INT64, - number=2, - ) - - @property - def raw_page(self): - return self - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=SearchResult, - ) - facets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Facet, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - corrected_query = proto.Field( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - next_page_token = proto.Field( - proto.STRING, - number=6, - ) - query_expansion_info = proto.Field( - proto.MESSAGE, - number=7, - message=QueryExpansionInfo, - ) - redirect_uri = proto.Field( - proto.STRING, - number=10, - ) - applied_controls = proto.RepeatedField( - proto.STRING, - number=12, - ) - invalid_condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py deleted file mode 100644 index f8b78591..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py +++ /dev/null @@ -1,309 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'ServingConfig', - }, -) - - -class ServingConfig(proto.Message): - r"""Configures metadata that is used to generate serving time results - (e.g. search results or recommendation predictions). The - ServingConfig is passed in the search and predict request and - together with the Catalog.default_branch, generates results. - - Attributes: - name (str): - Immutable. Fully qualified name - projects/\ */locations/global/catalogs/*/servingConfig/\* - display_name (str): - Required. The human readable serving config display name. - Used in Retail UI. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - model_id (str): - The id of the model to use at serving time. Currently only - RecommendationModels are supported: - https://cloud.google.com/retail/recommendations-ai/docs/create-models - Can be changed but only to a compatible model (e.g. - others-you-may-like CTR to others-you-may-like CVR). - - Required when - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - price_reranking_level (str): - How much price ranking we want in serving results. Price - reranking causes product items with a similar recommendation - probability to be ordered by price, with the highest-priced - items first. This setting could result in a decrease in - click-through and conversion rates. Allowed values are: - - - 'no-price-reranking' - - 'low-price-raranking' - - 'medium-price-reranking' - - 'high-price-reranking' - - If not specified, we choose default based on model type. - Default value: 'no-price-reranking'. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - facet_control_ids (Sequence[str]): - Facet specifications for faceted search. If empty, no facets - are returned. The ids refer to the ids of - [Control][google.cloud.retail.v2beta.Control] resources with - only the Facet control set. These controls are assumed to be - in the same [Catalog][google.cloud.retail.v2beta.Catalog] as - the - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]. A - maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - dynamic_facet_spec (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec): - The specification for dynamically generated facets. Notice - that only textual facets can be dynamically generated. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - boost_control_ids (Sequence[str]): - Condition boost specifications. If a product matches - multiple conditions in the specifications, boost scores from - these specifications are all applied and combined in a - non-linear way. Maximum number of specifications is 100. - - Notice that if both - [ServingConfig.boost_control_ids][google.cloud.retail.v2beta.ServingConfig.boost_control_ids] - and [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - filter_control_ids (Sequence[str]): - Condition filter specifications. If a product matches - multiple conditions in the specifications, filters from - these specifications are all applied and combined via the - AND operator. Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - redirect_control_ids (Sequence[str]): - Condition redirect specifications. Only the first triggered - redirect action is applied, even if multiple apply. Maximum - number of specifications is 1000. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - twoway_synonyms_control_ids (Sequence[str]): - Condition synonyms specifications. If multiple syonyms - conditions match, all matching synonyms control in the list - will execute. Order of controls in the list will not matter. - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - oneway_synonyms_control_ids (Sequence[str]): - Condition oneway synonyms specifications. If multiple oneway - synonyms conditions match, all matching oneway synonyms - controls in the list will execute. Order of controls in the - list will not matter. Maximum number of specifications is - 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - do_not_associate_control_ids (Sequence[str]): - Condition do not associate specifications. If multiple do - not associate conditions match, all matching do not - associate controls in the list will execute. - - - Order does not matter. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - replacement_control_ids (Sequence[str]): - Condition replacement specifications. - - - Applied according to the order in the list. - - A previously replaced term can not be re-replaced. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - ignore_control_ids (Sequence[str]): - Condition ignore specifications. If multiple ignore - conditions match, all matching ignore controls in the list - will execute. - - - Order does not matter. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - diversity_level (str): - How much diversity to use in recommendation model results - e.g. 'medium-diversity' or 'high-diversity'. Currently - supported values: - - - 'no-diversity' - - 'low-diversity' - - 'medium-diversity' - - 'high-diversity' - - 'auto-diversity' - - If not specified, we choose default based on recommendation - model type. Default value: 'no-diversity'. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - enable_category_filter_level (str): - Whether to add additional category filters on the - 'similar-items' model. If not specified, we enable it by - default. Allowed values are: - - - 'no-category-match': No additional filtering of original - results from the model and the customer's filters. - - 'relaxed-category-match': Only keep results with - categories that match at least one item categories in the - PredictRequests's context item. - - - If customer also sends filters in the PredictRequest, - then the results will satisfy both conditions (user - given and category match). - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - solution_types (Sequence[google.cloud.retail_v2beta.types.SolutionType]): - Required. Immutable. Specifies the solution - types that a serving config can be associated - with. Currently we support setting only one type - of solution. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - model_id = proto.Field( - proto.STRING, - number=3, - ) - price_reranking_level = proto.Field( - proto.STRING, - number=4, - ) - facet_control_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=6, - message=search_service.SearchRequest.DynamicFacetSpec, - ) - boost_control_ids = proto.RepeatedField( - proto.STRING, - number=7, - ) - filter_control_ids = proto.RepeatedField( - proto.STRING, - number=9, - ) - redirect_control_ids = proto.RepeatedField( - proto.STRING, - number=10, - ) - twoway_synonyms_control_ids = proto.RepeatedField( - proto.STRING, - number=18, - ) - oneway_synonyms_control_ids = proto.RepeatedField( - proto.STRING, - number=12, - ) - do_not_associate_control_ids = proto.RepeatedField( - proto.STRING, - number=13, - ) - replacement_control_ids = proto.RepeatedField( - proto.STRING, - number=14, - ) - ignore_control_ids = proto.RepeatedField( - proto.STRING, - number=15, - ) - diversity_level = proto.Field( - proto.STRING, - number=8, - ) - enable_category_filter_level = proto.Field( - proto.STRING, - number=16, - ) - solution_types = proto.RepeatedField( - proto.ENUM, - number=19, - enum=common.SolutionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py deleted file mode 100644 index 20edced0..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py +++ /dev/null @@ -1,234 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'CreateServingConfigRequest', - 'UpdateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'AddControlRequest', - 'RemoveControlRequest', - }, -) - - -class CreateServingConfigRequest(proto.Message): - r"""Request for CreateServingConfig method. - - Attributes: - parent (str): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - serving_config (google.cloud.retail_v2beta.types.ServingConfig): - Required. The ServingConfig to create. - serving_config_id (str): - Required. The ID to use for the ServingConfig, which will - become the final component of the ServingConfig's resource - name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-_/. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - serving_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_serving_config.ServingConfig, - ) - serving_config_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateServingConfigRequest(proto.Message): - r"""Request for UpdateServingConfig method. - - Attributes: - serving_config (google.cloud.retail_v2beta.types.ServingConfig): - Required. The ServingConfig to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [ServingConfig][google.cloud.retail.v2beta.ServingConfig] to - update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] - - If not set, all supported fields are updated. - """ - - serving_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_serving_config.ServingConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteServingConfigRequest(proto.Message): - r"""Request for DeleteServingConfig method. - - Attributes: - name (str): - Required. The resource name of the ServingConfig to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetServingConfigRequest(proto.Message): - r"""Request for GetServingConfig method. - - Attributes: - name (str): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListServingConfigsRequest(proto.Message): - r"""Request for ListServingConfigs method. - - Attributes: - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - page_size (int): - Optional. Maximum number of results to - return. If unspecified, defaults to 100. If a - value greater than 100 is provided, at most 100 - results are returned. - page_token (str): - Optional. A page token, received from a previous - ``ListServingConfigs`` call. Provide this to retrieve the - subsequent page. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListServingConfigsResponse(proto.Message): - r"""Response for ListServingConfigs method. - - Attributes: - serving_configs (Sequence[google.cloud.retail_v2beta.types.ServingConfig]): - All the ServingConfigs for a given catalog. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - serving_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_serving_config.ServingConfig, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class AddControlRequest(proto.Message): - r"""Request for AddControl method. - - Attributes: - serving_config (str): - Required. The source ServingConfig resource name . Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - control_id (str): - Required. The id of the control to apply. Assumed to be in - the same catalog as the serving config - if id is not found - a NOT_FOUND error is returned. - """ - - serving_config = proto.Field( - proto.STRING, - number=1, - ) - control_id = proto.Field( - proto.STRING, - number=2, - ) - - -class RemoveControlRequest(proto.Message): - r"""Request for RemoveControl method. - - Attributes: - serving_config (str): - Required. The source ServingConfig resource name . Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - control_id (str): - Required. The id of the control to apply. - Assumed to be in the same catalog as the serving - config. - """ - - serving_config = proto.Field( - proto.STRING, - number=1, - ) - control_id = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py deleted file mode 100644 index bf1b1aee..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py +++ /dev/null @@ -1,507 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import product as gcr_product -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'UserEvent', - 'ProductDetail', - 'CompletionDetail', - 'PurchaseTransaction', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information Retail API needs - to know about how end users interact with customers' website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - - ``add-to-cart``: Products being added to cart. - - ``category-page-view``: Special pages such as sale or - promotion pages viewed. - - ``detail-page-view``: Products detail page viewed. - - ``home-page-view``: Homepage viewed. - - ``promotion-offered``: Promotion is offered to a user. - - ``promotion-not-offered``: Promotion is not offered to a - user. - - ``purchase-complete``: User finishing a purchase. - - ``search``: Product search. - - ``shopping-cart-page-view``: User viewing a shopping - cart. - visitor_id (str): - Required. A unique identifier for tracking visitors. - - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor log in/out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - The field should not contain PII or user-data. We recommend - to use Google Analystics `Client - ID `__ - for this field. - session_id (str): - A unique identifier for tracking a visitor session with a - length limit of 128 bytes. A session is an aggregation of an - end user behavior in a time span. - - A general guideline to populate the sesion_id: - - 1. If user has no activity for 30 min, a new session_id - should be assigned. - 2. The session_id should be unique across users, suggest use - uuid or add visitor_id as prefix. - event_time (google.protobuf.timestamp_pb2.Timestamp): - Only required for - [UserEventService.ImportUserEvents][google.cloud.retail.v2beta.UserEventService.ImportUserEvents] - method. Timestamp of when the user event happened. - experiment_ids (Sequence[str]): - A list of identifiers for the independent - experiment groups this user event belongs to. - This is used to distinguish between user events - associated with different experiment setups - (e.g. using Retail API, using different - recommendation models). - attribution_token (str): - Highly recommended for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2beta.PredictionService.Predict]. - This field enables accurate attribution of recommendation - model performance. - - The value must be a valid - [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] - for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2beta.PredictionService.Predict]. - The value must be a valid - [SearchResponse.attribution_token][google.cloud.retail.v2beta.SearchResponse.attribution_token] - for user events that are the result of - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - This token enables us to accurately attribute page view or - purchase back to the event and the particular predict - response containing this clicked/purchased product. If user - clicks on product K in the recommendation results, pass - [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] - as a URL parameter to product K's page. When recording - events on product K's page, log the - [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] - to this field. - product_details (Sequence[google.cloud.retail_v2beta.types.ProductDetail]): - The main product details related to the event. - - This field is required for the following event types: - - - ``add-to-cart`` - - ``detail-page-view`` - - ``purchase-complete`` - - ``search`` - - In a ``search`` event, this field represents the products - returned to the end user on the current page (the end user - may have not finished browsing the whole page yet). When a - new page is returned to the end user, after - pagination/filtering/ordering even for the same query, a new - ``search`` event with different - [product_details][google.cloud.retail.v2beta.UserEvent.product_details] - is desired. The end user may have not finished browsing the - whole page yet. - completion_detail (google.cloud.retail_v2beta.types.CompletionDetail): - The main auto-completion details related to the event. - - This field should be set for ``search`` event when - autocomplete function is enabled and the user clicks a - suggestion for search. - attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): - Extra user event features to include in the recommendation - model. - - If you provide custom attributes for ingested user events, - also include them in the user events that you associate with - prediction requests. Custom attribute formatting must be - consistent between imported events and events provided with - prediction requests. This lets the Retail API use those - custom attributes when training models and serving - predictions, which helps improve recommendation quality. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - The key must be a UTF-8 encoded string with a length - limit of 5,000 characters. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a UTF-8 - encoded string with a length limit of 256 characters. - - For number attributes, at most 400 values are allowed. - - For product recommendations, an example of extra user - information is traffic_channel, which is how a user arrives - at the site. Users can arrive at the site by coming to the - site directly, coming through Google search, or in other - ways. - cart_id (str): - The ID or name of the associated shopping cart. This ID is - used to associate multiple items added or present in the - cart before purchase. - - This can only be set for ``add-to-cart``, - ``purchase-complete``, or ``shopping-cart-page-view`` - events. - purchase_transaction (google.cloud.retail_v2beta.types.PurchaseTransaction): - A transaction represents the entire purchase transaction. - - Required for ``purchase-complete`` events. Other event types - should not set this field. Otherwise, an INVALID_ARGUMENT - error is returned. - search_query (str): - The user's search query. - - See - [SearchRequest.query][google.cloud.retail.v2beta.SearchRequest.query] - for definition. - - The value must be a UTF-8 encoded string with a length limit - of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - At least one of - [search_query][google.cloud.retail.v2beta.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2beta.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. - - See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - order_by (str): - The order in which products are returned. - - See - [SearchRequest.order_by][google.cloud.retail.v2beta.SearchRequest.order_by] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - offset (int): - An integer that specifies the current offset for pagination - (the 0-indexed starting location, amongst the products - deemed by the API as relevant). - - See - [SearchRequest.offset][google.cloud.retail.v2beta.SearchRequest.offset] - for definition. - - If this field is negative, an INVALID_ARGUMENT is returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - - Required for ``category-page-view`` events. At least one of - [search_query][google.cloud.retail.v2beta.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2beta.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2beta.types.UserInfo): - User information. - uri (str): - Complete URL (window.location.href) of the - user's current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. Maximum length - 5,000 characters. - referrer_uri (str): - The referrer URL of the current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. - page_view_id (str): - A unique ID of a web page view. - - This should be kept the same for all user events triggered - from the same pageview. For example, an item detail page - view could trigger multiple events as the user is browsing - the page. The ``pageViewId`` property should be kept the - same for all these events so that they can be grouped - together properly. - - When using the client side event reporting with JavaScript - pixel and Google Tag Manager, this value is filled in - automatically. - """ - - event_type = proto.Field( - proto.STRING, - number=1, - ) - visitor_id = proto.Field( - proto.STRING, - number=2, - ) - session_id = proto.Field( - proto.STRING, - number=21, - ) - event_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - experiment_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - product_details = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='ProductDetail', - ) - completion_detail = proto.Field( - proto.MESSAGE, - number=22, - message='CompletionDetail', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=common.CustomAttribute, - ) - cart_id = proto.Field( - proto.STRING, - number=8, - ) - purchase_transaction = proto.Field( - proto.MESSAGE, - number=9, - message='PurchaseTransaction', - ) - search_query = proto.Field( - proto.STRING, - number=10, - ) - filter = proto.Field( - proto.STRING, - number=16, - ) - order_by = proto.Field( - proto.STRING, - number=17, - ) - offset = proto.Field( - proto.INT32, - number=18, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=11, - ) - user_info = proto.Field( - proto.MESSAGE, - number=12, - message=common.UserInfo, - ) - uri = proto.Field( - proto.STRING, - number=13, - ) - referrer_uri = proto.Field( - proto.STRING, - number=14, - ) - page_view_id = proto.Field( - proto.STRING, - number=15, - ) - - -class ProductDetail(proto.Message): - r"""Detailed product information associated with a user event. - - Attributes: - product (google.cloud.retail_v2beta.types.Product): - Required. [Product][google.cloud.retail.v2beta.Product] - information. - - Required field(s): - - - [Product.id][google.cloud.retail.v2beta.Product.id] - - Optional override field(s): - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - If any supported optional fields are provided, we will treat - them as a full override when looking up product information - from the catalog. Thus, it is important to ensure that the - overriding fields are accurate and complete. - - All other product fields are ignored and instead populated - via catalog lookup after event ingestion. - quantity (google.protobuf.wrappers_pb2.Int32Value): - Quantity of the product associated with the user event. - - For example, this field will be 2 if two products are added - to the shopping cart for ``purchase-complete`` event. - Required for ``add-to-cart`` and ``purchase-complete`` event - types. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - quantity = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -class CompletionDetail(proto.Message): - r"""Detailed completion information including completion - attribution token and clicked completion info. - - Attributes: - completion_attribution_token (str): - Completion attribution token in - [CompleteQueryResponse.attribution_token][google.cloud.retail.v2beta.CompleteQueryResponse.attribution_token]. - selected_suggestion (str): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2beta.CompleteQueryResponse.CompletionResult.suggestion]. - selected_position (int): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2beta.CompleteQueryResponse.CompletionResult.suggestion] - position, starting from 0. - """ - - completion_attribution_token = proto.Field( - proto.STRING, - number=1, - ) - selected_suggestion = proto.Field( - proto.STRING, - number=2, - ) - selected_position = proto.Field( - proto.INT32, - number=3, - ) - - -class PurchaseTransaction(proto.Message): - r"""A transaction represents the entire purchase transaction. - - Attributes: - id (str): - The transaction ID with a length limit of 128 - characters. - revenue (float): - Required. Total non-zero revenue or grand - total associated with the transaction. This - value include shipping, tax, or other - adjustments to total revenue that you want to - include as part of your revenue calculations. - tax (float): - All the taxes associated with the - transaction. - cost (float): - All the costs associated with the products. These can be - manufacturing costs, shipping expenses not borne by the end - user, or any other costs, such that: - - - Profit = - [revenue][google.cloud.retail.v2beta.PurchaseTransaction.revenue] - - - [tax][google.cloud.retail.v2beta.PurchaseTransaction.tax] - - - [cost][google.cloud.retail.v2beta.PurchaseTransaction.cost] - currency_code (str): - Required. Currency code. Use three-character - ISO-4217 code. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - revenue = proto.Field( - proto.FLOAT, - number=2, - ) - tax = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - currency_code = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py deleted file mode 100644 index 990180c4..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import user_event as gcr_user_event - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'WriteUserEventRequest', - 'CollectUserEventRequest', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'RejoinUserEventsMetadata', - }, -) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (google.cloud.retail_v2beta.types.UserEvent): - Required. User event to write. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (str): - Required. URL encoded UserEvent proto with a - length limit of 2,000,000 characters. - uri (str): - The URL including cgi-parameters but - excluding the hash fragment with a length limit - of 5,000 characters. This is often more useful - than the referer URL, because many browsers only - send the domain for 3rd party requests. - ets (int): - The event timestamp in milliseconds. This - prevents browser caching of otherwise identical - get requests. The name is abbreviated to reduce - the payload bytes. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.STRING, - number=2, - ) - uri = proto.Field( - proto.STRING, - number=3, - ) - ets = proto.Field( - proto.INT64, - number=4, - ) - - -class RejoinUserEventsRequest(proto.Message): - r"""Request message for RejoinUserEvents method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event_rejoin_scope (google.cloud.retail_v2beta.types.RejoinUserEventsRequest.UserEventRejoinScope): - The type of the user event rejoin to define the scope and - range of the user events to be rejoined with the latest - product catalog. Defaults to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not - set, or set to an invalid integer value. - """ - class UserEventRejoinScope(proto.Enum): - r"""The scope of user events to be rejoined with the latest product - catalog. If the rejoining aims at reducing number of unjoined - events, set UserEventRejoinScope to UNJOINED_EVENTS. If the - rejoining aims at correcting product catalog information in joined - events, set UserEventRejoinScope to JOINED_EVENTS. If all events - needs to be rejoined, set UserEventRejoinScope to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. - """ - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 - JOINED_EVENTS = 1 - UNJOINED_EVENTS = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event_rejoin_scope = proto.Field( - proto.ENUM, - number=2, - enum=UserEventRejoinScope, - ) - - -class RejoinUserEventsResponse(proto.Message): - r"""Response message for RejoinUserEvents method. - - Attributes: - rejoined_user_events_count (int): - Number of user events that were joined with - latest product catalog. - """ - - rejoined_user_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -class RejoinUserEventsMetadata(proto.Message): - r"""Metadata for RejoinUserEvents method. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/mypy.ini b/owl-bot-staging/v2beta/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v2beta/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2beta/noxfile.py b/owl-bot-staging/v2beta/noxfile.py deleted file mode 100644 index 5abd48a4..00000000 --- a/owl-bot-staging/v2beta/noxfile.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.6", - "3.7", - "3.8", - "3.9", - "3.10", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==19.10b0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.9" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/retail_v2beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py deleted file mode 100644 index 09847366..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_AddCatalogAttribute_async] -from google.cloud import retail_v2beta - - -async def sample_add_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_AddCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py deleted file mode 100644 index 4f05ae26..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync] -from google.cloud import retail_v2beta - - -def sample_add_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py deleted file mode 100644 index 637bfe3a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetAttributesConfig_async] -from google.cloud import retail_v2beta - - -async def sample_get_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetAttributesConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py deleted file mode 100644 index c347bee2..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetAttributesConfig_sync] -from google.cloud import retail_v2beta - - -def sample_get_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetAttributesConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py deleted file mode 100644 index 2133e940..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetCompletionConfig_async] -from google.cloud import retail_v2beta - - -async def sample_get_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetCompletionConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py deleted file mode 100644 index bb9bf00d..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetCompletionConfig_sync] -from google.cloud import retail_v2beta - - -def sample_get_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetCompletionConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py deleted file mode 100644 index e598ec09..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetDefaultBranch_async] -from google.cloud import retail_v2beta - - -async def sample_get_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py deleted file mode 100644 index 6adcb072..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetDefaultBranch_sync] -from google.cloud import retail_v2beta - - -def sample_get_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py deleted file mode 100644 index b4e3df0e..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_ListCatalogs_async] -from google.cloud import retail_v2beta - - -async def sample_list_catalogs(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py deleted file mode 100644 index d938f3ae..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_ListCatalogs_sync] -from google.cloud import retail_v2beta - - -def sample_list_catalogs(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py deleted file mode 100644 index 032fb3c6..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async] -from google.cloud import retail_v2beta - - -async def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = await client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py deleted file mode 100644 index f1ecc22b..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync] -from google.cloud import retail_v2beta - - -def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py deleted file mode 100644 index 8a87262f..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReplaceCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async] -from google.cloud import retail_v2beta - - -async def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py deleted file mode 100644 index 24b38d05..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReplaceCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync] -from google.cloud import retail_v2beta - - -def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py deleted file mode 100644 index 6eec0779..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_SetDefaultBranch_async] -from google.cloud import retail_v2beta - - -async def sample_set_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - -# [END retail_v2beta_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py deleted file mode 100644 index a3deb8fd..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_SetDefaultBranch_sync] -from google.cloud import retail_v2beta - - -def sample_set_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - -# [END retail_v2beta_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py deleted file mode 100644 index b4a235ec..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async] -from google.cloud import retail_v2beta - - -async def sample_update_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - attributes_config = retail_v2beta.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2beta.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = await client.update_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py deleted file mode 100644 index 8f82ee5d..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync] -from google.cloud import retail_v2beta - - -def sample_update_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - attributes_config = retail_v2beta.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2beta.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = client.update_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py deleted file mode 100644 index 772504ff..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateCatalog_async] -from google.cloud import retail_v2beta - - -async def sample_update_catalog(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2beta.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2beta.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py deleted file mode 100644 index ed59d356..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateCatalog_sync] -from google.cloud import retail_v2beta - - -def sample_update_catalog(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2beta.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2beta.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py deleted file mode 100644 index 377166a7..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async] -from google.cloud import retail_v2beta - - -async def sample_update_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - completion_config = retail_v2beta.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2beta.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = await client.update_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py deleted file mode 100644 index f641f121..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync] -from google.cloud import retail_v2beta - - -def sample_update_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - completion_config = retail_v2beta.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2beta.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = client.update_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py deleted file mode 100644 index 96fdc6a6..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CompletionService_CompleteQuery_async] -from google.cloud import retail_v2beta - - -async def sample_complete_query(): - # Create a client - client = retail_v2beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py deleted file mode 100644 index afb0ba7d..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CompletionService_CompleteQuery_sync] -from google.cloud import retail_v2beta - - -def sample_complete_query(): - # Create a client - client = retail_v2beta.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py deleted file mode 100644 index 912753e9..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CompletionService_ImportCompletionData_async] -from google.cloud import retail_v2beta - - -async def sample_import_completion_data(): - # Create a client - client = retail_v2beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2beta.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py deleted file mode 100644 index 2cbd277d..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CompletionService_ImportCompletionData_sync] -from google.cloud import retail_v2beta - - -def sample_import_completion_data(): - # Create a client - client = retail_v2beta.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2beta.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py deleted file mode 100644 index 51e0cb4f..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_CreateControl_async] -from google.cloud import retail_v2beta - - -async def sample_create_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = await client.create_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_CreateControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py deleted file mode 100644 index 8d16b152..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_CreateControl_sync] -from google.cloud import retail_v2beta - - -def sample_create_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = client.create_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_CreateControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py deleted file mode 100644 index cb18f6ba..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_DeleteControl_async] -from google.cloud import retail_v2beta - - -async def sample_delete_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteControlRequest( - name="name_value", - ) - - # Make the request - await client.delete_control(request=request) - - -# [END retail_v2beta_generated_ControlService_DeleteControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py deleted file mode 100644 index 8a0d4f56..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_DeleteControl_sync] -from google.cloud import retail_v2beta - - -def sample_delete_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteControlRequest( - name="name_value", - ) - - # Make the request - client.delete_control(request=request) - - -# [END retail_v2beta_generated_ControlService_DeleteControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py deleted file mode 100644 index f9eeb9fd..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_GetControl_async] -from google.cloud import retail_v2beta - - -async def sample_get_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetControlRequest( - name="name_value", - ) - - # Make the request - response = await client.get_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_GetControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py deleted file mode 100644 index ee0de08a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_GetControl_sync] -from google.cloud import retail_v2beta - - -def sample_get_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetControlRequest( - name="name_value", - ) - - # Make the request - response = client.get_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_GetControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py deleted file mode 100644 index 9a645706..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListControls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_ListControls_async] -from google.cloud import retail_v2beta - - -async def sample_list_controls(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_ControlService_ListControls_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py deleted file mode 100644 index 97c8ba62..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListControls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_ListControls_sync] -from google.cloud import retail_v2beta - - -def sample_list_controls(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_ControlService_ListControls_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py deleted file mode 100644 index 9a42018c..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_UpdateControl_async] -from google.cloud import retail_v2beta - - -async def sample_update_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateControlRequest( - control=control, - ) - - # Make the request - response = await client.update_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_UpdateControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py deleted file mode 100644 index 2a306202..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_UpdateControl_sync] -from google.cloud import retail_v2beta - - -def sample_update_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateControlRequest( - control=control, - ) - - # Make the request - response = client.update_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_UpdateControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py deleted file mode 100644 index fd37548f..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_PredictionService_Predict_async] -from google.cloud import retail_v2beta - - -async def sample_predict(): - # Create a client - client = retail_v2beta.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py deleted file mode 100644 index 6975056e..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_PredictionService_Predict_sync] -from google.cloud import retail_v2beta - - -def sample_predict(): - # Create a client - client = retail_v2beta.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py deleted file mode 100644 index 92a7a7e1..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async] -from google.cloud import retail_v2beta - - -async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py deleted file mode 100644 index d828edde..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync] -from google.cloud import retail_v2beta - - -def sample_add_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py deleted file mode 100644 index ebcf5c80..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_AddLocalInventories_async] -from google.cloud import retail_v2beta - - -async def sample_add_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py deleted file mode 100644 index 9d3d9ab0..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_AddLocalInventories_sync] -from google.cloud import retail_v2beta - - -def sample_add_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py deleted file mode 100644 index 2bba20c0..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_CreateProduct_async] -from google.cloud import retail_v2beta - - -async def sample_create_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py deleted file mode 100644 index 32bd03e2..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_CreateProduct_sync] -from google.cloud import retail_v2beta - - -def sample_create_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py deleted file mode 100644 index 8f9591fa..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_DeleteProduct_async] -from google.cloud import retail_v2beta - - -async def sample_delete_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - -# [END retail_v2beta_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py deleted file mode 100644 index 56630734..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_DeleteProduct_sync] -from google.cloud import retail_v2beta - - -def sample_delete_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - -# [END retail_v2beta_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py deleted file mode 100644 index f8dcfc01..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_GetProduct_async] -from google.cloud import retail_v2beta - - -async def sample_get_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py deleted file mode 100644 index ab5cd918..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_GetProduct_sync] -from google.cloud import retail_v2beta - - -def sample_get_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py deleted file mode 100644 index aa4256cc..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_ImportProducts_async] -from google.cloud import retail_v2beta - - -async def sample_import_products(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2beta.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py deleted file mode 100644 index b4bc8314..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_ImportProducts_sync] -from google.cloud import retail_v2beta - - -def sample_import_products(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2beta.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py deleted file mode 100644 index e259ecd6..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_ListProducts_async] -from google.cloud import retail_v2beta - - -async def sample_list_products(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py deleted file mode 100644 index 5cb40315..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_ListProducts_sync] -from google.cloud import retail_v2beta - - -def sample_list_products(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py deleted file mode 100644 index 1b18eb50..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async] -from google.cloud import retail_v2beta - - -async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py deleted file mode 100644 index f430e360..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync] -from google.cloud import retail_v2beta - - -def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py deleted file mode 100644 index 55fba819..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_RemoveLocalInventories_async] -from google.cloud import retail_v2beta - - -async def sample_remove_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py deleted file mode 100644 index 31d1e58e..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_RemoveLocalInventories_sync] -from google.cloud import retail_v2beta - - -def sample_remove_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py deleted file mode 100644 index 9b467025..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_SetInventory_async] -from google.cloud import retail_v2beta - - -async def sample_set_inventory(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2beta.Product() - inventory.title = "title_value" - - request = retail_v2beta.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py deleted file mode 100644 index d1061827..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_SetInventory_sync] -from google.cloud import retail_v2beta - - -def sample_set_inventory(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2beta.Product() - inventory.title = "title_value" - - request = retail_v2beta.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py deleted file mode 100644 index 8d9590cd..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_UpdateProduct_async] -from google.cloud import retail_v2beta - - -async def sample_update_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py deleted file mode 100644 index fc614e58..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_UpdateProduct_sync] -from google.cloud import retail_v2beta - - -def sample_update_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py deleted file mode 100644 index 967c9102..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_SearchService_Search_async] -from google.cloud import retail_v2beta - - -async def sample_search(): - # Create a client - client = retail_v2beta.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py deleted file mode 100644 index 1e6a5045..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_SearchService_Search_sync] -from google.cloud import retail_v2beta - - -def sample_search(): - # Create a client - client = retail_v2beta.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py deleted file mode 100644 index d6554386..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_AddControl_async] -from google.cloud import retail_v2beta - - -async def sample_add_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.add_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_AddControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py deleted file mode 100644 index e61e4e2a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_AddControl_sync] -from google.cloud import retail_v2beta - - -def sample_add_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.add_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_AddControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py deleted file mode 100644 index b09fadf2..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_CreateServingConfig_async] -from google.cloud import retail_v2beta - - -async def sample_create_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = await client.create_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_CreateServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py deleted file mode 100644 index 5d4c0993..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync] -from google.cloud import retail_v2beta - - -def sample_create_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = client.create_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py deleted file mode 100644 index c0b03659..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async] -from google.cloud import retail_v2beta - - -async def sample_delete_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_serving_config(request=request) - - -# [END retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py deleted file mode 100644 index 1db19c0a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync] -from google.cloud import retail_v2beta - - -def sample_delete_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_serving_config(request=request) - - -# [END retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py deleted file mode 100644 index 64f6aeef..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_GetServingConfig_async] -from google.cloud import retail_v2beta - - -async def sample_get_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_GetServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py deleted file mode 100644 index 1cfab934..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_GetServingConfig_sync] -from google.cloud import retail_v2beta - - -def sample_get_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_GetServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py deleted file mode 100644 index 7ad0a3aa..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServingConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_ListServingConfigs_async] -from google.cloud import retail_v2beta - - -async def sample_list_serving_configs(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_ServingConfigService_ListServingConfigs_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py deleted file mode 100644 index 6a3e7e2a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServingConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync] -from google.cloud import retail_v2beta - - -def sample_list_serving_configs(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py deleted file mode 100644 index c9994a00..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_RemoveControl_async] -from google.cloud import retail_v2beta - - -async def sample_remove_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.remove_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_RemoveControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py deleted file mode 100644 index db6dfa93..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_RemoveControl_sync] -from google.cloud import retail_v2beta - - -def sample_remove_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.remove_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_RemoveControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py deleted file mode 100644 index 2a6bd3a0..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async] -from google.cloud import retail_v2beta - - -async def sample_update_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = await client.update_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py deleted file mode 100644 index f6441e46..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync] -from google.cloud import retail_v2beta - - -def sample_update_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = client.update_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py deleted file mode 100644 index ce80fabf..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_CollectUserEvent_async] -from google.cloud import retail_v2beta - - -async def sample_collect_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py deleted file mode 100644 index ff7df192..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_CollectUserEvent_sync] -from google.cloud import retail_v2beta - - -def sample_collect_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py deleted file mode 100644 index 259c3424..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_ImportUserEvents_async] -from google.cloud import retail_v2beta - - -async def sample_import_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2beta.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py deleted file mode 100644 index 89e0ec02..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_ImportUserEvents_sync] -from google.cloud import retail_v2beta - - -def sample_import_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2beta.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py deleted file mode 100644 index 6f97cab1..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_PurgeUserEvents_async] -from google.cloud import retail_v2beta - - -async def sample_purge_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py deleted file mode 100644 index 212d2693..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_PurgeUserEvents_sync] -from google.cloud import retail_v2beta - - -def sample_purge_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py deleted file mode 100644 index 8a95e668..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_RejoinUserEvents_async] -from google.cloud import retail_v2beta - - -async def sample_rejoin_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py deleted file mode 100644 index ebd635b8..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_RejoinUserEvents_sync] -from google.cloud import retail_v2beta - - -def sample_rejoin_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py deleted file mode 100644 index 71317cac..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_WriteUserEvent_async] -from google.cloud import retail_v2beta - - -async def sample_write_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py deleted file mode 100644 index e93e4df4..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_WriteUserEvent_sync] -from google.cloud import retail_v2beta - - -def sample_write_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json b/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json deleted file mode 100644 index 591f20ca..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json +++ /dev/null @@ -1,6913 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.retail.v2beta", - "version": "v2beta" - } - ], - "language": "PYTHON", - "name": "google-cloud-retail" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.add_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "AddCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "add_catalog_attribute" - }, - "description": "Sample for AddCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_AddCatalogAttribute_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.add_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "AddCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "add_catalog_attribute" - }, - "description": "Sample for AddCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetAttributesConfigRequest" - }, - { - "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.retail_v2beta.types.AttributesConfig", - "shortName": "get_attributes_config" - }, - "description": "Sample for GetAttributesConfig", - "file": "retail_v2beta_generated_catalog_service_get_attributes_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetAttributesConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_attributes_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetAttributesConfigRequest" - }, - { - "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.retail_v2beta.types.AttributesConfig", - "shortName": "get_attributes_config" - }, - "description": "Sample for GetAttributesConfig", - "file": "retail_v2beta_generated_catalog_service_get_attributes_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetAttributesConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_attributes_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_completion_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetCompletionConfigRequest" - }, - { - "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.retail_v2beta.types.CompletionConfig", - "shortName": "get_completion_config" - }, - "description": "Sample for GetCompletionConfig", - "file": "retail_v2beta_generated_catalog_service_get_completion_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetCompletionConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_completion_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_completion_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetCompletionConfigRequest" - }, - { - "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.retail_v2beta.types.CompletionConfig", - "shortName": "get_completion_config" - }, - "description": "Sample for GetCompletionConfig", - "file": "retail_v2beta_generated_catalog_service_get_completion_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetCompletionConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_completion_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2beta_generated_catalog_service_get_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetDefaultBranch_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2beta_generated_catalog_service_get_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetDefaultBranch_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListCatalogsRequest" - }, - { - "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.retail_v2beta.services.catalog_service.pagers.ListCatalogsAsyncPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2beta_generated_catalog_service_list_catalogs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_ListCatalogs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_list_catalogs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListCatalogsRequest" - }, - { - "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.retail_v2beta.services.catalog_service.pagers.ListCatalogsPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2beta_generated_catalog_service_list_catalogs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_ListCatalogs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_list_catalogs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.remove_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "RemoveCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "remove_catalog_attribute" - }, - "description": "Sample for RemoveCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.remove_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "RemoveCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "remove_catalog_attribute" - }, - "description": "Sample for RemoveCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.replace_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ReplaceCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "replace_catalog_attribute" - }, - "description": "Sample for ReplaceCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.replace_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ReplaceCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "replace_catalog_attribute" - }, - "description": "Sample for ReplaceCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2beta_generated_catalog_service_set_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_SetDefaultBranch_async", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_set_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2beta_generated_catalog_service_set_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_SetDefaultBranch_sync", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_set_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest" - }, - { - "name": "attributes_config", - "type": "google.cloud.retail_v2beta.types.AttributesConfig" - }, - { - "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.retail_v2beta.types.AttributesConfig", - "shortName": "update_attributes_config" - }, - "description": "Sample for UpdateAttributesConfig", - "file": "retail_v2beta_generated_catalog_service_update_attributes_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_attributes_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest" - }, - { - "name": "attributes_config", - "type": "google.cloud.retail_v2beta.types.AttributesConfig" - }, - { - "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.retail_v2beta.types.AttributesConfig", - "shortName": "update_attributes_config" - }, - "description": "Sample for UpdateAttributesConfig", - "file": "retail_v2beta_generated_catalog_service_update_attributes_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_attributes_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2beta.types.Catalog" - }, - { - "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.retail_v2beta.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2beta_generated_catalog_service_update_catalog_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateCatalog_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_catalog_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2beta.types.Catalog" - }, - { - "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.retail_v2beta.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2beta_generated_catalog_service_update_catalog_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateCatalog_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_catalog_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_completion_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest" - }, - { - "name": "completion_config", - "type": "google.cloud.retail_v2beta.types.CompletionConfig" - }, - { - "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.retail_v2beta.types.CompletionConfig", - "shortName": "update_completion_config" - }, - "description": "Sample for UpdateCompletionConfig", - "file": "retail_v2beta_generated_catalog_service_update_completion_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_completion_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_completion_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest" - }, - { - "name": "completion_config", - "type": "google.cloud.retail_v2beta.types.CompletionConfig" - }, - { - "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.retail_v2beta.types.CompletionConfig", - "shortName": "update_completion_config" - }, - "description": "Sample for UpdateCompletionConfig", - "file": "retail_v2beta_generated_catalog_service_update_completion_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_completion_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2beta.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2beta_generated_completion_service_complete_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CompletionService_CompleteQuery_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_completion_service_complete_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CompletionServiceClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2beta.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2beta_generated_completion_service_complete_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CompletionService_CompleteQuery_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_completion_service_complete_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2beta.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2beta_generated_completion_service_import_completion_data_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CompletionService_ImportCompletionData_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_completion_service_import_completion_data_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CompletionServiceClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2beta.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2beta_generated_completion_service_import_completion_data_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CompletionService_ImportCompletionData_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_completion_service_import_completion_data_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.create_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.CreateControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "CreateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateControlRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "control", - "type": "google.cloud.retail_v2beta.types.Control" - }, - { - "name": "control_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.retail_v2beta.types.Control", - "shortName": "create_control" - }, - "description": "Sample for CreateControl", - "file": "retail_v2beta_generated_control_service_create_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_CreateControl_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_create_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.create_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.CreateControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "CreateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateControlRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "control", - "type": "google.cloud.retail_v2beta.types.Control" - }, - { - "name": "control_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.retail_v2beta.types.Control", - "shortName": "create_control" - }, - "description": "Sample for CreateControl", - "file": "retail_v2beta_generated_control_service_create_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_CreateControl_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_create_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.delete_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.DeleteControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "DeleteControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteControlRequest" - }, - { - "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_control" - }, - "description": "Sample for DeleteControl", - "file": "retail_v2beta_generated_control_service_delete_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_DeleteControl_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_delete_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.delete_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.DeleteControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "DeleteControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteControlRequest" - }, - { - "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_control" - }, - "description": "Sample for DeleteControl", - "file": "retail_v2beta_generated_control_service_delete_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_DeleteControl_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_delete_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.get_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.GetControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "GetControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetControlRequest" - }, - { - "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.retail_v2beta.types.Control", - "shortName": "get_control" - }, - "description": "Sample for GetControl", - "file": "retail_v2beta_generated_control_service_get_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_GetControl_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_get_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.get_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.GetControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "GetControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetControlRequest" - }, - { - "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.retail_v2beta.types.Control", - "shortName": "get_control" - }, - "description": "Sample for GetControl", - "file": "retail_v2beta_generated_control_service_get_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_GetControl_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_get_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.list_controls", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.ListControls", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "ListControls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListControlsRequest" - }, - { - "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.retail_v2beta.services.control_service.pagers.ListControlsAsyncPager", - "shortName": "list_controls" - }, - "description": "Sample for ListControls", - "file": "retail_v2beta_generated_control_service_list_controls_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_ListControls_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_list_controls_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.list_controls", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.ListControls", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "ListControls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListControlsRequest" - }, - { - "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.retail_v2beta.services.control_service.pagers.ListControlsPager", - "shortName": "list_controls" - }, - "description": "Sample for ListControls", - "file": "retail_v2beta_generated_control_service_list_controls_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_ListControls_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_list_controls_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.update_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.UpdateControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "UpdateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateControlRequest" - }, - { - "name": "control", - "type": "google.cloud.retail_v2beta.types.Control" - }, - { - "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.retail_v2beta.types.Control", - "shortName": "update_control" - }, - "description": "Sample for UpdateControl", - "file": "retail_v2beta_generated_control_service_update_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_UpdateControl_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_update_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.update_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.UpdateControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "UpdateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateControlRequest" - }, - { - "name": "control", - "type": "google.cloud.retail_v2beta.types.Control" - }, - { - "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.retail_v2beta.types.Control", - "shortName": "update_control" - }, - "description": "Sample for UpdateControl", - "file": "retail_v2beta_generated_control_service_update_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_UpdateControl_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_update_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.PredictionServiceAsyncClient", - "shortName": "PredictionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.PredictionServiceAsyncClient.predict", - "method": { - "fullName": "google.cloud.retail.v2beta.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2beta.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2beta_generated_prediction_service_predict_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_PredictionService_Predict_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_prediction_service_predict_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.PredictionServiceClient", - "shortName": "PredictionServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.PredictionServiceClient.predict", - "method": { - "fullName": "google.cloud.retail.v2beta.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2beta.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2beta_generated_prediction_service_predict_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_PredictionService_Predict_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_prediction_service_predict_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2beta_generated_product_service_add_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_add_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2beta_generated_product_service_add_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_add_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2beta_generated_product_service_add_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_AddLocalInventories_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_add_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2beta_generated_product_service_add_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_AddLocalInventories_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_add_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "name": "product_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.retail_v2beta.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2beta_generated_product_service_create_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_CreateProduct_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_create_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "name": "product_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.retail_v2beta.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2beta_generated_product_service_create_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_CreateProduct_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_create_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2beta_generated_product_service_delete_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_DeleteProduct_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_delete_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2beta_generated_product_service_delete_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_DeleteProduct_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_delete_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetProductRequest" - }, - { - "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.retail_v2beta.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2beta_generated_product_service_get_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_GetProduct_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_get_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetProductRequest" - }, - { - "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.retail_v2beta.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2beta_generated_product_service_get_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_GetProduct_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_get_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2beta_generated_product_service_import_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_ImportProducts_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_import_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2beta_generated_product_service_import_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_ImportProducts_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_import_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListProductsRequest" - }, - { - "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.retail_v2beta.services.product_service.pagers.ListProductsAsyncPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2beta_generated_product_service_list_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_ListProducts_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_list_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListProductsRequest" - }, - { - "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.retail_v2beta.services.product_service.pagers.ListProductsPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2beta_generated_product_service_list_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_ListProducts_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_list_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2beta_generated_product_service_remove_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_remove_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2beta_generated_product_service_remove_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_RemoveLocalInventories_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_remove_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2beta_generated_product_service_remove_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_RemoveLocalInventories_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_remove_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2beta_generated_product_service_set_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_SetInventory_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_set_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2beta_generated_product_service_set_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_SetInventory_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_set_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "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.retail_v2beta.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2beta_generated_product_service_update_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_UpdateProduct_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_update_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "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.retail_v2beta.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2beta_generated_product_service_update_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_UpdateProduct_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_update_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.SearchServiceAsyncClient.search", - "method": { - "fullName": "google.cloud.retail.v2beta.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2beta.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2beta_generated_search_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_SearchService_Search_async", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_search_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.SearchServiceClient", - "shortName": "SearchServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.SearchServiceClient.search", - "method": { - "fullName": "google.cloud.retail.v2beta.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2beta.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.services.search_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2beta_generated_search_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_SearchService_Search_sync", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_search_service_search_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.add_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.AddControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "AddControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "add_control" - }, - "description": "Sample for AddControl", - "file": "retail_v2beta_generated_serving_config_service_add_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_AddControl_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_add_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.add_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.AddControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "AddControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "add_control" - }, - "description": "Sample for AddControl", - "file": "retail_v2beta_generated_serving_config_service_add_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_AddControl_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_add_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.create_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.CreateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "CreateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateServingConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2beta.types.ServingConfig" - }, - { - "name": "serving_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "create_serving_config" - }, - "description": "Sample for CreateServingConfig", - "file": "retail_v2beta_generated_serving_config_service_create_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_CreateServingConfig_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_create_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.create_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.CreateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "CreateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateServingConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2beta.types.ServingConfig" - }, - { - "name": "serving_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "create_serving_config" - }, - "description": "Sample for CreateServingConfig", - "file": "retail_v2beta_generated_serving_config_service_create_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_create_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.delete_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.DeleteServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "DeleteServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteServingConfigRequest" - }, - { - "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_serving_config" - }, - "description": "Sample for DeleteServingConfig", - "file": "retail_v2beta_generated_serving_config_service_delete_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_delete_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.delete_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.DeleteServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "DeleteServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteServingConfigRequest" - }, - { - "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_serving_config" - }, - "description": "Sample for DeleteServingConfig", - "file": "retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.get_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.GetServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "GetServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetServingConfigRequest" - }, - { - "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.retail_v2beta.types.ServingConfig", - "shortName": "get_serving_config" - }, - "description": "Sample for GetServingConfig", - "file": "retail_v2beta_generated_serving_config_service_get_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_GetServingConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_get_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.get_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.GetServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "GetServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetServingConfigRequest" - }, - { - "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.retail_v2beta.types.ServingConfig", - "shortName": "get_serving_config" - }, - "description": "Sample for GetServingConfig", - "file": "retail_v2beta_generated_serving_config_service_get_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_GetServingConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_get_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.list_serving_configs", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.ListServingConfigs", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "ListServingConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListServingConfigsRequest" - }, - { - "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.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager", - "shortName": "list_serving_configs" - }, - "description": "Sample for ListServingConfigs", - "file": "retail_v2beta_generated_serving_config_service_list_serving_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_ListServingConfigs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_list_serving_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.list_serving_configs", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.ListServingConfigs", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "ListServingConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListServingConfigsRequest" - }, - { - "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.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsPager", - "shortName": "list_serving_configs" - }, - "description": "Sample for ListServingConfigs", - "file": "retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.remove_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.RemoveControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "RemoveControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "remove_control" - }, - "description": "Sample for RemoveControl", - "file": "retail_v2beta_generated_serving_config_service_remove_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_RemoveControl_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_remove_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.remove_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.RemoveControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "RemoveControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "remove_control" - }, - "description": "Sample for RemoveControl", - "file": "retail_v2beta_generated_serving_config_service_remove_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_RemoveControl_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_remove_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.update_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.UpdateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "UpdateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2beta.types.ServingConfig" - }, - { - "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.retail_v2beta.types.ServingConfig", - "shortName": "update_serving_config" - }, - "description": "Sample for UpdateServingConfig", - "file": "retail_v2beta_generated_serving_config_service_update_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_update_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.update_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.UpdateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "UpdateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2beta.types.ServingConfig" - }, - { - "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.retail_v2beta.types.ServingConfig", - "shortName": "update_serving_config" - }, - "description": "Sample for UpdateServingConfig", - "file": "retail_v2beta_generated_serving_config_service_update_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_update_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2beta_generated_user_event_service_collect_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_CollectUserEvent_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_collect_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2beta_generated_user_event_service_collect_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_CollectUserEvent_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_collect_user_event_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2beta_generated_user_event_service_import_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_ImportUserEvents_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_import_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2beta_generated_user_event_service_import_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_ImportUserEvents_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_import_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2beta_generated_user_event_service_purge_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_PurgeUserEvents_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_purge_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2beta_generated_user_event_service_purge_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_PurgeUserEvents_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_purge_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2beta_generated_user_event_service_rejoin_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_RejoinUserEvents_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_rejoin_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_RejoinUserEvents_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2beta_generated_user_event_service_write_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_WriteUserEvent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_write_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2beta_generated_user_event_service_write_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_WriteUserEvent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_write_user_event_sync.py" - } - ] -} diff --git a/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py b/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py deleted file mode 100644 index dbd16de7..00000000 --- a/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py +++ /dev/null @@ -1,218 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class retailCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_catalog_attribute': ('attributes_config', 'catalog_attribute', ), - 'add_control': ('serving_config', 'control_id', ), - 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), - 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), - 'create_control': ('parent', 'control', 'control_id', ), - 'create_product': ('parent', 'product', 'product_id', ), - 'create_serving_config': ('parent', 'serving_config', 'serving_config_id', ), - 'delete_control': ('name', ), - 'delete_product': ('name', ), - 'delete_serving_config': ('name', ), - 'get_attributes_config': ('name', ), - 'get_completion_config': ('name', ), - 'get_control': ('name', ), - 'get_default_branch': ('catalog', ), - 'get_product': ('name', ), - 'get_serving_config': ('name', ), - 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), - 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), - 'import_user_events': ('parent', 'input_config', 'errors_config', ), - 'list_catalogs': ('parent', 'page_size', 'page_token', ), - 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', ), - 'list_serving_configs': ('parent', 'page_size', 'page_token', ), - 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), - 'purge_user_events': ('parent', 'filter', 'force', ), - 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), - 'remove_catalog_attribute': ('attributes_config', 'key', ), - 'remove_control': ('serving_config', 'control_id', ), - 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), - 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), - 'replace_catalog_attribute': ('attributes_config', 'catalog_attribute', 'update_mask', ), - 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), - 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), - 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), - 'update_attributes_config': ('attributes_config', 'update_mask', ), - 'update_catalog': ('catalog', 'update_mask', ), - 'update_completion_config': ('completion_config', 'update_mask', ), - 'update_control': ('control', 'update_mask', ), - 'update_product': ('product', 'update_mask', 'allow_missing', ), - 'update_serving_config': ('serving_config', 'update_mask', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=retailCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the retail client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2beta/setup.py b/owl-bot-staging/v2beta/setup.py deleted file mode 100644 index 1103510b..00000000 --- a/owl-bot-staging/v2beta/setup.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-retail', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-retail", - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 2.8.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'googleapis-common-protos >= 1.55.0, <2.0.0dev', - 'proto-plus >= 1.19.7', - ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v2beta/tests/__init__.py b/owl-bot-staging/v2beta/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/tests/unit/__init__.py b/owl-bot-staging/v2beta/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py b/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py deleted file mode 100644 index a933c6e0..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py +++ /dev/null @@ -1,3844 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.catalog_service import CatalogServiceAsyncClient -from google.cloud.retail_v2beta.services.catalog_service import CatalogServiceClient -from google.cloud.retail_v2beta.services.catalog_service import pagers -from google.cloud.retail_v2beta.services.catalog_service import transports -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CatalogServiceClient._get_default_mtls_endpoint(None) is None - assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CatalogServiceGrpcTransport, "grpc"), - (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_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", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_catalog_service_client_get_transport_class(): - transport = CatalogServiceClient.get_transport_class() - available_transports = [ - transports.CatalogServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CatalogServiceClient.get_transport_class("grpc") - assert transport == transports.CatalogServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CatalogServiceClient, CatalogServiceAsyncClient -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_catalog_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ListCatalogsRequest, - dict, -]) -def test_list_catalogs(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalogs), - '__call__') as call: - client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - -@pytest.mark.asyncio -async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_catalogs_async_from_dict(): - await test_list_catalogs_async(request_type=dict) - - -def test_list_catalogs_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = catalog_service.ListCatalogsResponse() - client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_catalogs( - 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_catalogs_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_catalogs_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_catalogs( - 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_catalogs_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - - -def test_list_catalogs_pager(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_catalogs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, catalog.Catalog) - for i in results) -def test_list_catalogs_pages(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = list(client.list_catalogs(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_catalogs_async_pager(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_catalogs(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, catalog.Catalog) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_catalogs_async_pages(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCatalogRequest, - dict, -]) -def test_update_catalog(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - ) - response = client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_catalog_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalog), - '__call__') as call: - client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - -@pytest.mark.asyncio -async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_catalog_async_from_dict(): - await test_update_catalog_async(request_type=dict) - - -def test_update_catalog_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = gcr_catalog.Catalog() - client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_catalog_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -def test_update_catalog_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_catalog_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.SetDefaultBranchRequest, - dict, -]) -def test_set_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_set_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_set_default_branch_async_from_dict(): - await test_set_default_branch_async(request_type=dict) - - -def test_set_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = None - client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_set_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_set_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetDefaultBranchRequest, - dict, -]) -def test_get_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - ) - response = client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -def test_get_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_default_branch), - '__call__') as call: - client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - )) - response = await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -@pytest.mark.asyncio -async def test_get_default_branch_async_from_dict(): - await test_get_default_branch_async(request_type=dict) - - -def test_get_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = catalog_service.GetDefaultBranchResponse() - client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_get_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_get_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetCompletionConfigRequest, - dict, -]) -def test_get_completion_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - ) - response = client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -def test_get_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_completion_config), - '__call__') as call: - client.get_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - -@pytest.mark.asyncio -async def test_get_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCompletionConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - )) - response = await client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -@pytest.mark.asyncio -async def test_get_completion_config_async_from_dict(): - await test_get_completion_config_async(request_type=dict) - - -def test_get_completion_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCompletionConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - call.return_value = catalog.CompletionConfig() - client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_completion_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCompletionConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - await client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_completion_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_completion_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_completion_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_completion_config( - catalog_service.GetCompletionConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_completion_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_completion_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_completion_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_completion_config( - catalog_service.GetCompletionConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCompletionConfigRequest, - dict, -]) -def test_update_completion_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - ) - response = client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -def test_update_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_completion_config), - '__call__') as call: - client.update_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - -@pytest.mark.asyncio -async def test_update_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCompletionConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - )) - response = await client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -@pytest.mark.asyncio -async def test_update_completion_config_async_from_dict(): - await test_update_completion_config_async(request_type=dict) - - -def test_update_completion_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCompletionConfigRequest() - - request.completion_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - call.return_value = catalog.CompletionConfig() - client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'completion_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_completion_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCompletionConfigRequest() - - request.completion_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - await client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'completion_config.name=name_value', - ) in kw['metadata'] - - -def test_update_completion_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_completion_config( - completion_config=catalog.CompletionConfig(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].completion_config - mock_val = catalog.CompletionConfig(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_completion_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_completion_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_completion_config( - completion_config=catalog.CompletionConfig(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].completion_config - mock_val = catalog.CompletionConfig(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_completion_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetAttributesConfigRequest, - dict, -]) -def test_get_attributes_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_get_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_attributes_config), - '__call__') as call: - client.get_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - -@pytest.mark.asyncio -async def test_get_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetAttributesConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_get_attributes_config_async_from_dict(): - await test_get_attributes_config_async(request_type=dict) - - -def test_get_attributes_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetAttributesConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_attributes_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetAttributesConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_attributes_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_attributes_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_attributes_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_attributes_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_attributes_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_attributes_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateAttributesConfigRequest, - dict, -]) -def test_update_attributes_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_update_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_attributes_config), - '__call__') as call: - client.update_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - -@pytest.mark.asyncio -async def test_update_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateAttributesConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_update_attributes_config_async_from_dict(): - await test_update_attributes_config_async(request_type=dict) - - -def test_update_attributes_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateAttributesConfigRequest() - - request.attributes_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_attributes_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateAttributesConfigRequest() - - request.attributes_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config.name=name_value', - ) in kw['metadata'] - - -def test_update_attributes_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_attributes_config( - attributes_config=catalog.AttributesConfig(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].attributes_config - mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_attributes_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_attributes_config( - attributes_config=catalog.AttributesConfig(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].attributes_config - mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.AddCatalogAttributeRequest, - dict, -]) -def test_add_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_add_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - client.add_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_add_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.AddCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_add_catalog_attribute_async_from_dict(): - await test_add_catalog_attribute_async(request_type=dict) - - -def test_add_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.AddCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.AddCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - catalog_service.RemoveCatalogAttributeRequest, - dict, -]) -def test_remove_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_remove_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - client.remove_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.RemoveCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_async_from_dict(): - await test_remove_catalog_attribute_async(request_type=dict) - - -def test_remove_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.RemoveCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.RemoveCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ReplaceCatalogAttributeRequest, - dict, -]) -def test_replace_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_replace_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - client.replace_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ReplaceCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_async_from_dict(): - await test_replace_catalog_attribute_async(request_type=dict) - - -def test_replace_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ReplaceCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ReplaceCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CatalogServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.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 = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CatalogServiceGrpcTransport, - ) - -def test_catalog_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_catalog_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_catalogs', - 'update_catalog', - 'set_default_branch', - 'get_default_branch', - 'get_completion_config', - 'update_completion_config', - 'get_attributes_config', - 'update_attributes_config', - 'add_catalog_attribute', - 'remove_catalog_attribute', - 'replace_catalog_attribute', - ) - 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_catalog_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.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport( - 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_catalog_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.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport() - adc.assert_called_once() - - -def test_catalog_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) - CatalogServiceClient() - 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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -def test_catalog_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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - transports.CatalogServiceRestTransport, - ], -) -def test_catalog_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.CatalogServiceGrpcTransport, grpc_helpers), - (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_catalog_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_no_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_with_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_catalog_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcTransport( - 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_catalog_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcAsyncIOTransport( - 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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_attributes_config_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.attributes_config_path(project, location, catalog) - assert expected == actual - - -def test_parse_attributes_config_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CatalogServiceClient.attributes_config_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_attributes_config_path(path) - assert expected == actual - -def test_branch_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = CatalogServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "branch": "clam", - } - path = CatalogServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_branch_path(path) - assert expected == actual - -def test_catalog_path(): - project = "whelk" - location = "octopus" - catalog = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - } - path = CatalogServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_completion_config_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.completion_config_path(project, location, catalog) - assert expected == actual - - -def test_parse_completion_config_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - } - path = CatalogServiceClient.completion_config_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_completion_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CatalogServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = CatalogServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = CatalogServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = CatalogServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CatalogServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = CatalogServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = CatalogServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = CatalogServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = CatalogServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CatalogServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py deleted file mode 100644 index 8abb5922..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py +++ /dev/null @@ -1,1502 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.completion_service import CompletionServiceAsyncClient -from google.cloud.retail_v2beta.services.completion_service import CompletionServiceClient -from google.cloud.retail_v2beta.services.completion_service import transports -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CompletionServiceClient._get_default_mtls_endpoint(None) is None - assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CompletionServiceGrpcTransport, "grpc"), - (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_completion_service_client_get_transport_class(): - transport = CompletionServiceClient.get_transport_class() - available_transports = [ - transports.CompletionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CompletionServiceClient.get_transport_class("grpc") - assert transport == transports.CompletionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CompletionServiceClient, CompletionServiceAsyncClient -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_completion_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CompletionServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - ) - response = client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - -@pytest.mark.asyncio -async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - )) - response = await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -@pytest.mark.asyncio -async def test_complete_query_async_from_dict(): - await test_complete_query_async(request_type=dict) - - -def test_complete_query_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = completion_service.CompleteQueryResponse() - client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_complete_query_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) - await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportCompletionDataRequest, - dict, -]) -def test_import_completion_data(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_completion_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - -@pytest.mark.asyncio -async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_completion_data_async_from_dict(): - await test_import_completion_data_async(request_type=dict) - - -def test_import_completion_data_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # 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_completion_data_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CompletionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CompletionServiceGrpcTransport, - ) - -def test_completion_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_completion_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'complete_query', - 'import_completion_data', - ) - 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_completion_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_completion_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport() - adc.assert_called_once() - - -def test_completion_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CompletionServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, - ], -) -def test_completion_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionServiceGrpcTransport, grpc_helpers), - (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_completion_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_no_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_with_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_completion_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_completion_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_completion_service_grpc_lro_client(): - client = CompletionServiceClient( - 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_completion_service_grpc_lro_async_client(): - client = CompletionServiceAsyncClient( - 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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CompletionServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CompletionServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CompletionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CompletionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = CompletionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CompletionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CompletionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CompletionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = CompletionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CompletionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CompletionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CompletionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CompletionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py deleted file mode 100644 index 33a56677..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py +++ /dev/null @@ -1,2605 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.control_service import ControlServiceAsyncClient -from google.cloud.retail_v2beta.services.control_service import ControlServiceClient -from google.cloud.retail_v2beta.services.control_service import pagers -from google.cloud.retail_v2beta.services.control_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.cloud.retail_v2beta.types import search_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ControlServiceClient._get_default_mtls_endpoint(None) is None - assert ControlServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ControlServiceClient, "grpc"), - (ControlServiceAsyncClient, "grpc_asyncio"), -]) -def test_control_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ControlServiceGrpcTransport, "grpc"), - (transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_control_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", [ - (ControlServiceClient, "grpc"), - (ControlServiceAsyncClient, "grpc_asyncio"), -]) -def test_control_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_control_service_client_get_transport_class(): - transport = ControlServiceClient.get_transport_class() - available_transports = [ - transports.ControlServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ControlServiceClient.get_transport_class("grpc") - assert transport == transports.ControlServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -def test_control_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(ControlServiceClient, '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(ControlServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "true"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "false"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_control_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ControlServiceClient, ControlServiceAsyncClient -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -def test_control_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_control_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_control_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_control_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.control_service.transports.ControlServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ControlServiceClient( - 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", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_control_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.CreateControlRequest, - dict, -]) -def test_create_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_create_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.create_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - -@pytest.mark.asyncio -async def test_create_control_async(transport: str = 'grpc_asyncio', request_type=control_service.CreateControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_create_control_async_from_dict(): - await test_create_control_async(request_type=dict) - - -def test_create_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.CreateControlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - call.return_value = gcr_control.Control() - client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.CreateControlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - await client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_control( - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) - assert arg == mock_val - arg = args[0].control_id - mock_val = 'control_id_value' - assert arg == mock_val - - -def test_create_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.CreateControlRequest(), - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_id_value', - ) - -@pytest.mark.asyncio -async def test_create_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_control( - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) - assert arg == mock_val - arg = args[0].control_id - mock_val = 'control_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.CreateControlRequest(), - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.DeleteControlRequest, - dict, -]) -def test_delete_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.delete_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - -@pytest.mark.asyncio -async def test_delete_control_async(transport: str = 'grpc_asyncio', request_type=control_service.DeleteControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_control_async_from_dict(): - await test_delete_control_async(request_type=dict) - - -def test_delete_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.DeleteControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__call__') as call: - call.return_value = None - client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.DeleteControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__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_control( - 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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.DeleteControlRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__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_control( - 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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.DeleteControlRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.UpdateControlRequest, - dict, -]) -def test_update_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_update_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.update_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - -@pytest.mark.asyncio -async def test_update_control_async(transport: str = 'grpc_asyncio', request_type=control_service.UpdateControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_update_control_async_from_dict(): - await test_update_control_async(request_type=dict) - - -def test_update_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.UpdateControlRequest() - - request.control.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - call.return_value = gcr_control.Control() - client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'control.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.UpdateControlRequest() - - request.control.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - await client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'control.name=name_value', - ) in kw['metadata'] - - -def test_update_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_control( - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_control( - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.GetControlRequest, - dict, -]) -def test_get_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_get_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.get_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - -@pytest.mark.asyncio -async def test_get_control_async(transport: str = 'grpc_asyncio', request_type=control_service.GetControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_get_control_async_from_dict(): - await test_get_control_async(request_type=dict) - - -def test_get_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.GetControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - call.return_value = control.Control() - client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.GetControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) - await client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_control( - 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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.GetControlRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_control( - 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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.GetControlRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.ListControlsRequest, - dict, -]) -def test_list_controls(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_controls_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_controls), - '__call__') as call: - client.list_controls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - -@pytest.mark.asyncio -async def test_list_controls_async(transport: str = 'grpc_asyncio', request_type=control_service.ListControlsRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_controls_async_from_dict(): - await test_list_controls_async(request_type=dict) - - -def test_list_controls_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.ListControlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - call.return_value = control_service.ListControlsResponse() - client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_controls_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.ListControlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) - await client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_controls_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_controls( - 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_controls_flattened_error(): - client = ControlServiceClient( - credentials=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_controls( - control_service.ListControlsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_controls_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_controls( - 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_controls_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_controls( - control_service.ListControlsRequest(), - parent='parent_value', - ) - - -def test_list_controls_pager(transport_name: str = "grpc"): - client = ControlServiceClient( - 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_controls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_controls(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, control.Control) - for i in results) -def test_list_controls_pages(transport_name: str = "grpc"): - client = ControlServiceClient( - 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_controls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - pages = list(client.list_controls(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_controls_async_pager(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_controls(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, control.Control) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_controls_async_pages(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_controls(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ControlServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ControlServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ControlServiceClient.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 = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ControlServiceGrpcTransport, - ) - -def test_control_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ControlServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_control_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.control_service.transports.ControlServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ControlServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_control', - 'delete_control', - 'update_control', - 'get_control', - 'list_controls', - ) - 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_control_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.retail_v2beta.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ControlServiceTransport( - 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_control_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.retail_v2beta.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ControlServiceTransport() - adc.assert_called_once() - - -def test_control_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) - ControlServiceClient() - 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.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - ], -) -def test_control_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.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - transports.ControlServiceRestTransport, - ], -) -def test_control_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.ControlServiceGrpcTransport, grpc_helpers), - (transports.ControlServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_control_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_control_service_host_no_port(transport_name): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_control_service_host_with_port(transport_name): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_control_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ControlServiceGrpcTransport( - 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_control_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ControlServiceGrpcAsyncIOTransport( - 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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = ControlServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = ControlServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_control_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - control = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) - actual = ControlServiceClient.control_path(project, location, catalog, control) - assert expected == actual - - -def test_parse_control_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "control": "clam", - } - path = ControlServiceClient.control_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_control_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ControlServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ControlServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ControlServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ControlServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ControlServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ControlServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ControlServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ControlServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.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 = ControlServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ControlServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.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.ControlServiceTransport, '_prep_wrapped_messages') as prep: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ControlServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ControlServiceClient.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 = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ControlServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ControlServiceClient( - 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", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py deleted file mode 100644 index 37ea8b9f..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py +++ /dev/null @@ -1,1330 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.prediction_service import PredictionServiceAsyncClient -from google.cloud.retail_v2beta.services.prediction_service import PredictionServiceClient -from google.cloud.retail_v2beta.services.prediction_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import prediction_service -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import promotion -from google.cloud.retail_v2beta.types import user_event -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PredictionServiceClient._get_default_mtls_endpoint(None) is None - assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PredictionServiceGrpcTransport, "grpc"), - (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_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", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_prediction_service_client_get_transport_class(): - transport = PredictionServiceClient.get_transport_class() - available_transports = [ - transports.PredictionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = PredictionServiceClient.get_transport_class("grpc") - assert transport == transports.PredictionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - PredictionServiceClient, PredictionServiceAsyncClient -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_prediction_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - prediction_service.PredictRequest, - dict, -]) -def test_predict(request_type, transport: str = 'grpc'): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - response = client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - -@pytest.mark.asyncio -async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - )) - response = await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -@pytest.mark.asyncio -async def test_predict_async_from_dict(): - await test_predict_async(request_type=dict) - - -def test_predict_field_headers(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = prediction_service.PredictResponse() - client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_predict_field_headers_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) - await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PredictionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PredictionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.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 = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, - ) - -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'predict', - ) - 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport( - 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport() - adc.assert_called_once() - - -def test_prediction_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) - PredictionServiceClient() - 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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -def test_prediction_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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - transports.PredictionServiceRestTransport, - ], -) -def test_prediction_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.PredictionServiceGrpcTransport, grpc_helpers), - (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_prediction_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_no_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_with_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_prediction_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcTransport( - 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_prediction_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcAsyncIOTransport( - 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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_product_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - product = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - "branch": "winkle", - "product": "nautilus", - } - path = PredictionServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PredictionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = PredictionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = PredictionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = PredictionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PredictionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = PredictionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = PredictionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = PredictionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = PredictionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PredictionServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py deleted file mode 100644 index 1f4c5dc7..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py +++ /dev/null @@ -1,4136 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.product_service import ProductServiceAsyncClient -from google.cloud.retail_v2beta.services.product_service import ProductServiceClient -from google.cloud.retail_v2beta.services.product_service import pagers -from google.cloud.retail_v2beta.services.product_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.cloud.retail_v2beta.types import promotion -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ProductServiceClient._get_default_mtls_endpoint(None) is None - assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ProductServiceGrpcTransport, "grpc"), - (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_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", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_product_service_client_get_transport_class(): - transport = ProductServiceClient.get_transport_class() - available_transports = [ - transports.ProductServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ProductServiceClient.get_transport_class("grpc") - assert transport == transports.ProductServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_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(ProductServiceClient, '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(ProductServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ProductServiceClient, ProductServiceAsyncClient -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_product_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.CreateProductRequest, - dict, -]) -def test_create_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_create_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - -@pytest.mark.asyncio -async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_create_product_async_from_dict(): - await test_create_product_async(request_type=dict) - - -def test_create_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - - -def test_create_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - -@pytest.mark.asyncio -async def test_create_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.GetProductRequest, - dict, -]) -def test_get_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_get_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - -@pytest.mark.asyncio -async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_get_product_async_from_dict(): - await test_get_product_async(request_type=dict) - - -def test_get_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = product.Product() - client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.GetProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.GetProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.ListProductsRequest, - dict, -]) -def test_list_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - -@pytest.mark.asyncio -async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_products_async_from_dict(): - await test_list_products_async(request_type=dict) - - -def test_list_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = product_service.ListProductsResponse() - client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_products( - 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_products_flattened_error(): - client = ProductServiceClient( - credentials=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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_products_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_products( - 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_products_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - - -def test_list_products_pager(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_products(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, product.Product) - for i in results) -def test_list_products_pages(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = list(client.list_products(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_products_async_pager(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_products(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, product.Product) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_products_async_pages(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_products(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - product_service.UpdateProductRequest, - dict, -]) -def test_update_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_update_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - -@pytest.mark.asyncio -async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_update_product_async_from_dict(): - await test_update_product_async(request_type=dict) - - -def test_update_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -def test_update_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.DeleteProductRequest, - dict, -]) -def test_delete_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - -@pytest.mark.asyncio -async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_product_async_from_dict(): - await test_delete_product_async(request_type=dict) - - -def test_delete_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = None - client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportProductsRequest, - dict, -]) -def test_import_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - -@pytest.mark.asyncio -async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__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_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_products_async_from_dict(): - await test_import_products_async(request_type=dict) - - -def test_import_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - product_service.SetInventoryRequest, - dict, -]) -def test_set_inventory(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_inventory_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - -@pytest.mark.asyncio -async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_inventory_async_from_dict(): - await test_set_inventory_async(request_type=dict) - - -def test_set_inventory_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_inventory_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -def test_set_inventory_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_set_inventory_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_set_inventory_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_inventory_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddFulfillmentPlacesRequest, - dict, -]) -def test_add_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async_from_dict(): - await test_add_fulfillment_places_async(request_type=dict) - - -def test_add_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveFulfillmentPlacesRequest, - dict, -]) -def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async_from_dict(): - await test_remove_fulfillment_places_async(request_type=dict) - - -def test_remove_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddLocalInventoriesRequest, - dict, -]) -def test_add_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_local_inventories_async_from_dict(): - await test_add_local_inventories_async(request_type=dict) - - -def test_add_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveLocalInventoriesRequest, - dict, -]) -def test_remove_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_local_inventories_async_from_dict(): - await test_remove_local_inventories_async(request_type=dict) - - -def test_remove_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProductServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ProductServiceClient.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 = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProductServiceGrpcTransport, - ) - -def test_product_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_product_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.product_service.transports.ProductServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_product', - 'get_product', - 'list_products', - 'update_product', - 'delete_product', - 'import_products', - 'set_inventory', - 'add_fulfillment_places', - 'remove_fulfillment_places', - 'add_local_inventories', - 'remove_local_inventories', - ) - 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_product_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.retail_v2beta.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport( - 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_product_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.retail_v2beta.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport() - adc.assert_called_once() - - -def test_product_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) - ProductServiceClient() - 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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - ], -) -def test_product_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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - transports.ProductServiceRestTransport, - ], -) -def test_product_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.ProductServiceGrpcTransport, grpc_helpers), - (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_product_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_no_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_with_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_product_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcTransport( - 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_product_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcAsyncIOTransport( - 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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_product_service_grpc_lro_client(): - client = ProductServiceClient( - 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_product_service_grpc_lro_async_client(): - client = ProductServiceAsyncClient( - 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" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = ProductServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = ProductServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = ProductServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = ProductServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProductServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ProductServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProductServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ProductServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProductServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ProductServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ProductServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ProductServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ProductServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ProductServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ProductServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py deleted file mode 100644 index 55c11327..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py +++ /dev/null @@ -1,1547 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.search_service import SearchServiceAsyncClient -from google.cloud.retail_v2beta.services.search_service import SearchServiceClient -from google.cloud.retail_v2beta.services.search_service import pagers -from google.cloud.retail_v2beta.services.search_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SearchServiceClient._get_default_mtls_endpoint(None) is None - assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SearchServiceGrpcTransport, "grpc"), - (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_search_service_client_get_transport_class(): - transport = SearchServiceClient.get_transport_class() - available_transports = [ - transports.SearchServiceGrpcTransport, - ] - assert transport in available_transports - - transport = SearchServiceClient.get_transport_class("grpc") - assert transport == transports.SearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SearchServiceClient, SearchServiceAsyncClient -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SearchServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - search_service.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - - -def test_search_field_headers(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = search_service.SearchResponse() - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_field_headers_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_search_pager(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('placement', ''), - )), - ) - pager = client.search(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_async_pager(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, - ) - -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_search_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_search_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport() - adc.assert_called_once() - - -def test_search_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SearchServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - transports.SearchServiceRestTransport, - ], -) -def test_search_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SearchServiceGrpcTransport, grpc_helpers), - (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_search_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_no_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_with_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_branch_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = SearchServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = SearchServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = SearchServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = SearchServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py deleted file mode 100644 index d88b744c..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py +++ /dev/null @@ -1,3330 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.serving_config_service import ServingConfigServiceAsyncClient -from google.cloud.retail_v2beta.services.serving_config_service import ServingConfigServiceClient -from google.cloud.retail_v2beta.services.serving_config_service import pagers -from google.cloud.retail_v2beta.services.serving_config_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ServingConfigServiceClient._get_default_mtls_endpoint(None) is None - assert ServingConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServingConfigServiceClient, "grpc"), - (ServingConfigServiceAsyncClient, "grpc_asyncio"), -]) -def test_serving_config_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ServingConfigServiceGrpcTransport, "grpc"), - (transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_serving_config_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", [ - (ServingConfigServiceClient, "grpc"), - (ServingConfigServiceAsyncClient, "grpc_asyncio"), -]) -def test_serving_config_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_serving_config_service_client_get_transport_class(): - transport = ServingConfigServiceClient.get_transport_class() - available_transports = [ - transports.ServingConfigServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ServingConfigServiceClient.get_transport_class("grpc") - assert transport == transports.ServingConfigServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -def test_serving_config_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(ServingConfigServiceClient, '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(ServingConfigServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "true"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "false"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_serving_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ServingConfigServiceClient, ServingConfigServiceAsyncClient -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -def test_serving_config_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_serving_config_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_serving_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_serving_config_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ServingConfigServiceClient( - 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", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_serving_config_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.CreateServingConfigRequest, - dict, -]) -def test_create_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_create_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.create_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - -@pytest.mark.asyncio -async def test_create_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.CreateServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_create_serving_config_async_from_dict(): - await test_create_serving_config_async(request_type=dict) - - -def test_create_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.CreateServingConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.CreateServingConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_serving_config( - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].serving_config - mock_val = gcr_serving_config.ServingConfig(name='name_value') - assert arg == mock_val - arg = args[0].serving_config_id - mock_val = 'serving_config_id_value' - assert arg == mock_val - - -def test_create_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.CreateServingConfigRequest(), - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_serving_config( - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].serving_config - mock_val = gcr_serving_config.ServingConfig(name='name_value') - assert arg == mock_val - arg = args[0].serving_config_id - mock_val = 'serving_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.CreateServingConfigRequest(), - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.DeleteServingConfigRequest, - dict, -]) -def test_delete_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.delete_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - -@pytest.mark.asyncio -async def test_delete_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.DeleteServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_serving_config_async_from_dict(): - await test_delete_serving_config_async(request_type=dict) - - -def test_delete_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.DeleteServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__call__') as call: - call.return_value = None - client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.DeleteServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__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_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.DeleteServingConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__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_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.DeleteServingConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.UpdateServingConfigRequest, - dict, -]) -def test_update_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_update_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.update_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - -@pytest.mark.asyncio -async def test_update_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.UpdateServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_update_serving_config_async_from_dict(): - await test_update_serving_config_async(request_type=dict) - - -def test_update_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.UpdateServingConfigRequest() - - request.serving_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.UpdateServingConfigRequest() - - request.serving_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config.name=name_value', - ) in kw['metadata'] - - -def test_update_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_serving_config( - serving_config=gcr_serving_config.ServingConfig(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].serving_config - mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_serving_config( - serving_config=gcr_serving_config.ServingConfig(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].serving_config - mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.GetServingConfigRequest, - dict, -]) -def test_get_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_get_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.get_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - -@pytest.mark.asyncio -async def test_get_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.GetServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_get_serving_config_async_from_dict(): - await test_get_serving_config_async(request_type=dict) - - -def test_get_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.GetServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - call.return_value = serving_config.ServingConfig() - client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.GetServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) - await client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.GetServingConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.GetServingConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.ListServingConfigsRequest, - dict, -]) -def test_list_serving_configs(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_serving_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_configs), - '__call__') as call: - client.list_serving_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - -@pytest.mark.asyncio -async def test_list_serving_configs_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.ListServingConfigsRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_serving_configs_async_from_dict(): - await test_list_serving_configs_async(request_type=dict) - - -def test_list_serving_configs_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.ListServingConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - call.return_value = serving_config_service.ListServingConfigsResponse() - client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_serving_configs_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.ListServingConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) - await client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_serving_configs_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_serving_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_serving_configs_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_serving_configs_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_serving_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_serving_configs_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent='parent_value', - ) - - -def test_list_serving_configs_pager(transport_name: str = "grpc"): - client = ServingConfigServiceClient( - 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_serving_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_serving_configs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, serving_config.ServingConfig) - for i in results) -def test_list_serving_configs_pages(transport_name: str = "grpc"): - client = ServingConfigServiceClient( - 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_serving_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_serving_configs(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_serving_configs_async_pager(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_serving_configs(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, serving_config.ServingConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_serving_configs_async_pages(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_serving_configs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - serving_config_service.AddControlRequest, - dict, -]) -def test_add_control(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_add_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - client.add_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - -@pytest.mark.asyncio -async def test_add_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.AddControlRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_add_control_async_from_dict(): - await test_add_control_async(request_type=dict) - - -def test_add_control_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.AddControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_control_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.AddControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_add_control_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.add_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - - -def test_add_control_flattened_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_control( - serving_config_service.AddControlRequest(), - serving_config='serving_config_value', - ) - -@pytest.mark.asyncio -async def test_add_control_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.add_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_control_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_control( - serving_config_service.AddControlRequest(), - serving_config='serving_config_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.RemoveControlRequest, - dict, -]) -def test_remove_control(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_remove_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - client.remove_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - -@pytest.mark.asyncio -async def test_remove_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.RemoveControlRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_remove_control_async_from_dict(): - await test_remove_control_async(request_type=dict) - - -def test_remove_control_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.RemoveControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_control_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.RemoveControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_remove_control_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.remove_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - - -def test_remove_control_flattened_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config='serving_config_value', - ) - -@pytest.mark.asyncio -async def test_remove_control_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.remove_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_control_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config='serving_config_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ServingConfigServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ServingConfigServiceClient.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 = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ServingConfigServiceGrpcTransport, - ) - -def test_serving_config_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ServingConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_serving_config_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ServingConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_serving_config', - 'delete_serving_config', - 'update_serving_config', - 'get_serving_config', - 'list_serving_configs', - 'add_control', - 'remove_control', - ) - 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_serving_config_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.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServingConfigServiceTransport( - 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_serving_config_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.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServingConfigServiceTransport() - adc.assert_called_once() - - -def test_serving_config_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) - ServingConfigServiceClient() - 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.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - ], -) -def test_serving_config_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.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - transports.ServingConfigServiceRestTransport, - ], -) -def test_serving_config_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.ServingConfigServiceGrpcTransport, grpc_helpers), - (transports.ServingConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_serving_config_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_serving_config_service_host_no_port(transport_name): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_serving_config_service_host_with_port(transport_name): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_serving_config_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServingConfigServiceGrpcTransport( - 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_serving_config_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( - 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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = ServingConfigServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = ServingConfigServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - serving_config = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, serving_config=serving_config, ) - actual = ServingConfigServiceClient.serving_config_path(project, location, catalog, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "serving_config": "clam", - } - path = ServingConfigServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ServingConfigServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ServingConfigServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ServingConfigServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ServingConfigServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ServingConfigServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ServingConfigServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ServingConfigServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ServingConfigServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.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 = ServingConfigServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ServingConfigServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.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.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ServingConfigServiceClient.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 = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ServingConfigServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ServingConfigServiceClient( - 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", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py deleted file mode 100644 index 6ff51098..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py +++ /dev/null @@ -1,2039 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.retail_v2beta.services.user_event_service import UserEventServiceClient -from google.cloud.retail_v2beta.services.user_event_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import promotion -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, UserEventServiceAsyncClient -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - ) - response = client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = user_event.UserEvent() - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) - await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeUserEventsRequest, - dict, -]) -def test_purge_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - -@pytest.mark.asyncio -async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_user_events_async_from_dict(): - await test_purge_user_events_async(request_type=dict) - - -def test_purge_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_purge_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.RejoinUserEventsRequest, - dict, -]) -def test_rejoin_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_rejoin_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - -@pytest.mark.asyncio -async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_rejoin_user_events_async_from_dict(): - await test_rejoin_user_events_async(request_type=dict) - - -def test_rejoin_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_rejoin_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'purge_user_events', - 'import_user_events', - 'rejoin_user_events', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_user_event_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_user_event_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -def test_user_event_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - UserEventServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, - ], -) -def test_user_event_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_no_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_with_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = UserEventServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = UserEventServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_product_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - product = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - "branch": "whelk", - "product": "octopus", - } - path = UserEventServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/tests/unit/gapic/retail_v2/test_catalog_service.py b/tests/unit/gapic/retail_v2/test_catalog_service.py index 01a1aa46..5f48de87 100644 --- a/tests/unit/gapic/retail_v2/test_catalog_service.py +++ b/tests/unit/gapic/retail_v2/test_catalog_service.py @@ -227,6 +227,7 @@ def test_catalog_service_client_client_options( 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 @@ -244,6 +245,7 @@ def test_catalog_service_client_client_options( 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 @@ -261,6 +263,7 @@ def test_catalog_service_client_client_options( 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 @@ -290,6 +293,25 @@ def test_catalog_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -357,6 +379,7 @@ def test_catalog_service_client_mtls_env_auto( 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 @@ -391,6 +414,7 @@ def test_catalog_service_client_mtls_env_auto( 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. @@ -413,6 +437,7 @@ def test_catalog_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -527,6 +552,7 @@ def test_catalog_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -565,6 +591,7 @@ def test_catalog_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -585,6 +612,7 @@ def test_catalog_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -623,6 +651,7 @@ def test_catalog_service_client_create_channel_credentials_file( 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. @@ -2024,6 +2053,29 @@ def test_catalog_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + transports.CatalogServiceRestTransport, + ], +) +def test_catalog_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", [ @@ -2521,4 +2573,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2/test_completion_service.py b/tests/unit/gapic/retail_v2/test_completion_service.py index 2ee29ba3..b3eff55d 100644 --- a/tests/unit/gapic/retail_v2/test_completion_service.py +++ b/tests/unit/gapic/retail_v2/test_completion_service.py @@ -238,6 +238,7 @@ def test_completion_service_client_client_options( 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 @@ -255,6 +256,7 @@ def test_completion_service_client_client_options( 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 @@ -272,6 +274,7 @@ def test_completion_service_client_client_options( 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 @@ -301,6 +304,25 @@ def test_completion_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -378,6 +400,7 @@ def test_completion_service_client_mtls_env_auto( 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 @@ -412,6 +435,7 @@ def test_completion_service_client_mtls_env_auto( 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. @@ -434,6 +458,7 @@ def test_completion_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -548,6 +573,7 @@ def test_completion_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -586,6 +612,7 @@ def test_completion_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -606,6 +633,7 @@ def test_completion_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -644,6 +672,7 @@ def test_completion_service_client_create_channel_credentials_file( 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. @@ -1206,6 +1235,29 @@ def test_completion_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, + ], +) +def test_completion_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -1711,4 +1763,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2/test_prediction_service.py b/tests/unit/gapic/retail_v2/test_prediction_service.py index abcd5e11..7ee15865 100644 --- a/tests/unit/gapic/retail_v2/test_prediction_service.py +++ b/tests/unit/gapic/retail_v2/test_prediction_service.py @@ -238,6 +238,7 @@ def test_prediction_service_client_client_options( 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 @@ -255,6 +256,7 @@ def test_prediction_service_client_client_options( 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 @@ -272,6 +274,7 @@ def test_prediction_service_client_client_options( 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 @@ -301,6 +304,25 @@ def test_prediction_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -378,6 +400,7 @@ def test_prediction_service_client_mtls_env_auto( 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 @@ -412,6 +435,7 @@ def test_prediction_service_client_mtls_env_auto( 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. @@ -434,6 +458,7 @@ def test_prediction_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -548,6 +573,7 @@ def test_prediction_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -586,6 +612,7 @@ def test_prediction_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -606,6 +633,7 @@ def test_prediction_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -644,6 +672,7 @@ def test_prediction_service_client_create_channel_credentials_file( 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. @@ -1050,6 +1079,29 @@ def test_prediction_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + transports.PredictionServiceRestTransport, + ], +) +def test_prediction_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", [ @@ -1529,4 +1581,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2/test_product_service.py b/tests/unit/gapic/retail_v2/test_product_service.py index acd7889a..c982d5ae 100644 --- a/tests/unit/gapic/retail_v2/test_product_service.py +++ b/tests/unit/gapic/retail_v2/test_product_service.py @@ -241,6 +241,7 @@ def test_product_service_client_client_options( 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 @@ -258,6 +259,7 @@ def test_product_service_client_client_options( 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 @@ -275,6 +277,7 @@ def test_product_service_client_client_options( 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 @@ -304,6 +307,25 @@ def test_product_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -371,6 +393,7 @@ def test_product_service_client_mtls_env_auto( 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 @@ -405,6 +428,7 @@ def test_product_service_client_mtls_env_auto( 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. @@ -427,6 +451,7 @@ def test_product_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -541,6 +566,7 @@ def test_product_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -579,6 +605,7 @@ def test_product_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -599,6 +626,7 @@ def test_product_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -637,6 +665,7 @@ def test_product_service_client_create_channel_credentials_file( 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. @@ -3823,6 +3852,29 @@ def test_product_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + transports.ProductServiceRestTransport, + ], +) +def test_product_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", [ @@ -4362,4 +4414,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2/test_search_service.py b/tests/unit/gapic/retail_v2/test_search_service.py index 2f548379..f1af1c5a 100644 --- a/tests/unit/gapic/retail_v2/test_search_service.py +++ b/tests/unit/gapic/retail_v2/test_search_service.py @@ -223,6 +223,7 @@ def test_search_service_client_client_options( 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 @@ -240,6 +241,7 @@ def test_search_service_client_client_options( 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 @@ -257,6 +259,7 @@ def test_search_service_client_client_options( 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 @@ -286,6 +289,25 @@ def test_search_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -353,6 +375,7 @@ def test_search_service_client_mtls_env_auto( 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 @@ -387,6 +410,7 @@ def test_search_service_client_mtls_env_auto( 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. @@ -409,6 +433,7 @@ def test_search_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -523,6 +548,7 @@ def test_search_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -561,6 +587,7 @@ def test_search_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -581,6 +608,7 @@ def test_search_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -619,6 +647,7 @@ def test_search_service_client_create_channel_credentials_file( 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. @@ -1227,6 +1256,29 @@ def test_search_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + transports.SearchServiceRestTransport, + ], +) +def test_search_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -1730,4 +1782,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2/test_user_event_service.py b/tests/unit/gapic/retail_v2/test_user_event_service.py index babc824f..be8770cc 100644 --- a/tests/unit/gapic/retail_v2/test_user_event_service.py +++ b/tests/unit/gapic/retail_v2/test_user_event_service.py @@ -252,6 +252,7 @@ def test_user_event_service_client_client_options( 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 @@ -269,6 +270,7 @@ def test_user_event_service_client_client_options( 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 @@ -286,6 +288,7 @@ def test_user_event_service_client_client_options( 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 @@ -315,6 +318,25 @@ def test_user_event_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -392,6 +414,7 @@ def test_user_event_service_client_mtls_env_auto( 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 @@ -426,6 +449,7 @@ def test_user_event_service_client_mtls_env_auto( 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. @@ -448,6 +472,7 @@ def test_user_event_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -562,6 +587,7 @@ def test_user_event_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -600,6 +626,7 @@ def test_user_event_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -620,6 +647,7 @@ def test_user_event_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -658,6 +686,7 @@ def test_user_event_service_client_create_channel_credentials_file( 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. @@ -1748,6 +1777,29 @@ def test_user_event_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +def test_user_event_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -2284,4 +2336,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2alpha/test_catalog_service.py b/tests/unit/gapic/retail_v2alpha/test_catalog_service.py index 31c05f41..1a4a2b89 100644 --- a/tests/unit/gapic/retail_v2alpha/test_catalog_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_catalog_service.py @@ -228,6 +228,7 @@ def test_catalog_service_client_client_options( 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 @@ -245,6 +246,7 @@ def test_catalog_service_client_client_options( 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 @@ -262,6 +264,7 @@ def test_catalog_service_client_client_options( 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 @@ -291,6 +294,25 @@ def test_catalog_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -358,6 +380,7 @@ def test_catalog_service_client_mtls_env_auto( 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 @@ -392,6 +415,7 @@ def test_catalog_service_client_mtls_env_auto( 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. @@ -414,6 +438,7 @@ def test_catalog_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -528,6 +553,7 @@ def test_catalog_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -566,6 +592,7 @@ def test_catalog_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -586,6 +613,7 @@ def test_catalog_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -624,6 +652,7 @@ def test_catalog_service_client_create_channel_credentials_file( 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. @@ -3665,6 +3694,29 @@ def test_catalog_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + transports.CatalogServiceRestTransport, + ], +) +def test_catalog_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", [ @@ -4214,4 +4266,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2alpha/test_completion_service.py b/tests/unit/gapic/retail_v2alpha/test_completion_service.py index f0a22498..0cea0e6e 100644 --- a/tests/unit/gapic/retail_v2alpha/test_completion_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_completion_service.py @@ -238,6 +238,7 @@ def test_completion_service_client_client_options( 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 @@ -255,6 +256,7 @@ def test_completion_service_client_client_options( 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 @@ -272,6 +274,7 @@ def test_completion_service_client_client_options( 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 @@ -301,6 +304,25 @@ def test_completion_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -378,6 +400,7 @@ def test_completion_service_client_mtls_env_auto( 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 @@ -412,6 +435,7 @@ def test_completion_service_client_mtls_env_auto( 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. @@ -434,6 +458,7 @@ def test_completion_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -548,6 +573,7 @@ def test_completion_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -586,6 +612,7 @@ def test_completion_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -606,6 +633,7 @@ def test_completion_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -644,6 +672,7 @@ def test_completion_service_client_create_channel_credentials_file( 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. @@ -1206,6 +1235,29 @@ def test_completion_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, + ], +) +def test_completion_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -1711,4 +1763,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2alpha/test_control_service.py b/tests/unit/gapic/retail_v2alpha/test_control_service.py index d29ea51c..e42c6ba3 100644 --- a/tests/unit/gapic/retail_v2alpha/test_control_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_control_service.py @@ -228,6 +228,7 @@ def test_control_service_client_client_options( 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 @@ -245,6 +246,7 @@ def test_control_service_client_client_options( 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 @@ -262,6 +264,7 @@ def test_control_service_client_client_options( 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 @@ -291,6 +294,25 @@ def test_control_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -358,6 +380,7 @@ def test_control_service_client_mtls_env_auto( 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 @@ -392,6 +415,7 @@ def test_control_service_client_mtls_env_auto( 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. @@ -414,6 +438,7 @@ def test_control_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -528,6 +553,7 @@ def test_control_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -566,6 +592,7 @@ def test_control_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -586,6 +613,7 @@ def test_control_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -624,6 +652,7 @@ def test_control_service_client_create_channel_credentials_file( 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. @@ -2403,6 +2432,29 @@ def test_control_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + transports.ControlServiceRestTransport, + ], +) +def test_control_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", [ @@ -2900,4 +2952,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2alpha/test_prediction_service.py b/tests/unit/gapic/retail_v2alpha/test_prediction_service.py index 6b71c9a5..5251b25a 100644 --- a/tests/unit/gapic/retail_v2alpha/test_prediction_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_prediction_service.py @@ -238,6 +238,7 @@ def test_prediction_service_client_client_options( 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 @@ -255,6 +256,7 @@ def test_prediction_service_client_client_options( 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 @@ -272,6 +274,7 @@ def test_prediction_service_client_client_options( 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 @@ -301,6 +304,25 @@ def test_prediction_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -378,6 +400,7 @@ def test_prediction_service_client_mtls_env_auto( 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 @@ -412,6 +435,7 @@ def test_prediction_service_client_mtls_env_auto( 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. @@ -434,6 +458,7 @@ def test_prediction_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -548,6 +573,7 @@ def test_prediction_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -586,6 +612,7 @@ def test_prediction_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -606,6 +633,7 @@ def test_prediction_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -644,6 +672,7 @@ def test_prediction_service_client_create_channel_credentials_file( 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. @@ -1050,6 +1079,29 @@ def test_prediction_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + transports.PredictionServiceRestTransport, + ], +) +def test_prediction_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", [ @@ -1529,4 +1581,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2alpha/test_product_service.py b/tests/unit/gapic/retail_v2alpha/test_product_service.py index 1135c8bc..7db42d58 100644 --- a/tests/unit/gapic/retail_v2alpha/test_product_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_product_service.py @@ -241,6 +241,7 @@ def test_product_service_client_client_options( 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 @@ -258,6 +259,7 @@ def test_product_service_client_client_options( 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 @@ -275,6 +277,7 @@ def test_product_service_client_client_options( 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 @@ -304,6 +307,25 @@ def test_product_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -371,6 +393,7 @@ def test_product_service_client_mtls_env_auto( 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 @@ -405,6 +428,7 @@ def test_product_service_client_mtls_env_auto( 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. @@ -427,6 +451,7 @@ def test_product_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -541,6 +566,7 @@ def test_product_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -579,6 +605,7 @@ def test_product_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -599,6 +626,7 @@ def test_product_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -637,6 +665,7 @@ def test_product_service_client_create_channel_credentials_file( 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. @@ -3972,6 +4001,29 @@ def test_product_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + transports.ProductServiceRestTransport, + ], +) +def test_product_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", [ @@ -4511,4 +4563,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2alpha/test_search_service.py b/tests/unit/gapic/retail_v2alpha/test_search_service.py index bca4b7b0..ec18ac32 100644 --- a/tests/unit/gapic/retail_v2alpha/test_search_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_search_service.py @@ -223,6 +223,7 @@ def test_search_service_client_client_options( 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 @@ -240,6 +241,7 @@ def test_search_service_client_client_options( 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 @@ -257,6 +259,7 @@ def test_search_service_client_client_options( 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 @@ -286,6 +289,25 @@ def test_search_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -353,6 +375,7 @@ def test_search_service_client_mtls_env_auto( 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 @@ -387,6 +410,7 @@ def test_search_service_client_mtls_env_auto( 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. @@ -409,6 +433,7 @@ def test_search_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -523,6 +548,7 @@ def test_search_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -561,6 +587,7 @@ def test_search_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -581,6 +608,7 @@ def test_search_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -619,6 +647,7 @@ def test_search_service_client_create_channel_credentials_file( 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. @@ -1227,6 +1256,29 @@ def test_search_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + transports.SearchServiceRestTransport, + ], +) +def test_search_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -1730,4 +1782,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py b/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py index 91ea9bd6..2077185f 100644 --- a/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py @@ -236,6 +236,7 @@ def test_serving_config_service_client_client_options( 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 @@ -253,6 +254,7 @@ def test_serving_config_service_client_client_options( 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 @@ -270,6 +272,7 @@ def test_serving_config_service_client_client_options( 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 @@ -299,6 +302,25 @@ def test_serving_config_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -376,6 +398,7 @@ def test_serving_config_service_client_mtls_env_auto( 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 @@ -410,6 +433,7 @@ def test_serving_config_service_client_mtls_env_auto( 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. @@ -432,6 +456,7 @@ def test_serving_config_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -550,6 +575,7 @@ def test_serving_config_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -588,6 +614,7 @@ def test_serving_config_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -608,6 +635,7 @@ def test_serving_config_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -646,6 +674,7 @@ def test_serving_config_service_client_create_channel_credentials_file( 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. @@ -3137,6 +3166,29 @@ def test_serving_config_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + transports.ServingConfigServiceRestTransport, + ], +) +def test_serving_config_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", [ @@ -3641,4 +3693,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2alpha/test_user_event_service.py b/tests/unit/gapic/retail_v2alpha/test_user_event_service.py index df327adf..c278649c 100644 --- a/tests/unit/gapic/retail_v2alpha/test_user_event_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_user_event_service.py @@ -252,6 +252,7 @@ def test_user_event_service_client_client_options( 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 @@ -269,6 +270,7 @@ def test_user_event_service_client_client_options( 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 @@ -286,6 +288,7 @@ def test_user_event_service_client_client_options( 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 @@ -315,6 +318,25 @@ def test_user_event_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -392,6 +414,7 @@ def test_user_event_service_client_mtls_env_auto( 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 @@ -426,6 +449,7 @@ def test_user_event_service_client_mtls_env_auto( 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. @@ -448,6 +472,7 @@ def test_user_event_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -562,6 +587,7 @@ def test_user_event_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -600,6 +626,7 @@ def test_user_event_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -620,6 +647,7 @@ def test_user_event_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -658,6 +686,7 @@ def test_user_event_service_client_create_channel_credentials_file( 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. @@ -1748,6 +1777,29 @@ def test_user_event_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +def test_user_event_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -2284,4 +2336,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2beta/test_catalog_service.py b/tests/unit/gapic/retail_v2beta/test_catalog_service.py index 0eeeafe5..b165b826 100644 --- a/tests/unit/gapic/retail_v2beta/test_catalog_service.py +++ b/tests/unit/gapic/retail_v2beta/test_catalog_service.py @@ -228,6 +228,7 @@ def test_catalog_service_client_client_options( 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 @@ -245,6 +246,7 @@ def test_catalog_service_client_client_options( 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 @@ -262,6 +264,7 @@ def test_catalog_service_client_client_options( 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 @@ -291,6 +294,25 @@ def test_catalog_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -358,6 +380,7 @@ def test_catalog_service_client_mtls_env_auto( 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 @@ -392,6 +415,7 @@ def test_catalog_service_client_mtls_env_auto( 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. @@ -414,6 +438,7 @@ def test_catalog_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -528,6 +553,7 @@ def test_catalog_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -566,6 +592,7 @@ def test_catalog_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -586,6 +613,7 @@ def test_catalog_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -624,6 +652,7 @@ def test_catalog_service_client_create_channel_credentials_file( 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. @@ -3665,6 +3694,29 @@ def test_catalog_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + transports.CatalogServiceRestTransport, + ], +) +def test_catalog_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", [ @@ -4214,4 +4266,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2beta/test_completion_service.py b/tests/unit/gapic/retail_v2beta/test_completion_service.py index b2316f13..77ca8c12 100644 --- a/tests/unit/gapic/retail_v2beta/test_completion_service.py +++ b/tests/unit/gapic/retail_v2beta/test_completion_service.py @@ -238,6 +238,7 @@ def test_completion_service_client_client_options( 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 @@ -255,6 +256,7 @@ def test_completion_service_client_client_options( 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 @@ -272,6 +274,7 @@ def test_completion_service_client_client_options( 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 @@ -301,6 +304,25 @@ def test_completion_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -378,6 +400,7 @@ def test_completion_service_client_mtls_env_auto( 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 @@ -412,6 +435,7 @@ def test_completion_service_client_mtls_env_auto( 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. @@ -434,6 +458,7 @@ def test_completion_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -548,6 +573,7 @@ def test_completion_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -586,6 +612,7 @@ def test_completion_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -606,6 +633,7 @@ def test_completion_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -644,6 +672,7 @@ def test_completion_service_client_create_channel_credentials_file( 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. @@ -1206,6 +1235,29 @@ def test_completion_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, + ], +) +def test_completion_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -1711,4 +1763,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2beta/test_control_service.py b/tests/unit/gapic/retail_v2beta/test_control_service.py index 8be1a32f..b1aed8ef 100644 --- a/tests/unit/gapic/retail_v2beta/test_control_service.py +++ b/tests/unit/gapic/retail_v2beta/test_control_service.py @@ -228,6 +228,7 @@ def test_control_service_client_client_options( 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 @@ -245,6 +246,7 @@ def test_control_service_client_client_options( 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 @@ -262,6 +264,7 @@ def test_control_service_client_client_options( 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 @@ -291,6 +294,25 @@ def test_control_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -358,6 +380,7 @@ def test_control_service_client_mtls_env_auto( 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 @@ -392,6 +415,7 @@ def test_control_service_client_mtls_env_auto( 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. @@ -414,6 +438,7 @@ def test_control_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -528,6 +553,7 @@ def test_control_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -566,6 +592,7 @@ def test_control_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -586,6 +613,7 @@ def test_control_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -624,6 +652,7 @@ def test_control_service_client_create_channel_credentials_file( 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. @@ -2367,6 +2396,29 @@ def test_control_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + transports.ControlServiceRestTransport, + ], +) +def test_control_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", [ @@ -2864,4 +2916,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2beta/test_prediction_service.py b/tests/unit/gapic/retail_v2beta/test_prediction_service.py index cfb09dd4..b1e0f4c5 100644 --- a/tests/unit/gapic/retail_v2beta/test_prediction_service.py +++ b/tests/unit/gapic/retail_v2beta/test_prediction_service.py @@ -238,6 +238,7 @@ def test_prediction_service_client_client_options( 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 @@ -255,6 +256,7 @@ def test_prediction_service_client_client_options( 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 @@ -272,6 +274,7 @@ def test_prediction_service_client_client_options( 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 @@ -301,6 +304,25 @@ def test_prediction_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -378,6 +400,7 @@ def test_prediction_service_client_mtls_env_auto( 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 @@ -412,6 +435,7 @@ def test_prediction_service_client_mtls_env_auto( 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. @@ -434,6 +458,7 @@ def test_prediction_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -548,6 +573,7 @@ def test_prediction_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -586,6 +612,7 @@ def test_prediction_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -606,6 +633,7 @@ def test_prediction_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -644,6 +672,7 @@ def test_prediction_service_client_create_channel_credentials_file( 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. @@ -1050,6 +1079,29 @@ def test_prediction_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + transports.PredictionServiceRestTransport, + ], +) +def test_prediction_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", [ @@ -1529,4 +1581,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2beta/test_product_service.py b/tests/unit/gapic/retail_v2beta/test_product_service.py index 43efbaa6..ac20808c 100644 --- a/tests/unit/gapic/retail_v2beta/test_product_service.py +++ b/tests/unit/gapic/retail_v2beta/test_product_service.py @@ -241,6 +241,7 @@ def test_product_service_client_client_options( 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 @@ -258,6 +259,7 @@ def test_product_service_client_client_options( 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 @@ -275,6 +277,7 @@ def test_product_service_client_client_options( 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 @@ -304,6 +307,25 @@ def test_product_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -371,6 +393,7 @@ def test_product_service_client_mtls_env_auto( 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 @@ -405,6 +428,7 @@ def test_product_service_client_mtls_env_auto( 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. @@ -427,6 +451,7 @@ def test_product_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -541,6 +566,7 @@ def test_product_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -579,6 +605,7 @@ def test_product_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -599,6 +626,7 @@ def test_product_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -637,6 +665,7 @@ def test_product_service_client_create_channel_credentials_file( 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. @@ -3823,6 +3852,29 @@ def test_product_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + transports.ProductServiceRestTransport, + ], +) +def test_product_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", [ @@ -4362,4 +4414,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2beta/test_search_service.py b/tests/unit/gapic/retail_v2beta/test_search_service.py index d5ba1b31..fbf14b45 100644 --- a/tests/unit/gapic/retail_v2beta/test_search_service.py +++ b/tests/unit/gapic/retail_v2beta/test_search_service.py @@ -223,6 +223,7 @@ def test_search_service_client_client_options( 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 @@ -240,6 +241,7 @@ def test_search_service_client_client_options( 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 @@ -257,6 +259,7 @@ def test_search_service_client_client_options( 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 @@ -286,6 +289,25 @@ def test_search_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -353,6 +375,7 @@ def test_search_service_client_mtls_env_auto( 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 @@ -387,6 +410,7 @@ def test_search_service_client_mtls_env_auto( 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. @@ -409,6 +433,7 @@ def test_search_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -523,6 +548,7 @@ def test_search_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -561,6 +587,7 @@ def test_search_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -581,6 +608,7 @@ def test_search_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -619,6 +647,7 @@ def test_search_service_client_create_channel_credentials_file( 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. @@ -1227,6 +1256,29 @@ def test_search_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + transports.SearchServiceRestTransport, + ], +) +def test_search_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -1730,4 +1782,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2beta/test_serving_config_service.py b/tests/unit/gapic/retail_v2beta/test_serving_config_service.py index 8ff6c4cc..70bfd6ea 100644 --- a/tests/unit/gapic/retail_v2beta/test_serving_config_service.py +++ b/tests/unit/gapic/retail_v2beta/test_serving_config_service.py @@ -236,6 +236,7 @@ def test_serving_config_service_client_client_options( 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 @@ -253,6 +254,7 @@ def test_serving_config_service_client_client_options( 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 @@ -270,6 +272,7 @@ def test_serving_config_service_client_client_options( 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 @@ -299,6 +302,25 @@ def test_serving_config_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -376,6 +398,7 @@ def test_serving_config_service_client_mtls_env_auto( 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 @@ -410,6 +433,7 @@ def test_serving_config_service_client_mtls_env_auto( 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. @@ -432,6 +456,7 @@ def test_serving_config_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -550,6 +575,7 @@ def test_serving_config_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -588,6 +614,7 @@ def test_serving_config_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -608,6 +635,7 @@ def test_serving_config_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -646,6 +674,7 @@ def test_serving_config_service_client_create_channel_credentials_file( 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. @@ -3137,6 +3166,29 @@ def test_serving_config_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + transports.ServingConfigServiceRestTransport, + ], +) +def test_serving_config_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", [ @@ -3641,4 +3693,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/retail_v2beta/test_user_event_service.py b/tests/unit/gapic/retail_v2beta/test_user_event_service.py index 763243bf..49db13cf 100644 --- a/tests/unit/gapic/retail_v2beta/test_user_event_service.py +++ b/tests/unit/gapic/retail_v2beta/test_user_event_service.py @@ -252,6 +252,7 @@ def test_user_event_service_client_client_options( 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 @@ -269,6 +270,7 @@ def test_user_event_service_client_client_options( 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 @@ -286,6 +288,7 @@ def test_user_event_service_client_client_options( 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 @@ -315,6 +318,25 @@ def test_user_event_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -392,6 +414,7 @@ def test_user_event_service_client_mtls_env_auto( 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 @@ -426,6 +449,7 @@ def test_user_event_service_client_mtls_env_auto( 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. @@ -448,6 +472,7 @@ def test_user_event_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -562,6 +587,7 @@ def test_user_event_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -600,6 +626,7 @@ def test_user_event_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -620,6 +647,7 @@ def test_user_event_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -658,6 +686,7 @@ def test_user_event_service_client_create_channel_credentials_file( 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. @@ -1748,6 +1777,29 @@ def test_user_event_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +def test_user_event_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -2284,4 +2336,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) From 4139c81dfc38c19e1b5467ddfd74f66ef77e5aba Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 5 Jul 2022 23:09:32 +0000 Subject: [PATCH 05/11] chore: use gapic-generator-python 1.1.1 PiperOrigin-RevId: 459095142 Source-Link: https://github.com/googleapis/googleapis/commit/4f1be992601ed740a581a32cedc4e7b6c6a27793 Source-Link: https://github.com/googleapis/googleapis-gen/commit/ae686d9cde4fc3e36d0ac02efb8643b15890c1ed Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYWU2ODZkOWNkZTRmYzNlMzZkMGFjMDJlZmI4NjQzYjE1ODkwYzFlZCJ9 --- owl-bot-staging/v2/.coveragerc | 17 + owl-bot-staging/v2/.flake8 | 33 + owl-bot-staging/v2/MANIFEST.in | 2 + owl-bot-staging/v2/README.rst | 49 + owl-bot-staging/v2/docs/conf.py | 376 + owl-bot-staging/v2/docs/index.rst | 7 + .../v2/docs/retail_v2/catalog_service.rst | 10 + .../v2/docs/retail_v2/completion_service.rst | 6 + .../v2/docs/retail_v2/prediction_service.rst | 6 + .../v2/docs/retail_v2/product_service.rst | 10 + .../v2/docs/retail_v2/search_service.rst | 10 + .../v2/docs/retail_v2/services.rst | 11 + owl-bot-staging/v2/docs/retail_v2/types.rst | 7 + .../v2/docs/retail_v2/user_event_service.rst | 6 + .../v2/google/cloud/retail/__init__.py | 193 + .../v2/google/cloud/retail/py.typed | 2 + .../v2/google/cloud/retail_v2/__init__.py | 194 + .../cloud/retail_v2/gapic_metadata.json | 333 + .../v2/google/cloud/retail_v2/py.typed | 2 + .../cloud/retail_v2/services/__init__.py | 15 + .../services/catalog_service/__init__.py | 22 + .../services/catalog_service/async_client.py | 653 ++ .../services/catalog_service/client.py | 862 ++ .../services/catalog_service/pagers.py | 140 + .../catalog_service/transports/__init__.py | 33 + .../catalog_service/transports/base.py | 198 + .../catalog_service/transports/grpc.py | 381 + .../transports/grpc_asyncio.py | 380 + .../services/completion_service/__init__.py | 22 + .../completion_service/async_client.py | 391 + .../services/completion_service/client.py | 593 ++ .../completion_service/transports/__init__.py | 33 + .../completion_service/transports/base.py | 176 + .../completion_service/transports/grpc.py | 325 + .../transports/grpc_asyncio.py | 324 + .../services/prediction_service/__init__.py | 22 + .../prediction_service/async_client.py | 279 + .../services/prediction_service/client.py | 480 ++ .../prediction_service/transports/__init__.py | 33 + .../prediction_service/transports/base.py | 154 + .../prediction_service/transports/grpc.py | 264 + .../transports/grpc_asyncio.py | 263 + .../services/product_service/__init__.py | 22 + .../services/product_service/async_client.py | 1701 ++++ .../services/product_service/client.py | 1904 +++++ .../services/product_service/pagers.py | 140 + .../product_service/transports/__init__.py | 33 + .../product_service/transports/base.py | 312 + .../product_service/transports/grpc.py | 680 ++ .../transports/grpc_asyncio.py | 679 ++ .../services/search_service/__init__.py | 22 + .../services/search_service/async_client.py | 303 + .../services/search_service/client.py | 513 ++ .../services/search_service/pagers.py | 139 + .../search_service/transports/__init__.py | 33 + .../search_service/transports/base.py | 154 + .../search_service/transports/grpc.py | 270 + .../search_service/transports/grpc_asyncio.py | 269 + .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 730 ++ .../services/user_event_service/client.py | 930 +++ .../user_event_service/transports/__init__.py | 33 + .../user_event_service/transports/base.py | 235 + .../user_event_service/transports/grpc.py | 417 + .../transports/grpc_asyncio.py | 416 + .../google/cloud/retail_v2/types/__init__.py | 194 + .../google/cloud/retail_v2/types/catalog.py | 131 + .../cloud/retail_v2/types/catalog_service.py | 248 + .../v2/google/cloud/retail_v2/types/common.py | 736 ++ .../retail_v2/types/completion_service.py | 229 + .../cloud/retail_v2/types/import_config.py | 697 ++ .../retail_v2/types/prediction_service.py | 275 + .../google/cloud/retail_v2/types/product.py | 701 ++ .../cloud/retail_v2/types/product_service.py | 858 ++ .../google/cloud/retail_v2/types/promotion.py | 50 + .../cloud/retail_v2/types/purge_config.py | 107 + .../cloud/retail_v2/types/search_service.py | 1150 +++ .../cloud/retail_v2/types/user_event.py | 508 ++ .../retail_v2/types/user_event_service.py | 154 + owl-bot-staging/v2/mypy.ini | 3 + owl-bot-staging/v2/noxfile.py | 180 + ...atalog_service_get_default_branch_async.py | 44 + ...catalog_service_get_default_branch_sync.py | 44 + ...ted_catalog_service_list_catalogs_async.py | 46 + ...ated_catalog_service_list_catalogs_sync.py | 46 + ...atalog_service_set_default_branch_async.py | 42 + ...catalog_service_set_default_branch_sync.py | 42 + ...ed_catalog_service_update_catalog_async.py | 49 + ...ted_catalog_service_update_catalog_sync.py | 49 + ...completion_service_complete_query_async.py | 46 + ..._completion_service_complete_query_sync.py | 46 + ...on_service_import_completion_data_async.py | 54 + ...ion_service_import_completion_data_sync.py | 54 + ...erated_prediction_service_predict_async.py | 50 + ...nerated_prediction_service_predict_sync.py | 50 + ...ct_service_add_fulfillment_places_async.py | 51 + ...uct_service_add_fulfillment_places_sync.py | 51 + ...uct_service_add_local_inventories_async.py | 49 + ...duct_service_add_local_inventories_sync.py | 49 + ...ed_product_service_create_product_async.py | 50 + ...ted_product_service_create_product_sync.py | 50 + ...ed_product_service_delete_product_async.py | 43 + ...ted_product_service_delete_product_sync.py | 43 + ...rated_product_service_get_product_async.py | 45 + ...erated_product_service_get_product_sync.py | 45 + ...d_product_service_import_products_async.py | 53 + ...ed_product_service_import_products_sync.py | 53 + ...ted_product_service_list_products_async.py | 46 + ...ated_product_service_list_products_sync.py | 46 + ...service_remove_fulfillment_places_async.py | 51 + ..._service_remove_fulfillment_places_sync.py | 51 + ..._service_remove_local_inventories_async.py | 50 + ...t_service_remove_local_inventories_sync.py | 50 + ...ted_product_service_set_inventory_async.py | 52 + ...ated_product_service_set_inventory_sync.py | 52 + ...ed_product_service_update_product_async.py | 48 + ...ted_product_service_update_product_sync.py | 48 + ...2_generated_search_service_search_async.py | 47 + ...v2_generated_search_service_search_sync.py | 47 + ..._event_service_collect_user_event_async.py | 46 + ...r_event_service_collect_user_event_sync.py | 46 + ..._event_service_import_user_events_async.py | 54 + ...r_event_service_import_user_events_sync.py | 54 + ...r_event_service_purge_user_events_async.py | 50 + ...er_event_service_purge_user_events_sync.py | 50 + ..._event_service_rejoin_user_events_async.py | 49 + ...r_event_service_rejoin_user_events_sync.py | 49 + ...er_event_service_write_user_event_async.py | 50 + ...ser_event_service_write_user_event_sync.py | 50 + .../snippet_metadata_retail_v2.json | 3826 +++++++++ .../v2/scripts/fixup_retail_v2_keywords.py | 199 + owl-bot-staging/v2/setup.py | 59 + owl-bot-staging/v2/tests/__init__.py | 16 + owl-bot-staging/v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../v2/tests/unit/gapic/retail_v2/__init__.py | 16 + .../gapic/retail_v2/test_catalog_service.py | 2317 ++++++ .../retail_v2/test_completion_service.py | 1501 ++++ .../retail_v2/test_prediction_service.py | 1329 ++++ .../gapic/retail_v2/test_product_service.py | 4135 ++++++++++ .../gapic/retail_v2/test_search_service.py | 1546 ++++ .../retail_v2/test_user_event_service.py | 2038 +++++ owl-bot-staging/v2alpha/.coveragerc | 17 + owl-bot-staging/v2alpha/.flake8 | 33 + owl-bot-staging/v2alpha/MANIFEST.in | 2 + owl-bot-staging/v2alpha/README.rst | 49 + owl-bot-staging/v2alpha/docs/conf.py | 376 + owl-bot-staging/v2alpha/docs/index.rst | 7 + .../docs/retail_v2alpha/catalog_service.rst | 10 + .../retail_v2alpha/completion_service.rst | 6 + .../docs/retail_v2alpha/control_service.rst | 10 + .../retail_v2alpha/prediction_service.rst | 6 + .../docs/retail_v2alpha/product_service.rst | 10 + .../docs/retail_v2alpha/search_service.rst | 10 + .../v2alpha/docs/retail_v2alpha/services.rst | 13 + .../retail_v2alpha/serving_config_service.rst | 10 + .../v2alpha/docs/retail_v2alpha/types.rst | 7 + .../retail_v2alpha/user_event_service.rst | 6 + .../v2alpha/google/cloud/retail/__init__.py | 281 + .../v2alpha/google/cloud/retail/py.typed | 2 + .../google/cloud/retail_v2alpha/__init__.py | 282 + .../cloud/retail_v2alpha/gapic_metadata.json | 561 ++ .../google/cloud/retail_v2alpha/py.typed | 2 + .../cloud/retail_v2alpha/services/__init__.py | 15 + .../services/catalog_service/__init__.py | 22 + .../services/catalog_service/async_client.py | 1352 ++++ .../services/catalog_service/client.py | 1582 ++++ .../services/catalog_service/pagers.py | 140 + .../catalog_service/transports/__init__.py | 33 + .../catalog_service/transports/base.py | 297 + .../catalog_service/transports/grpc.py | 600 ++ .../transports/grpc_asyncio.py | 599 ++ .../services/completion_service/__init__.py | 22 + .../completion_service/async_client.py | 391 + .../services/completion_service/client.py | 593 ++ .../completion_service/transports/__init__.py | 33 + .../completion_service/transports/base.py | 176 + .../completion_service/transports/grpc.py | 325 + .../transports/grpc_asyncio.py | 324 + .../services/control_service/__init__.py | 22 + .../services/control_service/async_client.py | 744 ++ .../services/control_service/client.py | 953 +++ .../services/control_service/pagers.py | 140 + .../control_service/transports/__init__.py | 33 + .../control_service/transports/base.py | 213 + .../control_service/transports/grpc.py | 382 + .../transports/grpc_asyncio.py | 381 + .../services/prediction_service/__init__.py | 22 + .../prediction_service/async_client.py | 279 + .../services/prediction_service/client.py | 480 ++ .../prediction_service/transports/__init__.py | 33 + .../prediction_service/transports/base.py | 154 + .../prediction_service/transports/grpc.py | 264 + .../transports/grpc_asyncio.py | 263 + .../services/product_service/__init__.py | 22 + .../services/product_service/async_client.py | 1804 +++++ .../services/product_service/client.py | 2008 +++++ .../services/product_service/pagers.py | 140 + .../product_service/transports/__init__.py | 33 + .../product_service/transports/base.py | 327 + .../product_service/transports/grpc.py | 726 ++ .../transports/grpc_asyncio.py | 725 ++ .../services/search_service/__init__.py | 22 + .../services/search_service/async_client.py | 303 + .../services/search_service/client.py | 513 ++ .../services/search_service/pagers.py | 139 + .../search_service/transports/__init__.py | 33 + .../search_service/transports/base.py | 154 + .../search_service/transports/grpc.py | 270 + .../search_service/transports/grpc_asyncio.py | 269 + .../serving_config_service/__init__.py | 22 + .../serving_config_service/async_client.py | 954 +++ .../services/serving_config_service/client.py | 1163 +++ .../services/serving_config_service/pagers.py | 140 + .../transports/__init__.py | 33 + .../serving_config_service/transports/base.py | 241 + .../serving_config_service/transports/grpc.py | 440 + .../transports/grpc_asyncio.py | 439 + .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 730 ++ .../services/user_event_service/client.py | 930 +++ .../user_event_service/transports/__init__.py | 33 + .../user_event_service/transports/base.py | 235 + .../user_event_service/transports/grpc.py | 417 + .../transports/grpc_asyncio.py | 416 + .../cloud/retail_v2alpha/types/__init__.py | 284 + .../cloud/retail_v2alpha/types/catalog.py | 528 ++ .../retail_v2alpha/types/catalog_service.py | 453 ++ .../cloud/retail_v2alpha/types/common.py | 1179 +++ .../types/completion_service.py | 223 + .../cloud/retail_v2alpha/types/control.py | 123 + .../retail_v2alpha/types/control_service.py | 197 + .../retail_v2alpha/types/export_config.py | 134 + .../retail_v2alpha/types/import_config.py | 691 ++ .../types/prediction_service.py | 263 + .../cloud/retail_v2alpha/types/product.py | 705 ++ .../retail_v2alpha/types/product_service.py | 877 ++ .../cloud/retail_v2alpha/types/promotion.py | 50 + .../retail_v2alpha/types/purge_config.py | 251 + .../retail_v2alpha/types/search_service.py | 1099 +++ .../retail_v2alpha/types/serving_config.py | 309 + .../types/serving_config_service.py | 234 + .../cloud/retail_v2alpha/types/user_event.py | 507 ++ .../types/user_event_service.py | 154 + owl-bot-staging/v2alpha/mypy.ini | 3 + owl-bot-staging/v2alpha/noxfile.py | 180 + ...log_service_add_catalog_attribute_async.py | 49 + ...alog_service_add_catalog_attribute_sync.py | 49 + ...log_service_get_attributes_config_async.py | 45 + ...alog_service_get_attributes_config_sync.py | 45 + ...log_service_get_completion_config_async.py | 45 + ...alog_service_get_completion_config_sync.py | 45 + ...atalog_service_get_default_branch_async.py | 44 + ...catalog_service_get_default_branch_sync.py | 44 + ...ted_catalog_service_list_catalogs_async.py | 46 + ...ated_catalog_service_list_catalogs_sync.py | 46 + ..._service_remove_catalog_attribute_async.py | 46 + ...g_service_remove_catalog_attribute_sync.py | 46 + ...service_replace_catalog_attribute_async.py | 49 + ..._service_replace_catalog_attribute_sync.py | 49 + ...atalog_service_set_default_branch_async.py | 42 + ...catalog_service_set_default_branch_sync.py | 42 + ..._service_update_attributes_config_async.py | 48 + ...g_service_update_attributes_config_sync.py | 48 + ...ed_catalog_service_update_catalog_async.py | 49 + ...ted_catalog_service_update_catalog_sync.py | 49 + ..._service_update_completion_config_async.py | 48 + ...g_service_update_completion_config_sync.py | 48 + ...completion_service_complete_query_async.py | 46 + ..._completion_service_complete_query_sync.py | 46 + ...on_service_import_completion_data_async.py | 54 + ...ion_service_import_completion_data_sync.py | 54 + ...ed_control_service_create_control_async.py | 53 + ...ted_control_service_create_control_sync.py | 53 + ...ed_control_service_delete_control_async.py | 43 + ...ted_control_service_delete_control_sync.py | 43 + ...rated_control_service_get_control_async.py | 45 + ...erated_control_service_get_control_sync.py | 45 + ...ted_control_service_list_controls_async.py | 46 + ...ated_control_service_list_controls_sync.py | 46 + ...ed_control_service_update_control_async.py | 51 + ...ted_control_service_update_control_sync.py | 51 + ...erated_prediction_service_predict_async.py | 50 + ...nerated_prediction_service_predict_sync.py | 50 + ...ct_service_add_fulfillment_places_async.py | 51 + ...uct_service_add_fulfillment_places_sync.py | 51 + ...uct_service_add_local_inventories_async.py | 49 + ...duct_service_add_local_inventories_sync.py | 49 + ...ed_product_service_create_product_async.py | 50 + ...ted_product_service_create_product_sync.py | 50 + ...ed_product_service_delete_product_async.py | 43 + ...ted_product_service_delete_product_sync.py | 43 + ...rated_product_service_get_product_async.py | 45 + ...erated_product_service_get_product_sync.py | 45 + ...d_product_service_import_products_async.py | 53 + ...ed_product_service_import_products_sync.py | 53 + ...ted_product_service_list_products_async.py | 46 + ...ated_product_service_list_products_sync.py | 46 + ...ed_product_service_purge_products_async.py | 50 + ...ted_product_service_purge_products_sync.py | 50 + ...service_remove_fulfillment_places_async.py | 51 + ..._service_remove_fulfillment_places_sync.py | 51 + ..._service_remove_local_inventories_async.py | 50 + ...t_service_remove_local_inventories_sync.py | 50 + ...ted_product_service_set_inventory_async.py | 52 + ...ated_product_service_set_inventory_sync.py | 52 + ...ed_product_service_update_product_async.py | 48 + ...ted_product_service_update_product_sync.py | 48 + ...a_generated_search_service_search_async.py | 47 + ...ha_generated_search_service_search_sync.py | 47 + ...erving_config_service_add_control_async.py | 46 + ...serving_config_service_add_control_sync.py | 46 + ...fig_service_create_serving_config_async.py | 51 + ...nfig_service_create_serving_config_sync.py | 51 + ...fig_service_delete_serving_config_async.py | 43 + ...nfig_service_delete_serving_config_sync.py | 43 + ...config_service_get_serving_config_async.py | 45 + ..._config_service_get_serving_config_sync.py | 45 + ...nfig_service_list_serving_configs_async.py | 46 + ...onfig_service_list_serving_configs_sync.py | 46 + ...ing_config_service_remove_control_async.py | 46 + ...ving_config_service_remove_control_sync.py | 46 + ...fig_service_update_serving_config_async.py | 49 + ...nfig_service_update_serving_config_sync.py | 49 + ..._event_service_collect_user_event_async.py | 46 + ...r_event_service_collect_user_event_sync.py | 46 + ..._event_service_import_user_events_async.py | 54 + ...r_event_service_import_user_events_sync.py | 54 + ...r_event_service_purge_user_events_async.py | 50 + ...er_event_service_purge_user_events_sync.py | 50 + ..._event_service_rejoin_user_events_async.py | 49 + ...r_event_service_rejoin_user_events_sync.py | 49 + ...er_event_service_write_user_event_async.py | 50 + ...ser_event_service_write_user_event_sync.py | 50 + .../snippet_metadata_retail_v2alpha.json | 7066 +++++++++++++++++ .../scripts/fixup_retail_v2alpha_keywords.py | 219 + owl-bot-staging/v2alpha/setup.py | 59 + owl-bot-staging/v2alpha/tests/__init__.py | 16 + .../v2alpha/tests/unit/__init__.py | 16 + .../v2alpha/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/retail_v2alpha/__init__.py | 16 + .../retail_v2alpha/test_catalog_service.py | 3843 +++++++++ .../retail_v2alpha/test_completion_service.py | 1501 ++++ .../retail_v2alpha/test_control_service.py | 2616 ++++++ .../retail_v2alpha/test_prediction_service.py | 1329 ++++ .../retail_v2alpha/test_product_service.py | 4287 ++++++++++ .../retail_v2alpha/test_search_service.py | 1546 ++++ .../test_serving_config_service.py | 3329 ++++++++ .../retail_v2alpha/test_user_event_service.py | 2038 +++++ owl-bot-staging/v2beta/.coveragerc | 17 + owl-bot-staging/v2beta/.flake8 | 33 + owl-bot-staging/v2beta/MANIFEST.in | 2 + owl-bot-staging/v2beta/README.rst | 49 + owl-bot-staging/v2beta/docs/conf.py | 376 + owl-bot-staging/v2beta/docs/index.rst | 7 + .../docs/retail_v2beta/catalog_service.rst | 10 + .../docs/retail_v2beta/completion_service.rst | 6 + .../docs/retail_v2beta/control_service.rst | 10 + .../docs/retail_v2beta/prediction_service.rst | 6 + .../docs/retail_v2beta/product_service.rst | 10 + .../docs/retail_v2beta/search_service.rst | 10 + .../v2beta/docs/retail_v2beta/services.rst | 13 + .../retail_v2beta/serving_config_service.rst | 10 + .../v2beta/docs/retail_v2beta/types.rst | 7 + .../docs/retail_v2beta/user_event_service.rst | 6 + .../v2beta/google/cloud/retail/__init__.py | 275 + .../v2beta/google/cloud/retail/py.typed | 2 + .../google/cloud/retail_v2beta/__init__.py | 276 + .../cloud/retail_v2beta/gapic_metadata.json | 551 ++ .../google/cloud/retail_v2beta/py.typed | 2 + .../cloud/retail_v2beta/services/__init__.py | 15 + .../services/catalog_service/__init__.py | 22 + .../services/catalog_service/async_client.py | 1350 ++++ .../services/catalog_service/client.py | 1580 ++++ .../services/catalog_service/pagers.py | 140 + .../catalog_service/transports/__init__.py | 33 + .../catalog_service/transports/base.py | 297 + .../catalog_service/transports/grpc.py | 600 ++ .../transports/grpc_asyncio.py | 599 ++ .../services/completion_service/__init__.py | 22 + .../completion_service/async_client.py | 391 + .../services/completion_service/client.py | 593 ++ .../completion_service/transports/__init__.py | 33 + .../completion_service/transports/base.py | 176 + .../completion_service/transports/grpc.py | 325 + .../transports/grpc_asyncio.py | 324 + .../services/control_service/__init__.py | 22 + .../services/control_service/async_client.py | 742 ++ .../services/control_service/client.py | 951 +++ .../services/control_service/pagers.py | 140 + .../control_service/transports/__init__.py | 33 + .../control_service/transports/base.py | 213 + .../control_service/transports/grpc.py | 382 + .../transports/grpc_asyncio.py | 381 + .../services/prediction_service/__init__.py | 22 + .../prediction_service/async_client.py | 279 + .../services/prediction_service/client.py | 480 ++ .../prediction_service/transports/__init__.py | 33 + .../prediction_service/transports/base.py | 154 + .../prediction_service/transports/grpc.py | 264 + .../transports/grpc_asyncio.py | 263 + .../services/product_service/__init__.py | 22 + .../services/product_service/async_client.py | 1692 ++++ .../services/product_service/client.py | 1895 +++++ .../services/product_service/pagers.py | 140 + .../product_service/transports/__init__.py | 33 + .../product_service/transports/base.py | 312 + .../product_service/transports/grpc.py | 680 ++ .../transports/grpc_asyncio.py | 679 ++ .../services/search_service/__init__.py | 22 + .../services/search_service/async_client.py | 303 + .../services/search_service/client.py | 513 ++ .../services/search_service/pagers.py | 139 + .../search_service/transports/__init__.py | 33 + .../search_service/transports/base.py | 154 + .../search_service/transports/grpc.py | 270 + .../search_service/transports/grpc_asyncio.py | 269 + .../serving_config_service/__init__.py | 22 + .../serving_config_service/async_client.py | 954 +++ .../services/serving_config_service/client.py | 1163 +++ .../services/serving_config_service/pagers.py | 140 + .../transports/__init__.py | 33 + .../serving_config_service/transports/base.py | 241 + .../serving_config_service/transports/grpc.py | 440 + .../transports/grpc_asyncio.py | 439 + .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 730 ++ .../services/user_event_service/client.py | 930 +++ .../user_event_service/transports/__init__.py | 33 + .../user_event_service/transports/base.py | 235 + .../user_event_service/transports/grpc.py | 417 + .../transports/grpc_asyncio.py | 416 + .../cloud/retail_v2beta/types/__init__.py | 278 + .../cloud/retail_v2beta/types/catalog.py | 528 ++ .../retail_v2beta/types/catalog_service.py | 453 ++ .../cloud/retail_v2beta/types/common.py | 1178 +++ .../retail_v2beta/types/completion_service.py | 223 + .../cloud/retail_v2beta/types/control.py | 112 + .../retail_v2beta/types/control_service.py | 197 + .../retail_v2beta/types/export_config.py | 134 + .../retail_v2beta/types/import_config.py | 691 ++ .../retail_v2beta/types/prediction_service.py | 263 + .../cloud/retail_v2beta/types/product.py | 705 ++ .../retail_v2beta/types/product_service.py | 844 ++ .../cloud/retail_v2beta/types/promotion.py | 50 + .../cloud/retail_v2beta/types/purge_config.py | 107 + .../retail_v2beta/types/search_service.py | 1074 +++ .../retail_v2beta/types/serving_config.py | 309 + .../types/serving_config_service.py | 234 + .../cloud/retail_v2beta/types/user_event.py | 507 ++ .../retail_v2beta/types/user_event_service.py | 154 + owl-bot-staging/v2beta/mypy.ini | 3 + owl-bot-staging/v2beta/noxfile.py | 180 + ...log_service_add_catalog_attribute_async.py | 49 + ...alog_service_add_catalog_attribute_sync.py | 49 + ...log_service_get_attributes_config_async.py | 45 + ...alog_service_get_attributes_config_sync.py | 45 + ...log_service_get_completion_config_async.py | 45 + ...alog_service_get_completion_config_sync.py | 45 + ...atalog_service_get_default_branch_async.py | 44 + ...catalog_service_get_default_branch_sync.py | 44 + ...ted_catalog_service_list_catalogs_async.py | 46 + ...ated_catalog_service_list_catalogs_sync.py | 46 + ..._service_remove_catalog_attribute_async.py | 46 + ...g_service_remove_catalog_attribute_sync.py | 46 + ...service_replace_catalog_attribute_async.py | 49 + ..._service_replace_catalog_attribute_sync.py | 49 + ...atalog_service_set_default_branch_async.py | 42 + ...catalog_service_set_default_branch_sync.py | 42 + ..._service_update_attributes_config_async.py | 48 + ...g_service_update_attributes_config_sync.py | 48 + ...ed_catalog_service_update_catalog_async.py | 49 + ...ted_catalog_service_update_catalog_sync.py | 49 + ..._service_update_completion_config_async.py | 48 + ...g_service_update_completion_config_sync.py | 48 + ...completion_service_complete_query_async.py | 46 + ..._completion_service_complete_query_sync.py | 46 + ...on_service_import_completion_data_async.py | 54 + ...ion_service_import_completion_data_sync.py | 54 + ...ed_control_service_create_control_async.py | 52 + ...ted_control_service_create_control_sync.py | 52 + ...ed_control_service_delete_control_async.py | 43 + ...ted_control_service_delete_control_sync.py | 43 + ...rated_control_service_get_control_async.py | 45 + ...erated_control_service_get_control_sync.py | 45 + ...ted_control_service_list_controls_async.py | 46 + ...ated_control_service_list_controls_sync.py | 46 + ...ed_control_service_update_control_async.py | 50 + ...ted_control_service_update_control_sync.py | 50 + ...erated_prediction_service_predict_async.py | 50 + ...nerated_prediction_service_predict_sync.py | 50 + ...ct_service_add_fulfillment_places_async.py | 51 + ...uct_service_add_fulfillment_places_sync.py | 51 + ...uct_service_add_local_inventories_async.py | 49 + ...duct_service_add_local_inventories_sync.py | 49 + ...ed_product_service_create_product_async.py | 50 + ...ted_product_service_create_product_sync.py | 50 + ...ed_product_service_delete_product_async.py | 43 + ...ted_product_service_delete_product_sync.py | 43 + ...rated_product_service_get_product_async.py | 45 + ...erated_product_service_get_product_sync.py | 45 + ...d_product_service_import_products_async.py | 53 + ...ed_product_service_import_products_sync.py | 53 + ...ted_product_service_list_products_async.py | 46 + ...ated_product_service_list_products_sync.py | 46 + ...service_remove_fulfillment_places_async.py | 51 + ..._service_remove_fulfillment_places_sync.py | 51 + ..._service_remove_local_inventories_async.py | 50 + ...t_service_remove_local_inventories_sync.py | 50 + ...ted_product_service_set_inventory_async.py | 52 + ...ated_product_service_set_inventory_sync.py | 52 + ...ed_product_service_update_product_async.py | 48 + ...ted_product_service_update_product_sync.py | 48 + ...a_generated_search_service_search_async.py | 47 + ...ta_generated_search_service_search_sync.py | 47 + ...erving_config_service_add_control_async.py | 46 + ...serving_config_service_add_control_sync.py | 46 + ...fig_service_create_serving_config_async.py | 51 + ...nfig_service_create_serving_config_sync.py | 51 + ...fig_service_delete_serving_config_async.py | 43 + ...nfig_service_delete_serving_config_sync.py | 43 + ...config_service_get_serving_config_async.py | 45 + ..._config_service_get_serving_config_sync.py | 45 + ...nfig_service_list_serving_configs_async.py | 46 + ...onfig_service_list_serving_configs_sync.py | 46 + ...ing_config_service_remove_control_async.py | 46 + ...ving_config_service_remove_control_sync.py | 46 + ...fig_service_update_serving_config_async.py | 49 + ...nfig_service_update_serving_config_sync.py | 49 + ..._event_service_collect_user_event_async.py | 46 + ...r_event_service_collect_user_event_sync.py | 46 + ..._event_service_import_user_events_async.py | 54 + ...r_event_service_import_user_events_sync.py | 54 + ...r_event_service_purge_user_events_async.py | 50 + ...er_event_service_purge_user_events_sync.py | 50 + ..._event_service_rejoin_user_events_async.py | 49 + ...r_event_service_rejoin_user_events_sync.py | 49 + ...er_event_service_write_user_event_async.py | 50 + ...ser_event_service_write_user_event_sync.py | 50 + .../snippet_metadata_retail_v2beta.json | 6913 ++++++++++++++++ .../scripts/fixup_retail_v2beta_keywords.py | 218 + owl-bot-staging/v2beta/setup.py | 59 + owl-bot-staging/v2beta/tests/__init__.py | 16 + owl-bot-staging/v2beta/tests/unit/__init__.py | 16 + .../v2beta/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/retail_v2beta/__init__.py | 16 + .../retail_v2beta/test_catalog_service.py | 3843 +++++++++ .../retail_v2beta/test_completion_service.py | 1501 ++++ .../retail_v2beta/test_control_service.py | 2604 ++++++ .../retail_v2beta/test_prediction_service.py | 1329 ++++ .../retail_v2beta/test_product_service.py | 4135 ++++++++++ .../retail_v2beta/test_search_service.py | 1546 ++++ .../test_serving_config_service.py | 3329 ++++++++ .../retail_v2beta/test_user_event_service.py | 2038 +++++ 554 files changed, 175493 insertions(+) create mode 100644 owl-bot-staging/v2/.coveragerc create mode 100644 owl-bot-staging/v2/.flake8 create mode 100644 owl-bot-staging/v2/MANIFEST.in create mode 100644 owl-bot-staging/v2/README.rst create mode 100644 owl-bot-staging/v2/docs/conf.py create mode 100644 owl-bot-staging/v2/docs/index.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/catalog_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/completion_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/prediction_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/product_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/search_service.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/services.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/types.rst create mode 100644 owl-bot-staging/v2/docs/retail_v2/user_event_service.rst create mode 100644 owl-bot-staging/v2/google/cloud/retail/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/common.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/product.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py create mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py create mode 100644 owl-bot-staging/v2/mypy.ini create mode 100644 owl-bot-staging/v2/noxfile.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json create mode 100644 owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py create mode 100644 owl-bot-staging/v2/setup.py create mode 100644 owl-bot-staging/v2/tests/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py create mode 100644 owl-bot-staging/v2alpha/.coveragerc create mode 100644 owl-bot-staging/v2alpha/.flake8 create mode 100644 owl-bot-staging/v2alpha/MANIFEST.in create mode 100644 owl-bot-staging/v2alpha/README.rst create mode 100644 owl-bot-staging/v2alpha/docs/conf.py create mode 100644 owl-bot-staging/v2alpha/docs/index.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst create mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail/py.typed create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py create mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py create mode 100644 owl-bot-staging/v2alpha/mypy.ini create mode 100644 owl-bot-staging/v2alpha/noxfile.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json create mode 100644 owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py create mode 100644 owl-bot-staging/v2alpha/setup.py create mode 100644 owl-bot-staging/v2alpha/tests/__init__.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py create mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py create mode 100644 owl-bot-staging/v2beta/.coveragerc create mode 100644 owl-bot-staging/v2beta/.flake8 create mode 100644 owl-bot-staging/v2beta/MANIFEST.in create mode 100644 owl-bot-staging/v2beta/README.rst create mode 100644 owl-bot-staging/v2beta/docs/conf.py create mode 100644 owl-bot-staging/v2beta/docs/index.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/services.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/types.rst create mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst create mode 100644 owl-bot-staging/v2beta/google/cloud/retail/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail/py.typed create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py create mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py create mode 100644 owl-bot-staging/v2beta/mypy.ini create mode 100644 owl-bot-staging/v2beta/noxfile.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json create mode 100644 owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py create mode 100644 owl-bot-staging/v2beta/setup.py create mode 100644 owl-bot-staging/v2beta/tests/__init__.py create mode 100644 owl-bot-staging/v2beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py create mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc new file mode 100644 index 00000000..a8b114f0 --- /dev/null +++ b/owl-bot-staging/v2/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/retail/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2/.flake8 b/owl-bot-staging/v2/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v2/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in new file mode 100644 index 00000000..985b915c --- /dev/null +++ b/owl-bot-staging/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/retail *.py +recursive-include google/cloud/retail_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst new file mode 100644 index 00000000..cb039760 --- /dev/null +++ b/owl-bot-staging/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Retail API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Retail API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py new file mode 100644 index 00000000..5be9eb4b --- /dev/null +++ b/owl-bot-staging/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-retail documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-retail" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-retail-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-retail.tex", + u"google-cloud-retail Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-retail", + u"Google Cloud Retail Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-retail", + u"google-cloud-retail Documentation", + author, + "google-cloud-retail", + "GAPIC library for Google Cloud Retail API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst new file mode 100644 index 00000000..c70f61bc --- /dev/null +++ b/owl-bot-staging/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + retail_v2/services + retail_v2/types diff --git a/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst b/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst new file mode 100644 index 00000000..5b7227d9 --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst @@ -0,0 +1,10 @@ +CatalogService +-------------------------------- + +.. automodule:: google.cloud.retail_v2.services.catalog_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2.services.catalog_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/completion_service.rst b/owl-bot-staging/v2/docs/retail_v2/completion_service.rst new file mode 100644 index 00000000..551f89ed --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/completion_service.rst @@ -0,0 +1,6 @@ +CompletionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2.services.completion_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst b/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst new file mode 100644 index 00000000..12ffb6ee --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst @@ -0,0 +1,6 @@ +PredictionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2.services.prediction_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/product_service.rst b/owl-bot-staging/v2/docs/retail_v2/product_service.rst new file mode 100644 index 00000000..0b8fa911 --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/product_service.rst @@ -0,0 +1,10 @@ +ProductService +-------------------------------- + +.. automodule:: google.cloud.retail_v2.services.product_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2.services.product_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/search_service.rst b/owl-bot-staging/v2/docs/retail_v2/search_service.rst new file mode 100644 index 00000000..af72819d --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/search_service.rst @@ -0,0 +1,10 @@ +SearchService +------------------------------- + +.. automodule:: google.cloud.retail_v2.services.search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2.services.search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/services.rst b/owl-bot-staging/v2/docs/retail_v2/services.rst new file mode 100644 index 00000000..f86138d7 --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/services.rst @@ -0,0 +1,11 @@ +Services for Google Cloud Retail v2 API +======================================= +.. toctree:: + :maxdepth: 2 + + catalog_service + completion_service + prediction_service + product_service + search_service + user_event_service diff --git a/owl-bot-staging/v2/docs/retail_v2/types.rst b/owl-bot-staging/v2/docs/retail_v2/types.rst new file mode 100644 index 00000000..54951beb --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Retail v2 API +==================================== + +.. automodule:: google.cloud.retail_v2.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst b/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst new file mode 100644 index 00000000..00e214a9 --- /dev/null +++ b/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst @@ -0,0 +1,6 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.retail_v2.services.user_event_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/google/cloud/retail/__init__.py b/owl-bot-staging/v2/google/cloud/retail/__init__.py new file mode 100644 index 00000000..0d70ed64 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail/__init__.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.retail_v2.services.catalog_service.client import CatalogServiceClient +from google.cloud.retail_v2.services.catalog_service.async_client import CatalogServiceAsyncClient +from google.cloud.retail_v2.services.completion_service.client import CompletionServiceClient +from google.cloud.retail_v2.services.completion_service.async_client import CompletionServiceAsyncClient +from google.cloud.retail_v2.services.prediction_service.client import PredictionServiceClient +from google.cloud.retail_v2.services.prediction_service.async_client import PredictionServiceAsyncClient +from google.cloud.retail_v2.services.product_service.client import ProductServiceClient +from google.cloud.retail_v2.services.product_service.async_client import ProductServiceAsyncClient +from google.cloud.retail_v2.services.search_service.client import SearchServiceClient +from google.cloud.retail_v2.services.search_service.async_client import SearchServiceAsyncClient +from google.cloud.retail_v2.services.user_event_service.client import UserEventServiceClient +from google.cloud.retail_v2.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.retail_v2.types.catalog import Catalog +from google.cloud.retail_v2.types.catalog import ProductLevelConfig +from google.cloud.retail_v2.types.catalog_service import GetDefaultBranchRequest +from google.cloud.retail_v2.types.catalog_service import GetDefaultBranchResponse +from google.cloud.retail_v2.types.catalog_service import ListCatalogsRequest +from google.cloud.retail_v2.types.catalog_service import ListCatalogsResponse +from google.cloud.retail_v2.types.catalog_service import SetDefaultBranchRequest +from google.cloud.retail_v2.types.catalog_service import UpdateCatalogRequest +from google.cloud.retail_v2.types.common import Audience +from google.cloud.retail_v2.types.common import ColorInfo +from google.cloud.retail_v2.types.common import CustomAttribute +from google.cloud.retail_v2.types.common import FulfillmentInfo +from google.cloud.retail_v2.types.common import Image +from google.cloud.retail_v2.types.common import Interval +from google.cloud.retail_v2.types.common import LocalInventory +from google.cloud.retail_v2.types.common import PriceInfo +from google.cloud.retail_v2.types.common import Rating +from google.cloud.retail_v2.types.common import UserInfo +from google.cloud.retail_v2.types.completion_service import CompleteQueryRequest +from google.cloud.retail_v2.types.completion_service import CompleteQueryResponse +from google.cloud.retail_v2.types.import_config import BigQuerySource +from google.cloud.retail_v2.types.import_config import CompletionDataInputConfig +from google.cloud.retail_v2.types.import_config import GcsSource +from google.cloud.retail_v2.types.import_config import ImportCompletionDataRequest +from google.cloud.retail_v2.types.import_config import ImportCompletionDataResponse +from google.cloud.retail_v2.types.import_config import ImportErrorsConfig +from google.cloud.retail_v2.types.import_config import ImportMetadata +from google.cloud.retail_v2.types.import_config import ImportProductsRequest +from google.cloud.retail_v2.types.import_config import ImportProductsResponse +from google.cloud.retail_v2.types.import_config import ImportUserEventsRequest +from google.cloud.retail_v2.types.import_config import ImportUserEventsResponse +from google.cloud.retail_v2.types.import_config import ProductInlineSource +from google.cloud.retail_v2.types.import_config import ProductInputConfig +from google.cloud.retail_v2.types.import_config import UserEventImportSummary +from google.cloud.retail_v2.types.import_config import UserEventInlineSource +from google.cloud.retail_v2.types.import_config import UserEventInputConfig +from google.cloud.retail_v2.types.prediction_service import PredictRequest +from google.cloud.retail_v2.types.prediction_service import PredictResponse +from google.cloud.retail_v2.types.product import Product +from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesMetadata +from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesRequest +from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesResponse +from google.cloud.retail_v2.types.product_service import AddLocalInventoriesMetadata +from google.cloud.retail_v2.types.product_service import AddLocalInventoriesRequest +from google.cloud.retail_v2.types.product_service import AddLocalInventoriesResponse +from google.cloud.retail_v2.types.product_service import CreateProductRequest +from google.cloud.retail_v2.types.product_service import DeleteProductRequest +from google.cloud.retail_v2.types.product_service import GetProductRequest +from google.cloud.retail_v2.types.product_service import ListProductsRequest +from google.cloud.retail_v2.types.product_service import ListProductsResponse +from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesMetadata +from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesRequest +from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesResponse +from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesMetadata +from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesRequest +from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesResponse +from google.cloud.retail_v2.types.product_service import SetInventoryMetadata +from google.cloud.retail_v2.types.product_service import SetInventoryRequest +from google.cloud.retail_v2.types.product_service import SetInventoryResponse +from google.cloud.retail_v2.types.product_service import UpdateProductRequest +from google.cloud.retail_v2.types.promotion import Promotion +from google.cloud.retail_v2.types.purge_config import PurgeMetadata +from google.cloud.retail_v2.types.purge_config import PurgeUserEventsRequest +from google.cloud.retail_v2.types.purge_config import PurgeUserEventsResponse +from google.cloud.retail_v2.types.search_service import SearchRequest +from google.cloud.retail_v2.types.search_service import SearchResponse +from google.cloud.retail_v2.types.user_event import CompletionDetail +from google.cloud.retail_v2.types.user_event import ProductDetail +from google.cloud.retail_v2.types.user_event import PurchaseTransaction +from google.cloud.retail_v2.types.user_event import UserEvent +from google.cloud.retail_v2.types.user_event_service import CollectUserEventRequest +from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsMetadata +from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsRequest +from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsResponse +from google.cloud.retail_v2.types.user_event_service import WriteUserEventRequest + +__all__ = ('CatalogServiceClient', + 'CatalogServiceAsyncClient', + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', + 'ProductServiceClient', + 'ProductServiceAsyncClient', + 'SearchServiceClient', + 'SearchServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'Catalog', + 'ProductLevelConfig', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'SetDefaultBranchRequest', + 'UpdateCatalogRequest', + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2/google/cloud/retail/py.typed b/owl-bot-staging/v2/google/cloud/retail/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py new file mode 100644 index 00000000..c7f56a8d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.catalog_service import CatalogServiceClient +from .services.catalog_service import CatalogServiceAsyncClient +from .services.completion_service import CompletionServiceClient +from .services.completion_service import CompletionServiceAsyncClient +from .services.prediction_service import PredictionServiceClient +from .services.prediction_service import PredictionServiceAsyncClient +from .services.product_service import ProductServiceClient +from .services.product_service import ProductServiceAsyncClient +from .services.search_service import SearchServiceClient +from .services.search_service import SearchServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.catalog import Catalog +from .types.catalog import ProductLevelConfig +from .types.catalog_service import GetDefaultBranchRequest +from .types.catalog_service import GetDefaultBranchResponse +from .types.catalog_service import ListCatalogsRequest +from .types.catalog_service import ListCatalogsResponse +from .types.catalog_service import SetDefaultBranchRequest +from .types.catalog_service import UpdateCatalogRequest +from .types.common import Audience +from .types.common import ColorInfo +from .types.common import CustomAttribute +from .types.common import FulfillmentInfo +from .types.common import Image +from .types.common import Interval +from .types.common import LocalInventory +from .types.common import PriceInfo +from .types.common import Rating +from .types.common import UserInfo +from .types.completion_service import CompleteQueryRequest +from .types.completion_service import CompleteQueryResponse +from .types.import_config import BigQuerySource +from .types.import_config import CompletionDataInputConfig +from .types.import_config import GcsSource +from .types.import_config import ImportCompletionDataRequest +from .types.import_config import ImportCompletionDataResponse +from .types.import_config import ImportErrorsConfig +from .types.import_config import ImportMetadata +from .types.import_config import ImportProductsRequest +from .types.import_config import ImportProductsResponse +from .types.import_config import ImportUserEventsRequest +from .types.import_config import ImportUserEventsResponse +from .types.import_config import ProductInlineSource +from .types.import_config import ProductInputConfig +from .types.import_config import UserEventImportSummary +from .types.import_config import UserEventInlineSource +from .types.import_config import UserEventInputConfig +from .types.prediction_service import PredictRequest +from .types.prediction_service import PredictResponse +from .types.product import Product +from .types.product_service import AddFulfillmentPlacesMetadata +from .types.product_service import AddFulfillmentPlacesRequest +from .types.product_service import AddFulfillmentPlacesResponse +from .types.product_service import AddLocalInventoriesMetadata +from .types.product_service import AddLocalInventoriesRequest +from .types.product_service import AddLocalInventoriesResponse +from .types.product_service import CreateProductRequest +from .types.product_service import DeleteProductRequest +from .types.product_service import GetProductRequest +from .types.product_service import ListProductsRequest +from .types.product_service import ListProductsResponse +from .types.product_service import RemoveFulfillmentPlacesMetadata +from .types.product_service import RemoveFulfillmentPlacesRequest +from .types.product_service import RemoveFulfillmentPlacesResponse +from .types.product_service import RemoveLocalInventoriesMetadata +from .types.product_service import RemoveLocalInventoriesRequest +from .types.product_service import RemoveLocalInventoriesResponse +from .types.product_service import SetInventoryMetadata +from .types.product_service import SetInventoryRequest +from .types.product_service import SetInventoryResponse +from .types.product_service import UpdateProductRequest +from .types.promotion import Promotion +from .types.purge_config import PurgeMetadata +from .types.purge_config import PurgeUserEventsRequest +from .types.purge_config import PurgeUserEventsResponse +from .types.search_service import SearchRequest +from .types.search_service import SearchResponse +from .types.user_event import CompletionDetail +from .types.user_event import ProductDetail +from .types.user_event import PurchaseTransaction +from .types.user_event import UserEvent +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import RejoinUserEventsMetadata +from .types.user_event_service import RejoinUserEventsRequest +from .types.user_event_service import RejoinUserEventsResponse +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CatalogServiceAsyncClient', + 'CompletionServiceAsyncClient', + 'PredictionServiceAsyncClient', + 'ProductServiceAsyncClient', + 'SearchServiceAsyncClient', + 'UserEventServiceAsyncClient', +'AddFulfillmentPlacesMetadata', +'AddFulfillmentPlacesRequest', +'AddFulfillmentPlacesResponse', +'AddLocalInventoriesMetadata', +'AddLocalInventoriesRequest', +'AddLocalInventoriesResponse', +'Audience', +'BigQuerySource', +'Catalog', +'CatalogServiceClient', +'CollectUserEventRequest', +'ColorInfo', +'CompleteQueryRequest', +'CompleteQueryResponse', +'CompletionDataInputConfig', +'CompletionDetail', +'CompletionServiceClient', +'CreateProductRequest', +'CustomAttribute', +'DeleteProductRequest', +'FulfillmentInfo', +'GcsSource', +'GetDefaultBranchRequest', +'GetDefaultBranchResponse', +'GetProductRequest', +'Image', +'ImportCompletionDataRequest', +'ImportCompletionDataResponse', +'ImportErrorsConfig', +'ImportMetadata', +'ImportProductsRequest', +'ImportProductsResponse', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'Interval', +'ListCatalogsRequest', +'ListCatalogsResponse', +'ListProductsRequest', +'ListProductsResponse', +'LocalInventory', +'PredictRequest', +'PredictResponse', +'PredictionServiceClient', +'PriceInfo', +'Product', +'ProductDetail', +'ProductInlineSource', +'ProductInputConfig', +'ProductLevelConfig', +'ProductServiceClient', +'Promotion', +'PurchaseTransaction', +'PurgeMetadata', +'PurgeUserEventsRequest', +'PurgeUserEventsResponse', +'Rating', +'RejoinUserEventsMetadata', +'RejoinUserEventsRequest', +'RejoinUserEventsResponse', +'RemoveFulfillmentPlacesMetadata', +'RemoveFulfillmentPlacesRequest', +'RemoveFulfillmentPlacesResponse', +'RemoveLocalInventoriesMetadata', +'RemoveLocalInventoriesRequest', +'RemoveLocalInventoriesResponse', +'SearchRequest', +'SearchResponse', +'SearchServiceClient', +'SetDefaultBranchRequest', +'SetInventoryMetadata', +'SetInventoryRequest', +'SetInventoryResponse', +'UpdateCatalogRequest', +'UpdateProductRequest', +'UserEvent', +'UserEventImportSummary', +'UserEventInlineSource', +'UserEventInputConfig', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json new file mode 100644 index 00000000..9e04aec8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json @@ -0,0 +1,333 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.retail_v2", + "protoPackage": "google.cloud.retail.v2", + "schema": "1.0", + "services": { + "CatalogService": { + "clients": { + "grpc": { + "libraryClient": "CatalogServiceClient", + "rpcs": { + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CatalogServiceAsyncClient", + "rpcs": { + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + } + } + } + } + }, + "CompletionService": { + "clients": { + "grpc": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CompletionServiceAsyncClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + } + } + }, + "PredictionService": { + "clients": { + "grpc": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionServiceAsyncClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + } + } + }, + "ProductService": { + "clients": { + "grpc": { + "libraryClient": "ProductServiceClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductServiceAsyncClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + } + } + }, + "SearchService": { + "clients": { + "grpc": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SearchServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/py.typed b/owl-bot-staging/v2/google/cloud/retail_v2/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py new file mode 100644 index 00000000..d276b897 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CatalogServiceClient +from .async_client import CatalogServiceAsyncClient + +__all__ = ( + 'CatalogServiceClient', + 'CatalogServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py new file mode 100644 index 00000000..b0a1b99e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py @@ -0,0 +1,653 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.services.catalog_service import pagers +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport +from .client import CatalogServiceClient + + +class CatalogServiceAsyncClient: + """Service for managing catalog configuration.""" + + _client: CatalogServiceClient + + DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(CatalogServiceClient.branch_path) + parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) + catalog_path = staticmethod(CatalogServiceClient.catalog_path) + parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) + common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CatalogServiceClient.common_project_path) + parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) + common_location_path = staticmethod(CatalogServiceClient.common_location_path) + parse_common_location_path = staticmethod(CatalogServiceClient.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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CatalogServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsAsyncPager: + r"""Lists all the [Catalog][google.cloud.retail.v2.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_list_catalogs(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + parent (:class:`str`): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2.Catalog]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.retail_v2.services.catalog_service.pagers.ListCatalogsAsyncPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.ListCatalogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_catalogs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCatalogsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_update_catalog(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] + method. + catalog (:class:`google.cloud.retail_v2.types.Catalog`): + Required. The [Catalog][google.cloud.retail.v2.Catalog] + to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2.Catalog], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_catalog, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_set_default_branch(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (:class:`str`): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.SetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_get_default_branch(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (:class:`str`): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # 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_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py new file mode 100644 index 00000000..dab9ff8c --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py @@ -0,0 +1,862 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.services.catalog_service import pagers +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CatalogServiceGrpcTransport +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +class CatalogServiceClientMeta(type): + """Metaclass for the CatalogService 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[CatalogServiceTransport]] + _transport_registry["grpc"] = CatalogServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CatalogServiceTransport]: + """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): + """Service for managing catalog configuration.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CatalogServiceClient: 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: + CatalogServiceClient: 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) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CatalogServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CatalogServiceTransport): + # transport is a CatalogServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsPager: + r"""Lists all the [Catalog][google.cloud.retail.v2.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_list_catalogs(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2.Catalog]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.retail_v2.services.catalog_service.pagers.ListCatalogsPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ListCatalogsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ListCatalogsRequest): + request = catalog_service.ListCatalogsRequest(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_catalogs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCatalogsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_update_catalog(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] + method. + catalog (google.cloud.retail_v2.types.Catalog): + Required. The [Catalog][google.cloud.retail.v2.Catalog] + to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2.Catalog], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCatalogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCatalogRequest): + request = catalog_service.UpdateCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + 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_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_set_default_branch(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.SetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.SetDefaultBranchRequest): + request = catalog_service.SetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_get_default_branch(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetDefaultBranchRequest): + request = catalog_service.GetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py new file mode 100644 index 00000000..11dd0677 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog_service + + +class ListCatalogsPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.ListCatalogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.ListCatalogsResponse` + 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[..., catalog_service.ListCatalogsResponse], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + for page in self.pages: + yield from page.catalogs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCatalogsAsyncPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.ListCatalogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.ListCatalogsResponse` + 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[catalog_service.ListCatalogsResponse]], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + async def async_generator(): + async for page in self.pages: + for response in page.catalogs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py new file mode 100644 index 00000000..0cffa336 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 CatalogServiceTransport +from .grpc import CatalogServiceGrpcTransport +from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] +_transport_registry['grpc'] = CatalogServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport + +__all__ = ( + 'CatalogServiceTransport', + 'CatalogServiceGrpcTransport', + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py new file mode 100644 index 00000000..661247c1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py @@ -0,0 +1,198 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CatalogServiceTransport(abc.ABC): + """Abstract transport class for CatalogService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_catalogs: gapic_v1.method.wrap_method( + self.list_catalogs, + default_timeout=None, + client_info=client_info, + ), + self.update_catalog: gapic_v1.method.wrap_method( + self.update_catalog, + default_timeout=None, + client_info=client_info, + ), + self.set_default_branch: gapic_v1.method.wrap_method( + self.set_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_default_branch: gapic_v1.method.wrap_method( + self.get_default_branch, + 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Union[ + catalog_service.ListCatalogsResponse, + Awaitable[catalog_service.ListCatalogsResponse] + ]]: + raise NotImplementedError() + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Union[ + gcr_catalog.Catalog, + Awaitable[gcr_catalog.Catalog] + ]]: + raise NotImplementedError() + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Union[ + catalog_service.GetDefaultBranchResponse, + Awaitable[catalog_service.GetDefaultBranchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CatalogServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py new file mode 100644 index 00000000..17492b4a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO + + +class CatalogServiceGrpcTransport(CatalogServiceTransport): + """gRPC backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + catalog_service.ListCatalogsResponse]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + ~.ListCatalogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + gcr_catalog.Catalog]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + ~.Catalog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + empty_pb2.Empty]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + ~.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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + catalog_service.GetDefaultBranchResponse]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + ~.GetDefaultBranchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CatalogServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..dfc3cd7b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py @@ -0,0 +1,380 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CatalogServiceGrpcTransport + + +class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): + """gRPC AsyncIO backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Awaitable[catalog_service.ListCatalogsResponse]]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + Awaitable[~.ListCatalogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Awaitable[gcr_catalog.Catalog]]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + Awaitable[~.Catalog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + 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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Awaitable[catalog_service.GetDefaultBranchResponse]]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + Awaitable[~.GetDefaultBranchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py new file mode 100644 index 00000000..b8af95bd --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CompletionServiceClient +from .async_client import CompletionServiceAsyncClient + +__all__ = ( + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py new file mode 100644 index 00000000..9e5d6432 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .client import CompletionServiceClient + + +class CompletionServiceAsyncClient: + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: CompletionServiceClient + + DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(CompletionServiceClient.catalog_path) + parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) + common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CompletionServiceClient.common_project_path) + parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) + common_location_path = staticmethod(CompletionServiceClient.common_location_path) + parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CompletionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_complete_query(): + # Create a client + client = retail_v2.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_query, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_import_completion_data(): + # Create a client + client = retail_v2.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. + 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. + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_completion_data, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py new file mode 100644 index 00000000..ca5bb55d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CompletionServiceGrpcTransport +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +class CompletionServiceClientMeta(type): + """Metaclass for the CompletionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] + _transport_registry["grpc"] = CompletionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CompletionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CompletionServiceClient(metaclass=CompletionServiceClientMeta): + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CompletionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CompletionServiceTransport): + # transport is a CompletionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_complete_query(): + # Create a client + client = retail_v2.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a completion_service.CompleteQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, completion_service.CompleteQueryRequest): + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_import_completion_data(): + # Create a client + client = retail_v2.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. + 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. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportCompletionDataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportCompletionDataRequest): + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_completion_data] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py new file mode 100644 index 00000000..a0c9542f --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CompletionServiceTransport +from .grpc import CompletionServiceGrpcTransport +from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] +_transport_registry['grpc'] = CompletionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport + +__all__ = ( + 'CompletionServiceTransport', + 'CompletionServiceGrpcTransport', + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py new file mode 100644 index 00000000..7b2cb516 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CompletionServiceTransport(abc.ABC): + """Abstract transport class for CompletionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.complete_query: gapic_v1.method.wrap_method( + self.complete_query, + default_timeout=None, + client_info=client_info, + ), + self.import_completion_data: gapic_v1.method.wrap_method( + self.import_completion_data, + 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Union[ + completion_service.CompleteQueryResponse, + Awaitable[completion_service.CompleteQueryResponse] + ]]: + raise NotImplementedError() + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CompletionServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py new file mode 100644 index 00000000..44cb929b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py @@ -0,0 +1,325 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO + + +class CompletionServiceGrpcTransport(CompletionServiceTransport): + """gRPC backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + ~.CompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + operations_pb2.Operation]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CompletionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..f7131541 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py @@ -0,0 +1,324 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CompletionServiceGrpcTransport + + +class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): + """gRPC AsyncIO backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Awaitable[completion_service.CompleteQueryResponse]]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + Awaitable[~.CompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + 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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py new file mode 100644 index 00000000..7c079c80 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import PredictionServiceClient +from .async_client import PredictionServiceAsyncClient + +__all__ = ( + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py new file mode 100644 index 00000000..ae9f9c86 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport +from .client import PredictionServiceClient + + +class PredictionServiceAsyncClient: + """Service for making recommendation prediction.""" + + _client: PredictionServiceClient + + DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT + + product_path = staticmethod(PredictionServiceClient.product_path) + parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) + common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(PredictionServiceClient.common_project_path) + parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) + common_location_path = staticmethod(PredictionServiceClient.common_location_path) + parse_common_location_path = staticmethod(PredictionServiceClient.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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PredictionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_predict(): + # Create a client + client = retail_v2.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + request = prediction_service.PredictRequest(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.predict, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py new file mode 100644 index 00000000..67a94f53 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py @@ -0,0 +1,480 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionServiceGrpcTransport +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +class PredictionServiceClientMeta(type): + """Metaclass for the PredictionService 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[PredictionServiceTransport]] + _transport_registry["grpc"] = PredictionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PredictionServiceTransport]: + """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): + """Service for making recommendation prediction.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PredictionServiceClient: 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: + PredictionServiceClient: 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) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PredictionServiceTransport): + # transport is a PredictionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_predict(): + # Create a client + client = retail_v2.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a prediction_service.PredictRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_service.PredictRequest): + request = prediction_service.PredictRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.predict] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py new file mode 100644 index 00000000..bb65c664 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PredictionServiceTransport +from .grpc import PredictionServiceGrpcTransport +from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] +_transport_registry['grpc'] = PredictionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport + +__all__ = ( + 'PredictionServiceTransport', + 'PredictionServiceGrpcTransport', + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py new file mode 100644 index 00000000..f3b77c06 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import prediction_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PredictionServiceTransport(abc.ABC): + """Abstract transport class for PredictionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.predict: gapic_v1.method.wrap_method( + self.predict, + 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + Union[ + prediction_service.PredictResponse, + Awaitable[prediction_service.PredictResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'PredictionServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py new file mode 100644 index 00000000..0e86800c --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py @@ -0,0 +1,264 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO + + +class PredictionServiceGrpcTransport(PredictionServiceTransport): + """gRPC backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + prediction_service.PredictResponse]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + ~.PredictResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'PredictionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..472e079a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import PredictionServiceGrpcTransport + + +class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): + """gRPC AsyncIO backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + Awaitable[prediction_service.PredictResponse]]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + Awaitable[~.PredictResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py new file mode 100644 index 00000000..0fa6330a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ProductServiceClient +from .async_client import ProductServiceAsyncClient + +__all__ = ( + 'ProductServiceClient', + 'ProductServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py new file mode 100644 index 00000000..db29be72 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py @@ -0,0 +1,1701 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.services.product_service import pagers +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.cloud.retail_v2.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport +from .client import ProductServiceClient + + +class ProductServiceAsyncClient: + """Service for ingesting [Product][google.cloud.retail.v2.Product] + information of the customer's website. + """ + + _client: ProductServiceClient + + DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(ProductServiceClient.branch_path) + parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) + product_path = staticmethod(ProductServiceClient.product_path) + parse_product_path = staticmethod(ProductServiceClient.parse_product_path) + common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProductServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProductServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProductServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProductServiceClient.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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ProductServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ProductServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_create_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`google.cloud.retail_v2.types.Product`): + Required. The [Product][google.cloud.retail.v2.Product] + to create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + Required. The ID to use for the + [Product][google.cloud.retail.v2.Product], which will + become the final component of the + [Product.name][google.cloud.retail.v2.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2.Product]s with the same + [parent][google.cloud.retail.v2.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_get_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested + [Product][google.cloud.retail.v2.Product] 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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Gets a list of [Product][google.cloud.retail.v2.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_list_products(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2.Product]s under this + branch, regardless of whether or not this branch exists, + a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.services.product_service.pagers.ListProductsAsyncPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_update_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (:class:`google.cloud.retail_v2.types.Product`): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2.Product] to update. The + immutable and output only fields are NOT supported. If + not set, all supported fields (the fields that are + neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + The attribute key can be updated by setting the mask + path as "attributes.${key_name}". If a key name is + present in the mask but not in the patching product from + the request, this key will be deleted after the update. + + 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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_delete_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2.Product] to delete + can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] with more than + one + [variants][google.cloud.retail.v2.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2.Product]s. + + Request processing may be synchronous. Non-existing items are + created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2.Product]s to be successfully + updated. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_import_products(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2.Product] while respecting the + last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_set_inventory(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2.Product() + inventory.title = "title_value" + + request = retail_v2.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (:class:`google.cloud.retail_v2.types.Product`): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product] named in + [Product.name][google.cloud.retail.v2.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.SetInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_inventory, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + async def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places, + while respecting the last update timestamps of each inventory + field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_add_local_inventories(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.AddLocalInventoriesResponse` Response of the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + API. Currently empty because there is no meaningful + response populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places at + a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_remove_local_inventories(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py new file mode 100644 index 00000000..dc6ce5c9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py @@ -0,0 +1,1904 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.services.product_service import pagers +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.cloud.retail_v2.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductServiceGrpcTransport +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +class ProductServiceClientMeta(type): + """Metaclass for the ProductService 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[ProductServiceTransport]] + _transport_registry["grpc"] = ProductServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ProductServiceTransport]: + """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 ProductServiceClient(metaclass=ProductServiceClientMeta): + """Service for ingesting [Product][google.cloud.retail.v2.Product] + information of the customer's website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProductServiceClient: 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: + ProductServiceClient: 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) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ProductServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProductServiceTransport): + # transport is a ProductServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_create_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (google.cloud.retail_v2.types.Product): + Required. The [Product][google.cloud.retail.v2.Product] + to create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2.Product], which will + become the final component of the + [Product.name][google.cloud.retail.v2.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2.Product]s with the same + [parent][google.cloud.retail.v2.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.CreateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.CreateProductRequest): + request = product_service.CreateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_get_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested + [Product][google.cloud.retail.v2.Product] 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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.GetProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.GetProductRequest): + request = product_service.GetProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Gets a list of [Product][google.cloud.retail.v2.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_list_products(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2.Product]s under this + branch, regardless of whether or not this branch exists, + a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.services.product_service.pagers.ListProductsPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.ListProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.ListProductsRequest): + request = product_service.ListProductsRequest(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_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_update_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (google.cloud.retail_v2.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2.Product] to update. The + immutable and output only fields are NOT supported. If + not set, all supported fields (the fields that are + neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + The attribute key can be updated by setting the mask + path as "attributes.${key_name}". If a key name is + present in the mask but not in the patching product from + the request, this key will be deleted after the update. + + 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.retail_v2.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.UpdateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.UpdateProductRequest): + request = product_service.UpdateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + 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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2.Product]. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_delete_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2.Product] to delete + can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] with more than + one + [variants][google.cloud.retail.v2.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.DeleteProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.DeleteProductRequest): + request = product_service.DeleteProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2.Product]s. + + Request processing may be synchronous. Non-existing items are + created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2.Product]s to be successfully + updated. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_import_products(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportProductsRequest): + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2.Product] while respecting the + last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_set_inventory(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2.Product() + inventory.title = "title_value" + + request = retail_v2.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (google.cloud.retail_v2.types.Product): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product] named in + [Product.name][google.cloud.retail.v2.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.SetInventoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.SetInventoryRequest): + request = product_service.SetInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_add_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddFulfillmentPlacesRequest): + request = product_service.AddFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): + request = product_service.RemoveFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places, + while respecting the last update timestamps of each inventory + field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_add_local_inventories(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.AddLocalInventoriesResponse` Response of the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + API. Currently empty because there is no meaningful + response populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddLocalInventoriesRequest): + request = product_service.AddLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places at + a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_remove_local_inventories(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveLocalInventoriesRequest): + request = product_service.RemoveLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py new file mode 100644 index 00000000..f9e49958 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product_service + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.ListProductsResponse` + 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[..., product_service.ListProductsResponse], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[product_service.ListProductsResponse]: + 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[product.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.ListProductsResponse` + 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[product_service.ListProductsResponse]], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: + 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[product.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py new file mode 100644 index 00000000..db824dec --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ProductServiceTransport +from .grpc import ProductServiceGrpcTransport +from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] +_transport_registry['grpc'] = ProductServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport + +__all__ = ( + 'ProductServiceTransport', + 'ProductServiceGrpcTransport', + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py new file mode 100644 index 00000000..e3de653c --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py @@ -0,0 +1,312 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ProductServiceTransport(abc.ABC): + """Abstract transport class for ProductService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_product: gapic_v1.method.wrap_method( + self.create_product, + default_timeout=None, + client_info=client_info, + ), + self.get_product: gapic_v1.method.wrap_method( + self.get_product, + default_timeout=None, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + default_timeout=None, + client_info=client_info, + ), + self.update_product: gapic_v1.method.wrap_method( + self.update_product, + default_timeout=None, + client_info=client_info, + ), + self.delete_product: gapic_v1.method.wrap_method( + self.delete_product, + default_timeout=None, + client_info=client_info, + ), + self.import_products: gapic_v1.method.wrap_method( + self.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.set_inventory: gapic_v1.method.wrap_method( + self.set_inventory, + default_timeout=None, + client_info=client_info, + ), + self.add_fulfillment_places: gapic_v1.method.wrap_method( + self.add_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.remove_fulfillment_places: gapic_v1.method.wrap_method( + self.remove_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.add_local_inventories: gapic_v1.method.wrap_method( + self.add_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.remove_local_inventories: gapic_v1.method.wrap_method( + self.remove_local_inventories, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Union[ + product.Product, + Awaitable[product.Product] + ]]: + raise NotImplementedError() + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Union[ + product_service.ListProductsResponse, + Awaitable[product_service.ListProductsResponse] + ]]: + raise NotImplementedError() + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProductServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py new file mode 100644 index 00000000..108f3215 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py @@ -0,0 +1,680 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO + + +class ProductServiceGrpcTransport(ProductServiceTransport): + """gRPC backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + gcr_product.Product]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.CreateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + product.Product]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + product_service.ListProductsResponse]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + gcr_product.Product]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + ~.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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2.Product]s. + + Request processing may be synchronous. Non-existing items are + created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2.Product]s to be successfully + updated. + + Returns: + Callable[[~.ImportProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + operations_pb2.Operation]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2.Product] while respecting the + last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places, + while respecting the last update timestamps of each inventory + field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places at + a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProductServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..1d4ccc2d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py @@ -0,0 +1,679 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductServiceGrpcTransport + + +class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): + """gRPC AsyncIO backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.CreateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Awaitable[product.Product]]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Awaitable[product_service.ListProductsResponse]]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + 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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2.Product]s. + + Request processing may be synchronous. Non-existing items are + created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2.Product]s to be successfully + updated. + + Returns: + Callable[[~.ImportProductsRequest], + 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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2.Product] while respecting the + last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + 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 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + 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 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places, + while respecting the last update timestamps of each inventory + field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + 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 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2.Product] at a list of places at + a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2.Product] queried by + [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + 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 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py new file mode 100644 index 00000000..2f63fc22 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SearchServiceClient +from .async_client import SearchServiceAsyncClient + +__all__ = ( + 'SearchServiceClient', + 'SearchServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py new file mode 100644 index 00000000..c48710b8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.services.search_service import pagers +from google.cloud.retail_v2.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .client import SearchServiceClient + + +class SearchServiceAsyncClient: + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: SearchServiceClient + + DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(SearchServiceClient.branch_path) + parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + product_path = staticmethod(SearchServiceClient.product_path) + parse_product_path = staticmethod(SearchServiceClient.parse_product_path) + common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(SearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SearchServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAsyncPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_search(): + # Create a client + client = retail_v2.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.services.search_service.pagers.SearchAsyncPager: + Response message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py new file mode 100644 index 00000000..0072e3b0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py @@ -0,0 +1,513 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2.services.search_service import pagers +from google.cloud.retail_v2.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SearchServiceGrpcTransport +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +class SearchServiceClientMeta(type): + """Metaclass for the SearchService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] + _transport_registry["grpc"] = SearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SearchServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SearchServiceClient(metaclass=SearchServiceClientMeta): + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SearchServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SearchServiceTransport): + # transport is a SearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_search(): + # Create a client + client = retail_v2.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.services.search_service.pagers.SearchPager: + Response message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a search_service.SearchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py new file mode 100644 index 00000000..524810e2 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2.types import search_service + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py new file mode 100644 index 00000000..7917cd1d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SearchServiceTransport +from .grpc import SearchServiceGrpcTransport +from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] +_transport_registry['grpc'] = SearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport + +__all__ = ( + 'SearchServiceTransport', + 'SearchServiceGrpcTransport', + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py new file mode 100644 index 00000000..541055f5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2.types import search_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SearchServiceTransport(abc.ABC): + """Abstract transport class for SearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search: gapic_v1.method.wrap_method( + self.search, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Union[ + search_service.SearchResponse, + Awaitable[search_service.SearchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SearchServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py new file mode 100644 index 00000000..ee53c769 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py @@ -0,0 +1,270 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO + + +class SearchServiceGrpcTransport(SearchServiceTransport): + """gRPC backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..6c6e5f29 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SearchServiceGrpcTransport + + +class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): + """gRPC AsyncIO backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Awaitable[search_service.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py new file mode 100644 index 00000000..5f5171c1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py new file mode 100644 index 00000000..99002514 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py @@ -0,0 +1,730 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on the customer + website. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(UserEventServiceClient.catalog_path) + parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) + product_path = staticmethod(UserEventServiceClient.product_path) + parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_write_user_event(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_collect_user_event(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_purge_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_import_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2 + + async def sample_rejoin_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py new file mode 100644 index 00000000..cd1d35d8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py @@ -0,0 +1,930 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[UserEventServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on the customer + website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_write_user_event(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_collect_user_event(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_purge_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeUserEventsRequest): + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_import_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2 + + def sample_rejoin_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.RejoinUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.RejoinUserEventsRequest): + request = user_event_service.RejoinUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py new file mode 100644 index 00000000..f53ee5d7 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py new file mode 100644 index 00000000..661a2d50 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py @@ -0,0 +1,235 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.rejoin_user_events: gapic_v1.method.wrap_method( + self.rejoin_user_events, + 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 write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + user_event.UserEvent, + Awaitable[user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py new file mode 100644 index 00000000..af50579d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..cdc1a2f9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + 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 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py new file mode 100644 index 00000000..8e0ea23a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .catalog import ( + Catalog, + ProductLevelConfig, +) +from .catalog_service import ( + GetDefaultBranchRequest, + GetDefaultBranchResponse, + ListCatalogsRequest, + ListCatalogsResponse, + SetDefaultBranchRequest, + UpdateCatalogRequest, +) +from .common import ( + Audience, + ColorInfo, + CustomAttribute, + FulfillmentInfo, + Image, + Interval, + LocalInventory, + PriceInfo, + Rating, + UserInfo, +) +from .completion_service import ( + CompleteQueryRequest, + CompleteQueryResponse, +) +from .import_config import ( + BigQuerySource, + CompletionDataInputConfig, + GcsSource, + ImportCompletionDataRequest, + ImportCompletionDataResponse, + ImportErrorsConfig, + ImportMetadata, + ImportProductsRequest, + ImportProductsResponse, + ImportUserEventsRequest, + ImportUserEventsResponse, + ProductInlineSource, + ProductInputConfig, + UserEventImportSummary, + UserEventInlineSource, + UserEventInputConfig, +) +from .prediction_service import ( + PredictRequest, + PredictResponse, +) +from .product import ( + Product, +) +from .product_service import ( + AddFulfillmentPlacesMetadata, + AddFulfillmentPlacesRequest, + AddFulfillmentPlacesResponse, + AddLocalInventoriesMetadata, + AddLocalInventoriesRequest, + AddLocalInventoriesResponse, + CreateProductRequest, + DeleteProductRequest, + GetProductRequest, + ListProductsRequest, + ListProductsResponse, + RemoveFulfillmentPlacesMetadata, + RemoveFulfillmentPlacesRequest, + RemoveFulfillmentPlacesResponse, + RemoveLocalInventoriesMetadata, + RemoveLocalInventoriesRequest, + RemoveLocalInventoriesResponse, + SetInventoryMetadata, + SetInventoryRequest, + SetInventoryResponse, + UpdateProductRequest, +) +from .promotion import ( + Promotion, +) +from .purge_config import ( + PurgeMetadata, + PurgeUserEventsRequest, + PurgeUserEventsResponse, +) +from .search_service import ( + SearchRequest, + SearchResponse, +) +from .user_event import ( + CompletionDetail, + ProductDetail, + PurchaseTransaction, + UserEvent, +) +from .user_event_service import ( + CollectUserEventRequest, + RejoinUserEventsMetadata, + RejoinUserEventsRequest, + RejoinUserEventsResponse, + WriteUserEventRequest, +) + +__all__ = ( + 'Catalog', + 'ProductLevelConfig', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'SetDefaultBranchRequest', + 'UpdateCatalogRequest', + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py new file mode 100644 index 00000000..47a372fb --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'ProductLevelConfig', + 'Catalog', + }, +) + + +class ProductLevelConfig(proto.Message): + r"""Configures what level the product should be uploaded with + regards to how users will be send events and how predictions + will be made. + + Attributes: + ingestion_product_type (str): + The type of [Product][google.cloud.retail.v2.Product]s + allowed to be ingested into the catalog. Acceptable values + are: + + - ``primary`` (default): You can ingest + [Product][google.cloud.retail.v2.Product]s of all types. + When ingesting a + [Product][google.cloud.retail.v2.Product], its type will + default to + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + if unset. + - ``variant`` (incompatible with Retail Search): You can + only ingest + [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s. This means + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] + cannot be empty. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``variant`` and + [merchant_center_product_id_field][google.cloud.retail.v2.ProductLevelConfig.merchant_center_product_id_field] + is ``itemGroupId``, an INVALID_ARGUMENT error is returned. + + See `Product + levels `__ + for more details. + merchant_center_product_id_field (str): + Which field of `Merchant Center + Product `__ + should be imported as + [Product.id][google.cloud.retail.v2.Product.id]. Acceptable + values are: + + - ``offerId`` (default): Import ``offerId`` as the product + ID. + - ``itemGroupId``: Import ``itemGroupId`` as the product + ID. Notice that Retail API will choose one item from the + ones with the same ``itemGroupId``, and use it to + represent the item group. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``itemGroupId`` and + [ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] + is ``variant``, an INVALID_ARGUMENT error is returned. + + See `Product + levels `__ + for more details. + """ + + ingestion_product_type = proto.Field( + proto.STRING, + number=1, + ) + merchant_center_product_id_field = proto.Field( + proto.STRING, + number=2, + ) + + +class Catalog(proto.Message): + r"""The catalog configuration. + + Attributes: + name (str): + Required. Immutable. The fully qualified + resource name of the catalog. + display_name (str): + Required. Immutable. The catalog display name. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + product_level_config (google.cloud.retail_v2.types.ProductLevelConfig): + Required. The product level configuration. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + product_level_config = proto.Field( + proto.MESSAGE, + number=4, + message='ProductLevelConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py new file mode 100644 index 00000000..721ef858 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'UpdateCatalogRequest', + 'SetDefaultBranchRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + }, +) + + +class ListCatalogsRequest(proto.Message): + r"""Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + + Attributes: + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2.Catalog]s under this + location, regardless of whether or not this location exists, + a PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of [Catalog][google.cloud.retail.v2.Catalog]s + to return. If unspecified, defaults to 50. The maximum + allowed value is 1000. Values above 1000 will be coerced to + 1000. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [ListCatalogsResponse.next_page_token][google.cloud.retail.v2.ListCatalogsResponse.next_page_token], + received from a previous + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCatalogsResponse(proto.Message): + r"""Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] + method. + + Attributes: + catalogs (Sequence[google.cloud.retail_v2.types.Catalog]): + All the customer's + [Catalog][google.cloud.retail.v2.Catalog]s. + next_page_token (str): + A token that can be sent as + [ListCatalogsRequest.page_token][google.cloud.retail.v2.ListCatalogsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + catalogs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateCatalogRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] + method. + + Attributes: + catalog (google.cloud.retail_v2.types.Catalog): + Required. The [Catalog][google.cloud.retail.v2.Catalog] to + update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2.Catalog], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2.Catalog] 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 + [Catalog][google.cloud.retail.v2.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + catalog = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class SetDefaultBranchRequest(proto.Message): + r"""Request message to set a specified branch as new default_branch. + + Attributes: + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + branch_id (str): + The final component of the resource name of a branch. + + This field must be one of "0", "1" or "2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If there are no sufficient active products in the targeted + branch and + [force][google.cloud.retail.v2.SetDefaultBranchRequest.force] + is not set, a FAILED_PRECONDITION error is returned. + note (str): + Some note on this request, this can be retrieved by + [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch] + before next valid default branch set occurs. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + force (bool): + If set to true, it permits switching to a branch with + [branch_id][google.cloud.retail.v2.SetDefaultBranchRequest.branch_id] + even if it has no sufficient active products. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + force = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetDefaultBranchRequest(proto.Message): + r"""Request message to show which branch is currently the default + branch. + + Attributes: + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDefaultBranchResponse(proto.Message): + r"""Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. + + Attributes: + branch (str): + Full resource name of the branch id currently + set as default branch. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when this branch is set to default. + note (str): + This corresponds to + [SetDefaultBranchRequest.note][google.cloud.retail.v2.SetDefaultBranchRequest.note] + field, when this branch was set as default. + """ + + branch = proto.Field( + proto.STRING, + number=1, + ) + set_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py new file mode 100644 index 00000000..fe50745a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py @@ -0,0 +1,736 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'LocalInventory', + }, +) + + +class Audience(proto.Message): + r"""An intended audience of the + [Product][google.cloud.retail.v2.Product] for whom it's sold. + + Attributes: + genders (Sequence[str]): + The genders of the audience. Strongly encouraged to use the + standard values: "male", "female", "unisex". + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `gender `__. + Schema.org property + `Product.audience.suggestedGender `__. + age_groups (Sequence[str]): + The age groups of the audience. Strongly encouraged to use + the standard values: "newborn" (up to 3 months old), + "infant" (3–12 months old), "toddler" (1–5 years old), + "kids" (5–13 years old), "adult" (typically teens or older). + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `age_group `__. + Schema.org property + `Product.audience.suggestedMinAge `__ + and + `Product.audience.suggestedMaxAge `__. + """ + + genders = proto.RepeatedField( + proto.STRING, + number=1, + ) + age_groups = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class ColorInfo(proto.Message): + r"""The color information of a + [Product][google.cloud.retail.v2.Product]. + + Attributes: + color_families (Sequence[str]): + The standard color families. Strongly recommended to use the + following standard color groups: "Red", "Pink", "Orange", + "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", + "White", "Gray", "Black" and "Mixed". Normally it is + expected to have only 1 color family. May consider using + single "Mixed" instead of multiple values. + + A maximum of 5 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + colors (Sequence[str]): + The color display names, which may be different from + standard color family names, such as the color aliases used + in the website frontend. Normally it is expected to have + only 1 color. May consider using single "Mixed" instead of + multiple values. + + A maximum of 25 colors are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + """ + + color_families = proto.RepeatedField( + proto.STRING, + number=1, + ) + colors = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in + [Product][google.cloud.retail.v2.Product]. + + Attributes: + text (Sequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an INVALID_ARGUMENT + error is returned. + + Exactly one of + [text][google.cloud.retail.v2.CustomAttribute.text] or + [numbers][google.cloud.retail.v2.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + numbers (Sequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [text][google.cloud.retail.v2.CustomAttribute.text] or + [numbers][google.cloud.retail.v2.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + searchable (bool): + This field is normally ignored unless + [AttributesConfig.attribute_config_level][] of the + [Catalog][google.cloud.retail.v2.Catalog] is set to the + deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For + information about product-level attribute configuration, see + `Configuration + modes `__. + If true, custom attribute values are searchable by text + queries in + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2.UserEvent]. + + Only set if type + [text][google.cloud.retail.v2.CustomAttribute.text] is set. + Otherwise, a INVALID_ARGUMENT error is returned. + + This field is a member of `oneof`_ ``_searchable``. + indexable (bool): + This field is normally ignored unless + [AttributesConfig.attribute_config_level][] of the + [Catalog][google.cloud.retail.v2.Catalog] is set to the + deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For + information about product-level attribute configuration, see + `Configuration + modes `__. + If true, custom attribute values are indexed, so that they + can be filtered, faceted or boosted in + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2.UserEvent]. + + See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter], + [SearchRequest.facet_specs][google.cloud.retail.v2.SearchRequest.facet_specs] + and + [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] + for more details. + + This field is a member of `oneof`_ ``_indexable``. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + searchable = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + indexable = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + +class FulfillmentInfo(proto.Message): + r"""Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + Attributes: + type_ (str): + The fulfillment type, including commonly used types (such as + pickup in store and same day delivery), and custom types. + Customers have to map custom types to their display names + before rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + place_ids (Sequence[str]): + The IDs for this + [type][google.cloud.retail.v2.FulfillmentInfo.type], such as + the store IDs for + [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2.FulfillmentInfo.type] + or the region IDs for + [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2.FulfillmentInfo.type]. + + A maximum of 3000 values are allowed. Each value must be a + string with a length limit of 30 characters, matching the + pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". + Otherwise, an INVALID_ARGUMENT error is returned. + """ + + type_ = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class Image(proto.Message): + r"""[Product][google.cloud.retail.v2.Product] image. Recommendations AI + and Retail Search do not use product images to improve prediction + and search results. However, product images can be returned in + results, and are shown in prediction or search previews in the + console. + + Attributes: + uri (str): + Required. URI of the image. + + This field must be a valid UTF-8 encoded URI with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + height (int): + Height of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + width (int): + Width of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + height = proto.Field( + proto.INT32, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + + +class Interval(proto.Message): + r"""A floating point interval. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum = proto.Field( + proto.DOUBLE, + number=1, + oneof='min', + ) + exclusive_minimum = proto.Field( + proto.DOUBLE, + number=2, + oneof='min', + ) + maximum = proto.Field( + proto.DOUBLE, + number=3, + oneof='max', + ) + exclusive_maximum = proto.Field( + proto.DOUBLE, + number=4, + oneof='max', + ) + + +class PriceInfo(proto.Message): + r"""The price information of a + [Product][google.cloud.retail.v2.Product]. + + Attributes: + currency_code (str): + The 3-letter currency code defined in `ISO + 4217 `__. + + If this field is an unrecognizable currency code, an + INVALID_ARGUMENT error is returned. + + The + [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s with the same + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] + must share the same + [currency_code][google.cloud.retail.v2.PriceInfo.currency_code]. + Otherwise, a FAILED_PRECONDITION error is returned. + price (float): + Price of the product. + + Google Merchant Center property + `price `__. + Schema.org property + `Offer.price `__. + original_price (float): + Price of the product without any discount. If zero, by + default set to be the + [price][google.cloud.retail.v2.PriceInfo.price]. If set, + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + should be greater than or equal to + [price][google.cloud.retail.v2.PriceInfo.price], otherwise + an INVALID_ARGUMENT error is thrown. + cost (float): + The costs associated with the sale of a particular product. + Used for gross profit reporting. + + - Profit = [price][google.cloud.retail.v2.PriceInfo.price] + - [cost][google.cloud.retail.v2.PriceInfo.cost] + + Google Merchant Center property + `cost_of_goods_sold `__. + price_effective_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2.PriceInfo.price] starts to be + effective. This can be set as a future timestamp, and the + [price][google.cloud.retail.v2.PriceInfo.price] is only used + for search after + [price_effective_time][google.cloud.retail.v2.PriceInfo.price_effective_time]. + If so, the + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + is used before + [price_effective_time][google.cloud.retail.v2.PriceInfo.price_effective_time]. + + Do not set if + [price][google.cloud.retail.v2.PriceInfo.price] is always + effective because it will cause additional latency during + search. + price_expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2.PriceInfo.price] stops to be + effective. The + [price][google.cloud.retail.v2.PriceInfo.price] is used for + search before + [price_expire_time][google.cloud.retail.v2.PriceInfo.price_expire_time]. + If this field is set, the + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2.PriceInfo.original_price] + is used after + [price_expire_time][google.cloud.retail.v2.PriceInfo.price_expire_time]. + + Do not set if + [price][google.cloud.retail.v2.PriceInfo.price] is always + effective because it will cause additional latency during + search. + price_range (google.cloud.retail_v2.types.PriceInfo.PriceRange): + Output only. The price range of all the child + [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s grouped together + on the + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]. Only populated + for + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]. + Do not set this field in API requests. + """ + + class PriceRange(proto.Message): + r"""The price range of all + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. + + Attributes: + price (google.cloud.retail_v2.types.Interval): + The inclusive + [Product.pricing_info.price][google.cloud.retail.v2.PriceInfo.price] + interval of all + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. + original_price (google.cloud.retail_v2.types.Interval): + The inclusive + [Product.pricing_info.original_price][google.cloud.retail.v2.PriceInfo.original_price] + internal of all + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. + """ + + price = proto.Field( + proto.MESSAGE, + number=1, + message='Interval', + ) + original_price = proto.Field( + proto.MESSAGE, + number=2, + message='Interval', + ) + + currency_code = proto.Field( + proto.STRING, + number=1, + ) + price = proto.Field( + proto.FLOAT, + number=2, + ) + original_price = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + price_effective_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + price_expire_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + price_range = proto.Field( + proto.MESSAGE, + number=7, + message=PriceRange, + ) + + +class Rating(proto.Message): + r"""The rating of a [Product][google.cloud.retail.v2.Product]. + + Attributes: + rating_count (int): + The total number of ratings. This value is independent of + the value of + [rating_histogram][google.cloud.retail.v2.Rating.rating_histogram]. + + This value must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + average_rating (float): + The average rating of the + [Product][google.cloud.retail.v2.Product]. + + The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT + error is returned. + rating_histogram (Sequence[int]): + List of rating counts per rating value (index = rating - 1). + The list is empty if there is no rating. If the list is + non-empty, its size is always 5. Otherwise, an + INVALID_ARGUMENT error is returned. + + For example, [41, 14, 13, 47, 303]. It means that the + [Product][google.cloud.retail.v2.Product] got 41 ratings + with 1 star, 14 ratings with 2 star, and so on. + """ + + rating_count = proto.Field( + proto.INT32, + number=1, + ) + average_rating = proto.Field( + proto.FLOAT, + number=2, + ) + rating_histogram = proto.RepeatedField( + proto.INT32, + number=3, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. Don't set for + anonymous users. + + Always use a hashed value for this ID. + + Don't set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + ip_address (str): + The end user's IP address. This field is used to extract + location information for personalization. + + This field must be either an IPv4 address (e.g. + "104.133.9.80") or an IPv6 address (e.g. + "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an + INVALID_ARGUMENT error is returned. + + This should not be set when: + + - setting + [SearchRequest.user_info][google.cloud.retail.v2.SearchRequest.user_info]. + - using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request] + is set. + user_agent (str): + User agent as included in the HTTP header. Required for + getting + [SearchResponse.sponsored_results][google.cloud.retail.v2.SearchResponse.sponsored_results]. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request] + is set. + direct_user_request (bool): + True if the request is made directly from the end user, in + which case the + [ip_address][google.cloud.retail.v2.UserInfo.ip_address] and + [user_agent][google.cloud.retail.v2.UserInfo.user_agent] can + be populated from the HTTP request. This flag should be set + only if the API request is made directly from the end user + such as a mobile app (and not if a gateway or a server is + processing and pushing the user events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent]. + """ + + user_id = proto.Field( + proto.STRING, + number=1, + ) + ip_address = proto.Field( + proto.STRING, + number=2, + ) + user_agent = proto.Field( + proto.STRING, + number=3, + ) + direct_user_request = proto.Field( + proto.BOOL, + number=4, + ) + + +class LocalInventory(proto.Message): + r"""The inventory information at a place (e.g. a store) + identified by a place ID. + + Attributes: + place_id (str): + The place ID for the current set of inventory + information. + price_info (google.cloud.retail_v2.types.PriceInfo): + Product price and cost information. + + Google Merchant Center property + `price `__. + attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): + Additional local inventory attributes, for example, store + name, promotion tags, etc. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - At most 30 attributes are allowed. + - The key must be a UTF-8 encoded string with a length + limit of 32 characters. + - The key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis + or KEY_1_LIKE_THIS. + - The attribute values must be of the same type (text or + number). + - Only 1 value is allowed for each attribute. + - For text values, the length limit is 256 UTF-8 + characters. + - The attribute does not support search. The ``searchable`` + field should be unset or set to false. + - The max summed total bytes of custom attribute keys and + values per product is 5MiB. + fulfillment_types (Sequence[str]): + Input only. Supported fulfillment types. Valid fulfillment + type values include commonly used types (such as pickup in + store and same day delivery), and custom types. Customers + have to map custom types to their display names before + rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + All the elements must be distinct. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + place_id = proto.Field( + proto.STRING, + number=1, + ) + price_info = proto.Field( + proto.MESSAGE, + number=2, + message='PriceInfo', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='CustomAttribute', + ) + fulfillment_types = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py new file mode 100644 index 00000000..421cc1c0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'CompleteQueryRequest', + 'CompleteQueryResponse', + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Auto-complete parameters. + + Attributes: + catalog (str): + Required. Catalog for which the completion is performed. + + Full resource name of catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + query (str): + Required. The query used to generate + suggestions. + The maximum number of allowed characters is 255. + visitor_id (str): + Required field. A unique identifier for tracking visitors. + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + language_codes (Sequence[str]): + The language filters applied to the output suggestions. If + set, it should contain the language of the query. If not + set, suggestions are returned without considering language + restrictions. This is the BCP-47 language code, such as + "en-US" or "sr-Latn". For more information, see `Tags for + Identifying + Languages `__. The + maximum number of language codes is 3. + device_type (str): + The device type context for completion suggestions. It is + useful to apply different suggestions on different device + types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the + suggestions are across all device types. + + Supported formats: + + - ``UNKNOWN_DEVICE_TYPE`` + + - ``DESKTOP`` + + - ``MOBILE`` + + - A customized string starts with ``OTHER_``, e.g. + ``OTHER_IPHONE``. + dataset (str): + Determines which dataset to use for fetching completion. + "user-data" will use the imported dataset through + [CompletionService.ImportCompletionData][google.cloud.retail.v2.CompletionService.ImportCompletionData]. + "cloud-retail" will use the dataset generated by cloud + retail based on user events. If leave empty, it will use the + "user-data". + + Current supported values: + + - user-data + + - cloud-retail: This option requires enabling auto-learning + function first. See + `guidelines `__. + max_suggestions (int): + Completion max suggestions. If left unset or set to 0, then + will fallback to the configured value + [CompletionConfig.max_suggestions][]. + + The maximum allowed max suggestions is 20. If it is set + higher, it will be capped by 20. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + visitor_id = proto.Field( + proto.STRING, + number=7, + ) + language_codes = proto.RepeatedField( + proto.STRING, + number=3, + ) + device_type = proto.Field( + proto.STRING, + number=4, + ) + dataset = proto.Field( + proto.STRING, + number=6, + ) + max_suggestions = proto.Field( + proto.INT32, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response of the auto-complete query. + + Attributes: + completion_results (Sequence[google.cloud.retail_v2.types.CompleteQueryResponse.CompletionResult]): + Results of the matching suggestions. The + result list is ordered and the first result is + top suggestion. + attribution_token (str): + A unique complete token. This should be included in the + [UserEvent.completion_detail][google.cloud.retail.v2.UserEvent.completion_detail] + for search events resulting from this completion, which + enables accurate attribution of complete model performance. + recent_search_results (Sequence[google.cloud.retail_v2.types.CompleteQueryResponse.RecentSearchResult]): + Matched recent searches of this user. The maximum number of + recent searches is 10. This field is a restricted feature. + Contact Retail Search support team if you are interested in + enabling it. + + This feature is only available when + [CompleteQueryRequest.visitor_id][google.cloud.retail.v2.CompleteQueryRequest.visitor_id] + field is set and + [UserEvent][google.cloud.retail.v2.UserEvent] is imported. + The recent searches satisfy the follow rules: + + - They are ordered from latest to oldest. + + - They are matched with + [CompleteQueryRequest.query][google.cloud.retail.v2.CompleteQueryRequest.query] + case insensitively. + + - They are transformed to lower cases. + + - They are UTF-8 safe. + + Recent searches are deduplicated. More recent searches will + be reserved when duplication happens. + """ + + class CompletionResult(proto.Message): + r"""Resource that represents completion results. + + Attributes: + suggestion (str): + The suggestion for the query. + attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): + Custom attributes for the suggestion term. + + - For "user-data", the attributes are additional custom + attributes ingested through BigQuery. + + - For "cloud-retail", the attributes are product attributes + generated by Cloud Retail. This is an experimental + feature. Contact Retail Search support team if you are + interested in enabling it. + """ + + suggestion = proto.Field( + proto.STRING, + number=1, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=common.CustomAttribute, + ) + + class RecentSearchResult(proto.Message): + r"""Recent search of this user. + + Attributes: + recent_search (str): + The recent search query. + """ + + recent_search = proto.Field( + proto.STRING, + number=1, + ) + + completion_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=CompletionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + recent_search_results = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=RecentSearchResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py new file mode 100644 index 00000000..983e15df --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py @@ -0,0 +1,697 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import user_event +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'GcsSource', + 'BigQuerySource', + 'ProductInlineSource', + 'UserEventInlineSource', + 'ImportErrorsConfig', + 'ImportProductsRequest', + 'ImportUserEventsRequest', + 'ImportCompletionDataRequest', + 'ProductInputConfig', + 'UserEventInputConfig', + 'CompletionDataInputConfig', + 'ImportMetadata', + 'ImportProductsResponse', + 'ImportUserEventsResponse', + 'UserEventImportSummary', + 'ImportCompletionDataResponse', + }, +) + + +class GcsSource(proto.Message): + r"""Google Cloud Storage location for input content. + format. + + Attributes: + input_uris (Sequence[str]): + Required. Google Cloud Storage URIs to input files. URI can + be up to 2000 characters long. URIs can match the full + object path (for example, + ``gs://bucket/directory/object.json``) or a pattern matching + one or more files, such as ``gs://bucket/directory/*.json``. + A request can contain at most 100 files, and each file can + be up to 2 GB. See `Importing product + information `__ + for the expected file format and setup instructions. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2.Product] per line. Each + product must have a valid + [Product.id][google.cloud.retail.v2.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2.UserEvent] per line. + - ``user_event_ga360``: Using + https://support.google.com/analytics/answer/3437719. + + Supported values for control imports: + + - 'control' (default): One JSON [Control][] per line. + + Supported values for catalog attribute imports: + + - 'catalog_attribute' (default): One CSV + [CatalogAttribute][] per line. + """ + + input_uris = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID (can be project # or ID) that + the BigQuery source is in with a length limit of + 128 characters. If not specified, inherits the + project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2.Product] per line. Each + product must have a valid + [Product.id][google.cloud.retail.v2.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2.UserEvent] per line. + - ``user_event_ga360``: The schema is available here: + https://support.google.com/analytics/answer/3437719. + - ``user_event_ga4``: This feature is in private preview. + Please contact the support team for importing Google + Analytics 4 events. The schema is available here: + https://support.google.com/analytics/answer/7029846. + + Supported values for auto-completion imports: + + - ``suggestions`` (default): One JSON completion suggestion + per line. + - ``denylist``: One JSON deny suggestion per line. + - ``allowlist``: One JSON allow suggestion per line. + """ + + partition_date = proto.Field( + proto.MESSAGE, + number=6, + oneof='partition', + message=date_pb2.Date, + ) + project_id = proto.Field( + proto.STRING, + number=5, + ) + dataset_id = proto.Field( + proto.STRING, + number=1, + ) + table_id = proto.Field( + proto.STRING, + number=2, + ) + gcs_staging_dir = proto.Field( + proto.STRING, + number=3, + ) + data_schema = proto.Field( + proto.STRING, + number=4, + ) + + +class ProductInlineSource(proto.Message): + r"""The inline source for the input config for ImportProducts + method. + + Attributes: + products (Sequence[google.cloud.retail_v2.types.Product]): + Required. A list of products to update/create. Each product + must have a valid + [Product.id][google.cloud.retail.v2.Product.id]. Recommended + max of 100 items. + """ + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=product.Product, + ) + + +class UserEventInlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (Sequence[google.cloud.retail_v2.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + +class ImportErrorsConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage prefix for import errors. This must be + an empty, existing Cloud Storage directory. Import errors + will be written to sharded files in this directory, one per + line, as a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportProductsRequest(proto.Message): + r"""Request message for Import methods. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` + + If no updateMask is specified, requires products.create + permission. If updateMask is specified, requires + products.update permission. + request_id (str): + Deprecated. This field has no effect. + input_config (google.cloud.retail_v2.types.ProductInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported 'products' to update. If not set, will + by default update all fields. + reconciliation_mode (google.cloud.retail_v2.types.ImportProductsRequest.ReconciliationMode): + The mode of reconciliation between existing products and the + products to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. + notification_pubsub_topic (str): + Full Pub/Sub topic name for receiving notification. If this + field is set, when the import is finished, a notification + will be sent to specified Pub/Sub topic. The message data + will be JSON string of a + [Operation][google.longrunning.Operation]. + + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. It has to be within + the same project as + [ImportProductsRequest.parent][google.cloud.retail.v2.ImportProductsRequest.parent]. + Make sure that both + ``cloud-retail-customer-data-access@system.gserviceaccount.com`` + and + ``service-@gcp-sa-retail.iam.gserviceaccount.com`` + have the ``pubsub.topics.publish`` IAM permission on the + topic. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + """ + class ReconciliationMode(proto.Enum): + r"""Indicates how imported products are reconciled with the + existing products created or imported before. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + request_id = proto.Field( + proto.STRING, + number=6, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='ProductInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + reconciliation_mode = proto.Field( + proto.ENUM, + number=5, + enum=ReconciliationMode, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=7, + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + input_config (google.cloud.retail_v2.types.UserEventInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='UserEventInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + + +class ImportCompletionDataRequest(proto.Message): + r"""Request message for ImportCompletionData methods. + + Attributes: + parent (str): + Required. The catalog which the suggestions dataset belongs + to. + + Format: + ``projects/1234/locations/global/catalogs/default_catalog``. + input_config (google.cloud.retail_v2.types.CompletionDataInputConfig): + Required. The desired input location of the + data. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='CompletionDataInputConfig', + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=3, + ) + + +class ProductInputConfig(proto.Message): + r"""The input config source for products. + + 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: + product_inline_source (google.cloud.retail_v2.types.ProductInlineSource): + The Inline source for the input content for + products. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2.types.GcsSource): + Google Cloud Storage location for the input + content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + product_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='ProductInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class UserEventInputConfig(proto.Message): + r"""The input config source for user events. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user_event_inline_source (google.cloud.retail_v2.types.UserEventInlineSource): + Required. The Inline source for the input + content for UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2.types.GcsSource): + Required. Google Cloud Storage location for + the input content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2.types.BigQuerySource): + Required. BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + user_event_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='UserEventInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class CompletionDataInputConfig(proto.Message): + r"""The input config source for completion data. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + big_query_source (google.cloud.retail_v2.types.BigQuerySource): + Required. BigQuery input source. + Add the IAM permission "BigQuery Data Viewer" + for + cloud-retail-customer-data-access@system.gserviceaccount.com + before using this feature otherwise an error is + thrown. + + This field is a member of `oneof`_ ``source``. + """ + + big_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='BigQuerySource', + ) + + +class ImportMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + request_id (str): + Deprecated. This field is never set. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=3, + ) + failure_count = proto.Field( + proto.INT64, + number=4, + ) + request_id = proto.Field( + proto.STRING, + number=5, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=6, + ) + + +class ImportProductsResponse(proto.Message): + r"""Response of the + [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + import_summary (google.cloud.retail_v2.types.UserEventImportSummary): + Aggregated statistics of user event import + status. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + import_summary = proto.Field( + proto.MESSAGE, + number=3, + message='UserEventImportSummary', + ) + + +class UserEventImportSummary(proto.Message): + r"""A summary of import result. The UserEventImportSummary + summarizes the import status for user events. + + Attributes: + joined_events_count (int): + Count of user events imported with complete + existing catalog information. + unjoined_events_count (int): + Count of user events imported, but with + catalog information not found in the imported + catalog. + """ + + joined_events_count = proto.Field( + proto.INT64, + number=1, + ) + unjoined_events_count = proto.Field( + proto.INT64, + number=2, + ) + + +class ImportCompletionDataResponse(proto.Message): + r"""Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. + 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 (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py new file mode 100644 index 00000000..68e8c74b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py @@ -0,0 +1,275 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import user_event as gcr_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'PredictRequest', + 'PredictResponse', + }, +) + + +class PredictRequest(proto.Message): + r"""Request message for Predict method. + + Attributes: + placement (str): + Required. Full resource name of the format: + {name=projects/*/locations/global/catalogs/default_catalog/placements/*} + The ID of the Recommendations AI placement. Before you can + request predictions from your model, you must create at + least one placement for it. For more information, see + `Managing + placements `__. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements + user_event (google.cloud.retail_v2.types.UserEvent): + Required. Context about the user, what they are looking at + and what action they took to trigger the predict request. + Note that this user event detail won't be ingested to + userEvent logs. Thus, a separate userEvent write request is + required for event logging. + + Don't set + [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] + or + [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] + to the same fixed ID for different users. If you are trying + to receive non-personalized recommendations (not + recommended; this can negatively impact model performance), + instead set + [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] + to a random unique ID and leave + [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] + unset. + page_size (int): + Maximum number of results to return per page. + Set this property to the number of prediction + results needed. If zero, the service will choose + a reasonable default. The maximum allowed value + is 100. Values above 100 will be coerced to 100. + page_token (str): + The previous PredictResponse.next_page_token. + filter (str): + Filter for restricting prediction results with a length + limit of 5,000 characters. Accepts values for tags and the + ``filterOutOfStockItems`` flag. + + - Tag expressions. Restricts predictions to products that + match all of the specified tags. Boolean operators ``OR`` + and ``NOT`` are supported if the expression is enclosed + in parentheses, and must be separated from the tag values + by a space. ``-"tagA"`` is also supported and is + equivalent to ``NOT "tagA"``. Tag values must be double + quoted UTF-8 encoded strings with a size limit of 1,000 + characters. + + Note: "Recently viewed" models don't support tag + filtering at the moment. + + - filterOutOfStockItems. Restricts predictions to products + that do not have a stockState value of OUT_OF_STOCK. + + Examples: + + - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT + "promotional") + - filterOutOfStockItems tag=(-"promotional") + - filterOutOfStockItems + + If your filter blocks all prediction results, the API will + return generic (unfiltered) popular products. If you only + want results strictly matching the filters, set + ``strictFiltering`` to True in ``PredictRequest.params`` to + receive empty results instead. Note that the API will never + return items with storageStatus of "EXPIRED" or "DELETED" + regardless of filter choices. + validate_only (bool): + Use validate only mode for this prediction + query. If set to true, a dummy model will be + used that returns arbitrary products. Note that + the validate only mode should only be used for + testing the API, or if the model is not ready. + params (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific parameters for the predictions. + + Allowed values: + + - ``returnProduct``: Boolean. If set to true, the + associated product object will be returned in the + ``results.metadata`` field in the prediction response. + - ``returnScore``: Boolean. If set to true, the prediction + 'score' corresponding to each returned product will be + set in the ``results.metadata`` field in the prediction + response. The given 'score' indicates the probability of + an product being clicked/purchased given the user's + context and history. + - ``strictFiltering``: Boolean. True by default. If set to + false, the service will return generic (unfiltered) + popular products instead of empty if your filter blocks + all prediction results. + - ``priceRerankLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of + {'no-price-reranking', 'low-price-reranking', + 'medium-price-reranking', 'high-price-reranking'}. This + gives request-level control and adjusts prediction + results based on product price. + - ``diversityLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of {'no-diversity', + 'low-diversity', 'medium-diversity', 'high-diversity', + 'auto-diversity'}. This gives request-level control and + adjusts prediction results based on product category. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + placement = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + filter = proto.Field( + proto.STRING, + number=5, + ) + validate_only = proto.Field( + proto.BOOL, + number=6, + ) + params = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class PredictResponse(proto.Message): + r"""Response message for predict method. + + Attributes: + results (Sequence[google.cloud.retail_v2.types.PredictResponse.PredictionResult]): + A list of recommended products. The order + represents the ranking (from the most relevant + product to the least). + attribution_token (str): + A unique attribution token. This should be included in the + [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting + from this recommendation, which enables accurate attribution + of recommendation model performance. + missing_ids (Sequence[str]): + IDs of products in the request that were + missing from the inventory. + validate_only (bool): + True if the validateOnly property was set in + the request. + """ + + class PredictionResult(proto.Message): + r"""PredictionResult represents the recommendation prediction + results. + + Attributes: + id (str): + ID of the recommended product + metadata (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional product metadata / annotations. + + Possible values: + + - ``product``: JSON representation of the product. Is set + if ``returnProduct`` is set to true in + ``PredictRequest.params``. + - ``score``: Prediction score in double value. Is set if + ``returnScore`` is set to true in + ``PredictRequest.params``. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + metadata = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=PredictionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + missing_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py new file mode 100644 index 00000000..bff41d83 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py @@ -0,0 +1,701 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'Product', + }, +) + + +class Product(proto.Message): + r"""Product captures all metadata information of items to be + recommended or searched. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this product becomes unavailable for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + + If it is set, the [Product][google.cloud.retail.v2.Product] + is not available for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + after + [expire_time][google.cloud.retail.v2.Product.expire_time]. + However, the product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + [expire_time][google.cloud.retail.v2.Product.expire_time] + must be later than + [available_time][google.cloud.retail.v2.Product.available_time] + and + [publish_time][google.cloud.retail.v2.Product.publish_time], + otherwise an INVALID_ARGUMENT error is thrown. + + Corresponding properties: Google Merchant Center property + `expiration_date `__. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Input only. The TTL (time to live) of the product. + + If it is set, it must be a non-negative value, and + [expire_time][google.cloud.retail.v2.Product.expire_time] is + set as current timestamp plus + [ttl][google.cloud.retail.v2.Product.ttl]. The derived + [expire_time][google.cloud.retail.v2.Product.expire_time] is + returned in the output and + [ttl][google.cloud.retail.v2.Product.ttl] is left blank when + retrieving the [Product][google.cloud.retail.v2.Product]. + + If it is set, the product is not available for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + after current timestamp plus + [ttl][google.cloud.retail.v2.Product.ttl]. However, the + product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. + + This field is a member of `oneof`_ ``expiration``. + name (str): + Immutable. Full resource name of the product, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. + id (str): + Immutable. [Product][google.cloud.retail.v2.Product] + identifier, which is the final component of + [name][google.cloud.retail.v2.Product.name]. For example, + this field is "id_1", if + [name][google.cloud.retail.v2.Product.name] is + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `id `__. + Schema.org property + `Product.sku `__. + type_ (google.cloud.retail_v2.types.Product.Type): + Immutable. The type of the product. Default to + [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] + if unset. + primary_product_id (str): + Variant group identifier. Must be an + [id][google.cloud.retail.v2.Product.id], with the same + parent branch with this product. Otherwise, an error is + thrown. + + For + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]s, this field can + only be empty or set to the same value as + [id][google.cloud.retail.v2.Product.id]. + + For VARIANT [Product][google.cloud.retail.v2.Product]s, this + field cannot be empty. A maximum of 2,000 products are + allowed to share the same + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `item_group_id `__. + Schema.org property + `Product.inProductGroupWithID `__. + collection_member_ids (Sequence[str]): + The [id][google.cloud.retail.v2.Product.id] of the + collection members when + [type][google.cloud.retail.v2.Product.type] is + [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]. + + Non-existent product ids are allowed. The + [type][google.cloud.retail.v2.Product.type] of the members + must be either + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + or + [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + otherwise and INVALID_ARGUMENT error is thrown. Should not + set it for other types. A maximum of 1000 values are + allowed. Otherwise, an INVALID_ARGUMENT error is return. + gtin (str): + The Global Trade Item Number (GTIN) of the product. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This field must be a Unigram. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `gtin `__. + Schema.org property + `Product.isbn `__, + `Product.gtin8 `__, + `Product.gtin12 `__, + `Product.gtin13 `__, or + `Product.gtin14 `__. + + If the value is not a valid GTIN, an INVALID_ARGUMENT error + is returned. + categories (Sequence[str]): + Product categories. This field is repeated for supporting + one product belonging to several parallel categories. + Strongly recommended using the full path for better search / + recommendation quality. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + For example, if a shoes product belongs to both ["Shoes & + Accessories" -> "Shoes"] and ["Sports & Fitness" -> + "Athletic Clothing" -> "Shoes"], it could be represented as: + + :: + + "categories": [ + "Shoes & Accessories > Shoes", + "Sports & Fitness > Athletic Clothing > Shoes" + ] + + Must be set for + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] otherwise an + INVALID_ARGUMENT error is returned. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2.Product]. Empty values are + not allowed. Each value must be a UTF-8 encoded string with + a length limit of 5,000 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `google_product_category `__. + Schema.org property [Product.category] + (https://schema.org/category). + title (str): + Required. Product title. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `title `__. + Schema.org property + `Product.name `__. + brands (Sequence[str]): + The brands of the product. + + A maximum of 30 brands are allowed. Each brand must be a + UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `brand `__. + Schema.org property + `Product.brand `__. + description (str): + Product description. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `description `__. + Schema.org property + `Product.description `__. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. + + For product prediction, this field is ignored and the model + automatically detects the text language. The + [Product][google.cloud.retail.v2.Product] can include text + in different languages, but duplicating + [Product][google.cloud.retail.v2.Product]s to provide text + in multiple languages can result in degraded model + performance. + + For product search this field is in use. It defaults to + "en-US" if unset. + attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): + Highly encouraged. Extra product attributes to be included. + For example, for products, this could include the store + name, vendor, style, color, etc. These are very strong + signals for recommendation model, thus we highly recommend + providing the attributes here. + + Features that can take on one of a limited number of + possible values. Two types of features can be set are: + + Textual features. some examples would be the brand/maker of + a product, or country of a customer. Numerical features. + Some examples would be the height/weight of a product, or + age of a customer. + + For example: + ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - Max entries count: 200. + - The key must be a UTF-8 encoded string with a length + limit of 128 characters. + - For indexable attribute, the key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, + ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a + non-empty UTF-8 encoded string with a length limit of 256 + characters. + - For number attributes, at most 400 values are allowed. + tags (Sequence[str]): + Custom tags associated with the product. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2.Product]. This value must + be a UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This tag can be used for filtering recommendation results by + passing the tag as part of the + [PredictRequest.filter][google.cloud.retail.v2.PredictRequest.filter]. + + Corresponding properties: Google Merchant Center property + `custom_label_0–4 `__. + price_info (google.cloud.retail_v2.types.PriceInfo): + Product price and cost information. + + Corresponding properties: Google Merchant Center property + `price `__. + rating (google.cloud.retail_v2.types.Rating): + The rating of this product. + available_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this + [Product][google.cloud.retail.v2.Product] becomes available + for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + availability (google.cloud.retail_v2.types.Product.Availability): + The online availability of the + [Product][google.cloud.retail.v2.Product]. Default to + [Availability.IN_STOCK][google.cloud.retail.v2.Product.Availability.IN_STOCK]. + + Corresponding properties: Google Merchant Center property + `availability `__. + Schema.org property + `Offer.availability `__. + available_quantity (google.protobuf.wrappers_pb2.Int32Value): + The available quantity of the item. + fulfillment_info (Sequence[google.cloud.retail_v2.types.FulfillmentInfo]): + Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + All the elements must have distinct + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type]. + Otherwise, an INVALID_ARGUMENT error is returned. + uri (str): + Canonical URL directly linking to the product detail page. + + It is strongly recommended to provide a valid uri for the + product, otherwise the service performance could be + significantly degraded. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `link `__. + Schema.org property `Offer.url `__. + images (Sequence[google.cloud.retail_v2.types.Image]): + Product images for the product. We highly recommend putting + the main image first. + + A maximum of 300 images are allowed. + + Corresponding properties: Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + audience (google.cloud.retail_v2.types.Audience): + The target group associated with a given + audience (e.g. male, veterans, car owners, + musicians, etc.) of the product. + color_info (google.cloud.retail_v2.types.ColorInfo): + The color of the product. + + Corresponding properties: Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + sizes (Sequence[str]): + The size of the product. To represent different size systems + or size types, consider using this format: + [[[size_system:]size_type:]size_value]. + + For example, in "US:MENS:M", "US" represents size system; + "MENS" represents size type; "M" represents size value. In + "GIRLS:27", size system is empty; "GIRLS" represents size + type; "27" represents size value. In "32 inches", both size + system and size type are empty, while size value is "32 + inches". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2.Product]. Each value must + be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `size `__, + `size_type `__, + and + `size_system `__. + Schema.org property + `Product.size `__. + materials (Sequence[str]): + The material of the product. For example, "leather", + "wooden". + + A maximum of 20 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 200 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `material `__. + Schema.org property + `Product.material `__. + patterns (Sequence[str]): + The pattern or graphic print of the product. For example, + "striped", "polka dot", "paisley". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2.Product]. Each value must + be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `pattern `__. + Schema.org property + `Product.pattern `__. + conditions (Sequence[str]): + The condition of the product. Strongly encouraged to use the + standard values: "new", "refurbished", "used". + + A maximum of 1 value is allowed per + [Product][google.cloud.retail.v2.Product]. Each value must + be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `condition `__. + Schema.org property + `Offer.itemCondition `__. + promotions (Sequence[google.cloud.retail_v2.types.Promotion]): + The promotions applied to the product. A maximum of 10 + values are allowed per + [Product][google.cloud.retail.v2.Product]. Only + [Promotion.promotion_id][google.cloud.retail.v2.Promotion.promotion_id] + will be used, other fields will be ignored if set. + publish_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the product is published by the retailer + for the first time, which indicates the freshness of the + products. Note that this field is different from + [available_time][google.cloud.retail.v2.Product.available_time], + given it purely describes product freshness regardless of + when it is available on search and recommendation. + retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the + [Product][google.cloud.retail.v2.Product]s are returned in + [SearchResponse][google.cloud.retail.v2.SearchResponse]. + + Supported fields for all + [type][google.cloud.retail.v2.Product.type]s: + + - [audience][google.cloud.retail.v2.Product.audience] + - [availability][google.cloud.retail.v2.Product.availability] + - [brands][google.cloud.retail.v2.Product.brands] + - [color_info][google.cloud.retail.v2.Product.color_info] + - [conditions][google.cloud.retail.v2.Product.conditions] + - [gtin][google.cloud.retail.v2.Product.gtin] + - [materials][google.cloud.retail.v2.Product.materials] + - [name][google.cloud.retail.v2.Product.name] + - [patterns][google.cloud.retail.v2.Product.patterns] + - [price_info][google.cloud.retail.v2.Product.price_info] + - [rating][google.cloud.retail.v2.Product.rating] + - [sizes][google.cloud.retail.v2.Product.sizes] + - [title][google.cloud.retail.v2.Product.title] + - [uri][google.cloud.retail.v2.Product.uri] + + Supported fields only for + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]: + + - [categories][google.cloud.retail.v2.Product.categories] + - [description][google.cloud.retail.v2.Product.description] + - [images][google.cloud.retail.v2.Product.images] + + Supported fields only for + [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT]: + + - Only the first image in + [images][google.cloud.retail.v2.Product.images] + + To mark + [attributes][google.cloud.retail.v2.Product.attributes] as + retrievable, include paths of the form "attributes.key" + where "key" is the key of a custom attribute, as specified + in [attributes][google.cloud.retail.v2.Product.attributes]. + + For + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION], + the following fields are always returned in + [SearchResponse][google.cloud.retail.v2.SearchResponse] by + default: + + - [name][google.cloud.retail.v2.Product.name] + + For + [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT], + the following fields are always returned in by default: + + - [name][google.cloud.retail.v2.Product.name] + - [color_info][google.cloud.retail.v2.Product.color_info] + + The maximum number of paths is 30. Otherwise, an + INVALID_ARGUMENT error is returned. + + Note: Returning more fields in + [SearchResponse][google.cloud.retail.v2.SearchResponse] can + increase response payload size and serving latency. + variants (Sequence[google.cloud.retail_v2.types.Product]): + Output only. Product variants grouped together on primary + product which share similar product attributes. It's + automatically grouped by + [primary_product_id][google.cloud.retail.v2.Product.primary_product_id] + for all the product variants. Only populated for + [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]. + Do not set this field in API requests. + """ + class Type(proto.Enum): + r"""The type of this product.""" + TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + VARIANT = 2 + COLLECTION = 3 + + class Availability(proto.Enum): + r"""Product availability. If this field is unspecified, the + product is assumed to be in stock. + """ + AVAILABILITY_UNSPECIFIED = 0 + IN_STOCK = 1 + OUT_OF_STOCK = 2 + PREORDER = 3 + BACKORDER = 4 + + expire_time = proto.Field( + proto.MESSAGE, + number=16, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl = proto.Field( + proto.MESSAGE, + number=17, + oneof='expiration', + message=duration_pb2.Duration, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + type_ = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + primary_product_id = proto.Field( + proto.STRING, + number=4, + ) + collection_member_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + gtin = proto.Field( + proto.STRING, + number=6, + ) + categories = proto.RepeatedField( + proto.STRING, + number=7, + ) + title = proto.Field( + proto.STRING, + number=8, + ) + brands = proto.RepeatedField( + proto.STRING, + number=9, + ) + description = proto.Field( + proto.STRING, + number=10, + ) + language_code = proto.Field( + proto.STRING, + number=11, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message=common.CustomAttribute, + ) + tags = proto.RepeatedField( + proto.STRING, + number=13, + ) + price_info = proto.Field( + proto.MESSAGE, + number=14, + message=common.PriceInfo, + ) + rating = proto.Field( + proto.MESSAGE, + number=15, + message=common.Rating, + ) + available_time = proto.Field( + proto.MESSAGE, + number=18, + message=timestamp_pb2.Timestamp, + ) + availability = proto.Field( + proto.ENUM, + number=19, + enum=Availability, + ) + available_quantity = proto.Field( + proto.MESSAGE, + number=20, + message=wrappers_pb2.Int32Value, + ) + fulfillment_info = proto.RepeatedField( + proto.MESSAGE, + number=21, + message=common.FulfillmentInfo, + ) + uri = proto.Field( + proto.STRING, + number=22, + ) + images = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=common.Image, + ) + audience = proto.Field( + proto.MESSAGE, + number=24, + message=common.Audience, + ) + color_info = proto.Field( + proto.MESSAGE, + number=25, + message=common.ColorInfo, + ) + sizes = proto.RepeatedField( + proto.STRING, + number=26, + ) + materials = proto.RepeatedField( + proto.STRING, + number=27, + ) + patterns = proto.RepeatedField( + proto.STRING, + number=28, + ) + conditions = proto.RepeatedField( + proto.STRING, + number=29, + ) + promotions = proto.RepeatedField( + proto.MESSAGE, + number=34, + message=promotion.Promotion, + ) + publish_time = proto.Field( + proto.MESSAGE, + number=33, + message=timestamp_pb2.Timestamp, + ) + retrievable_fields = proto.Field( + proto.MESSAGE, + number=30, + message=field_mask_pb2.FieldMask, + ) + variants = proto.RepeatedField( + proto.MESSAGE, + number=31, + message='Product', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py new file mode 100644 index 00000000..ce4d5c3e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py @@ -0,0 +1,858 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'CreateProductRequest', + 'GetProductRequest', + 'UpdateProductRequest', + 'DeleteProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'SetInventoryRequest', + 'SetInventoryMetadata', + 'SetInventoryResponse', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesResponse', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesResponse', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesResponse', + }, +) + + +class CreateProductRequest(proto.Message): + r"""Request message for [CreateProduct][] method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + product (google.cloud.retail_v2.types.Product): + Required. The [Product][google.cloud.retail.v2.Product] to + create. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2.Product], which will become + the final component of the + [Product.name][google.cloud.retail.v2.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2.Product]s with the same + [parent][google.cloud.retail.v2.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + product_id = proto.Field( + proto.STRING, + number=3, + ) + + +class GetProductRequest(proto.Message): + r"""Request message for [GetProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested [Product][google.cloud.retail.v2.Product] + does not exist, a NOT_FOUND error is returned. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateProductRequest(proto.Message): + r"""Request message for [UpdateProduct][] method. + + Attributes: + product (google.cloud.retail_v2.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to update + does not exist and + [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Product][google.cloud.retail.v2.Product] to update. The + immutable and output only fields are NOT supported. If not + set, all supported fields (the fields that are neither + immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + The attribute key can be updated by setting the mask path as + "attributes.${key_name}". If a key name is present in the + mask but not in the patching product from the request, this + key will be deleted after the update. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, a + new [Product][google.cloud.retail.v2.Product] will be + created. In this situation, ``update_mask`` is ignored. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteProductRequest(proto.Message): + r"""Request message for [DeleteProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2.Product] to delete + does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2.Product] to delete can + neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] with more than one + [variants][google.cloud.retail.v2.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2.Product] will be deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProductsRequest(proto.Message): + r"""Request message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list products + under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2.Product]s under this + branch, regardless of whether or not this branch exists, a + PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of [Product][google.cloud.retail.v2.Product]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 + [ListProductsResponse.next_page_token][google.cloud.retail.v2.ListProductsResponse.next_page_token], + received from a previous + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + filter (str): + A filter to apply on the list results. Supported features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2.ListProductsRequest.filter] + is unset. + - List + [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s sharing the + same + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product]. For example: + ``primary_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2.Product]s bundled + in a + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product]. For example: + ``collection_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2.Product]s with a + partibular type. For example: ``type = "PRIMARY"`` + ``type = "VARIANT"`` ``type = "COLLECTION"`` + + If the field is unrecognizable, an INVALID_ARGUMENT error is + returned. + + If the specified + [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2.Product] or + [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2.Product] does not exist, a + NOT_FOUND error is returned. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields of [Product][google.cloud.retail.v2.Product] to + return in the responses. If not set or empty, the following + fields are returned: + + - [Product.name][google.cloud.retail.v2.Product.name] + - [Product.id][google.cloud.retail.v2.Product.id] + - [Product.title][google.cloud.retail.v2.Product.title] + - [Product.uri][google.cloud.retail.v2.Product.uri] + - [Product.images][google.cloud.retail.v2.Product.images] + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.brands][google.cloud.retail.v2.Product.brands] + + If "*" is provided, all fields are returned. + [Product.name][google.cloud.retail.v2.Product.name] is + always returned no matter what mask is set. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class ListProductsResponse(proto.Message): + r"""Response message for + [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] + method. + + Attributes: + products (Sequence[google.cloud.retail_v2.types.Product]): + The [Product][google.cloud.retail.v2.Product]s. + next_page_token (str): + A token that can be sent as + [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class SetInventoryRequest(proto.Message): + r"""Request message for [SetInventory][] method. + + Attributes: + inventory (google.cloud.retail_v2.types.Product): + Required. The inventory information to update. The allowable + fields to update are: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2.Product] named in + [Product.name][google.cloud.retail.v2.Product.name], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Product][google.cloud.retail.v2.Product] to update + does not have existing inventory information, the provided + inventory information will be inserted. + + If the [Product][google.cloud.retail.v2.Product] to update + has existing inventory information, the provided inventory + information will be merged while respecting the last update + time for each inventory field, using the provided or default + value for + [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of fulfillment + types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear in + [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types have + empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following inventory + fields: + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + - [Product.availability][google.cloud.retail.v2.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] + + If a full overwrite of inventory information while ignoring + timestamps is needed, [UpdateProduct][] should be invoked + instead. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the request is issued, used to + prevent out-of-order updates on inventory fields + with the last update time recorded. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] with name + [Product.name][google.cloud.retail.v2.Product.name] is not + found, the inventory update will still be processed and + retained for at most 1 day until the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + inventory = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + set_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + set_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=4, + ) + + +class SetInventoryMetadata(proto.Message): + r"""Metadata related to the progress of the SetInventory operation. + Currently empty because there is no meaningful metadata populated + from the [SetInventory][] method. + + """ + + +class SetInventoryResponse(proto.Message): + r"""Response of the SetInventoryRequest. Currently empty because there + is no meaningful response populated from the [SetInventory][] + method. + + """ + + +class AddFulfillmentPlacesRequest(proto.Message): + r"""Request message for + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery" to be added for this + [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type]. + Duplicate IDs will be automatically ignored. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If the total number of place IDs exceeds 2000 for this + [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type] + after adding, then the update will be rejected. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, the + fulfillment information will still be processed and retained + for at most 1 day and processed once the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + add_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class AddFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the AddFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + """ + + +class AddFulfillmentPlacesResponse(proto.Message): + r"""Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] + method. + + """ + + +class AddLocalInventoriesRequest(proto.Message): + r"""Request message for + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + local_inventories (Sequence[google.cloud.retail_v2.types.LocalInventory]): + Required. A list of inventory information at + difference places. Each place is identified by + its place ID. At most 3000 inventories are + allowed per request. + add_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided list of + [LocalInventory][google.cloud.retail.v2.LocalInventory] to + update. The field is updated to the provided value. + + If a field is set while the place does not have a previous + local inventory, the local inventory at that store is + created. + + If a field is set while the value of that field is not + provided, the original field value, if it exists, is + deleted. + + If the mask is not set or set with empty paths, all + inventory fields will be updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory updates are + issued. Used to prevent out-of-order updates on + local inventory fields. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, the + local inventory will still be processed and retained for at + most 1 day and processed once the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + local_inventories = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.LocalInventory, + ) + add_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + add_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=6, + ) + + +class AddLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the AddLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + """ + + +class AddLocalInventoriesResponse(proto.Message): + r"""Response of the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + API. Currently empty because there is no meaningful response + populated from the + [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] + method. + + """ + + +class RemoveLocalInventoriesRequest(proto.Message): + r"""Request message for [RemoveLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + place_ids (Sequence[str]): + Required. A list of place IDs to have their + inventory deleted. At most 3000 place IDs are + allowed per request. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory deletions are + issued. Used to prevent out-of-order updates and + deletions on local inventory fields. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, the + local inventory removal request will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class RemoveLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesResponse(proto.Message): + r"""Response of the [RemoveLocalInventories][] API. Currently empty + because there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + + +class RemoveFulfillmentPlacesRequest(proto.Message): + r"""Request message for [RemoveFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][google.cloud.retail.v2.FulfillmentInfo.type]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery", to be removed for this + [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type]. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2.Product] is not found, the + fulfillment information will still be processed and retained + for at most 1 day and processed once the + [Product][google.cloud.retail.v2.Product] is created. If set + to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class RemoveFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveFulfillmentPlaces][] method. + + """ + + +class RemoveFulfillmentPlacesResponse(proto.Message): + r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty + because there is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py new file mode 100644 index 00000000..e8d80a4e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'Promotion', + }, +) + + +class Promotion(proto.Message): + r"""Promotion information. + + Attributes: + promotion_id (str): + ID of the promotion. For example, "free gift". + + The value must be a UTF-8 encoded string with a length limit + of 128 characters, and match the pattern: + ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or + ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is + returned. + + Google Merchant Center property + `promotion `__. + """ + + promotion_id = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py new file mode 100644 index 00000000..b8159aa6 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + }, +) + + +class PurgeMetadata(proto.Message): + r"""Metadata related to the progress of the Purge operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + """ + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + + Attributes: + parent (str): + Required. The resource name of the catalog under which the + events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}`` + filter (str): + Required. The filter string to specify the events to be + deleted with a length limit of 5,000 characters. Empty + string filter is not allowed. The eligible fields for + filtering are: + + - ``eventType``: Double quoted + [UserEvent.event_type][google.cloud.retail.v2.UserEvent.event_type] + string. + - ``eventTime``: in ISO 8601 "zulu" format. + - ``visitorId``: Double quoted string. Specifying this will + delete all events associated with a visitor. + - ``userId``: Double quoted string. Specifying this will + delete all events associated with a user. + + Examples: + + - Deleting all events in a time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + - Deleting specific eventType in time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + - Deleting all events for a specific visitor: + ``visitorId = "visitor1024"`` + + The filtering fields are assumed to have an implicit AND. + force (bool): + Actually perform the purge. If ``force`` is set to false, + the method will return the expected purge count without + deleting any user events. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsResponse(proto.Message): + r"""Response of the PurgeUserEventsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purged_events_count (int): + The total count of events purged as a result + of the operation. + """ + + purged_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py new file mode 100644 index 00000000..e6274278 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py @@ -0,0 +1,1150 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'SearchRequest', + 'SearchResponse', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + + Attributes: + placement (str): + Required. The resource name of the search engine placement, + such as + ``projects/*/locations/global/catalogs/default_catalog/placements/default_search``. + This field is used to identify the serving configuration + name and the set of models that will be used to make the + search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + + Use "default_branch" as the branch ID or leave this field + empty, to search products under the default branch. + query (str): + Raw search query. + + If this field is empty, the request is considered a category + browsing request and returned results are based on + [filter][google.cloud.retail.v2.SearchRequest.filter] and + [page_categories][google.cloud.retail.v2.SearchRequest.page_categories]. + visitor_id (str): + Required. A unique identifier for tracking visitors. For + example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + This should be the same identifier as + [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2.types.UserInfo): + User information. + page_size (int): + Maximum number of [Product][google.cloud.retail.v2.Product]s + to return. If unspecified, defaults to a reasonable value. + The maximum allowed value is 120. Values above 120 will be + coerced to 120. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [SearchResponse.next_page_token][google.cloud.retail.v2.SearchResponse.next_page_token], + received from a previous + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Product][google.cloud.retail.v2.Product]s deemed by the API + as relevant) in search results. This field is only + considered if + [page_token][google.cloud.retail.v2.SearchRequest.page_token] + is unset. + + If this field is negative, an INVALID_ARGUMENT is returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. Filter expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + canonical_filter (str): + The default filter that is applied when a user performs a + search without checking any filters on the search page. + + The filter applied to every search request when quality + improvement such as query expansion is needed. For example, + if a query does not have enough results, an expanded query + with + [SearchRequest.canonical_filter][google.cloud.retail.v2.SearchRequest.canonical_filter] + will be returned as a supplement of the original query. This + field is strongly recommended to achieve high search + quality. + + See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] + for more details about filter syntax. + order_by (str): + The order in which products are returned. Products can be + ordered by a field in an + [Product][google.cloud.retail.v2.Product] object. Leave it + unset if ordered by relevance. OrderBy expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + facet_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + dynamic_facet_spec (google.cloud.retail_v2.types.SearchRequest.DynamicFacetSpec): + Deprecated. Refer to + https://cloud.google.com/retail/docs/configs#dynamic + to enable dynamic facets. Do not set this field. + The specification for dynamically generated + facets. Notice that only textual facets can be + dynamically generated. + boost_spec (google.cloud.retail_v2.types.SearchRequest.BoostSpec): + Boost specification to boost certain products. See more + details at this `user + guide `__. + + Notice that if both [ServingConfig.boost_control_ids][] and + [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] + are set, the boost conditions from both places are + evaluated. If a search request matches multiple boost + conditions, the final boost score is equal to the sum of the + boost scores from all matched boost conditions. + query_expansion_spec (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that specifies the + conditions under which query expansion will occur. See more + details at this `user + guide `__. + variant_rollup_keys (Sequence[str]): + The keys to fetch and rollup the matching + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s attributes, + [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo] or + [LocalInventory][google.cloud.retail.v2.LocalInventory]s + attributes. The attributes from all the matching + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s or + [LocalInventory][google.cloud.retail.v2.LocalInventory]s are + merged and de-duplicated. Notice that rollup attributes will + lead to extra query latency. Maximum number of keys is 30. + + For + [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], a + fulfillment type and a fulfillment ID must be provided in + the format of "fulfillmentType.fulfillmentId". E.g., in + "pickupInStore.store123", "pickupInStore" is fulfillment + type and "store123" is the store ID. + + Supported keys are: + + - colorFamilies + - price + - originalPrice + - discount + - variantId + - inventory(place_id,price) + - inventory(place_id,original_price) + - inventory(place_id,attributes.key), where key is any key + in the + [Product.local_inventories.attributes][google.cloud.retail.v2.LocalInventory.attributes] + map. + - attributes.key, where key is any key in the + [Product.attributes][google.cloud.retail.v2.Product.attributes] + map. + - pickupInStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "pickup-in-store". + - shipToStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "ship-to-store". + - sameDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "same-day-delivery". + - nextDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "next-day-delivery". + - customFulfillment1.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-1". + - customFulfillment2.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-2". + - customFulfillment3.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-3". + - customFulfillment4.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-4". + - customFulfillment5.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] + "custom-type-5". + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. Required for + category navigation queries to achieve good search quality. + The format should be the same as + [UserEvent.page_categories][google.cloud.retail.v2.UserEvent.page_categories]; + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + search_mode (google.cloud.retail_v2.types.SearchRequest.SearchMode): + The search mode of the search request. If not + specified, a single search request triggers both + product search and faceted search. + personalization_spec (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec): + The specification for personalization. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + spell_correction_spec (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec): + The spell correction specification that + specifies the mode under which spell correction + will take effect. + + This field is a member of `oneof`_ ``_spell_correction_spec``. + """ + class SearchMode(proto.Enum): + r"""The search mode of each search request.""" + SEARCH_MODE_UNSPECIFIED = 0 + PRODUCT_SEARCH_ONLY = 1 + FACETED_SEARCH_ONLY = 2 + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.retail_v2.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum of facet values that should be returned for this + facet. If unspecified, defaults to 20. The maximum allowed + value is 300. Values above 300 will be coerced to 300. + + If this field is negative, an INVALID_ARGUMENT is returned. + excluded_filter_keys (Sequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + Listing a facet key in this field allows its values to + appear as facet results, even when they are filtered out of + search results. Using this field does not affect what search + results are returned. + + For example, suppose there are 100 products with the color + facet "Red" and 200 products with the color facet "Blue". A + query containing the filter "colorFamilies:ANY("Red")" and + having "colorFamilies" as + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + would by default return only "Red" products in the search + results, and also return "Red" with count 100 as the only + color facet. Although there are also blue products + available, "Blue" would not be shown as an available facet + value. + + If "colorFamilies" is listed in "excludedFilterKeys", then + the query returns the facet values "Red" with count 100 and + "Blue" with count 200, because the "colorFamilies" key is + now excluded from the filter. Because this field doesn't + affect search results, the search results are still + correctly filtered to return only "Red" products. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined by Google Retail Search. It will be ordered + together with dynamic facets if dynamic facets is enabled. + If set to false, the position of this facet in the response + will be the same as in the request, and it will be ranked + before the facets with dynamic position enable and all + dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response will be determined by Google Retail + Search. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enable, which will + generate a facet 'gender'. Then the final order of the + facets in the response can be ("price", "brands", "rating", + "gender") or ("price", "brands", "gender", "rating") depends + on how Google Retail Search orders "gender" and "rating" + facets. However, notice that "price" and "brands" will + always be ranked at 1st and 2nd position since their + enable_dynamic_position are false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Product][google.cloud.retail.v2.Product] object, over which + the facet values are computed. Facet key is case-sensitive. + + Allowed facet keys when + [FacetKey.query][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.query] + is not specified: + + - textual_field = + + - "brands" + - "categories" + - "genders" + - "ageGroups" + - "availability" + - "colorFamilies" + - "colors" + - "sizes" + - "materials" + - "patterns" + - "conditions" + - "attributes.key" + - "pickupInStore" + - "shipToStore" + - "sameDayDelivery" + - "nextDayDelivery" + - "customFulfillment1" + - "customFulfillment2" + - "customFulfillment3" + - "customFulfillment4" + - "customFulfillment5" + - "inventory(place_id,attributes.key)" + + - numerical_field = + + - "price" + - "discount" + - "rating" + - "ratingCount" + - "attributes.key" + - "inventory(place_id,price)" + - "inventory(place_id,original_price)" + - "inventory(place_id,attributes.key)". + intervals (Sequence[google.cloud.retail_v2.types.Interval]): + Set only if values should be bucketized into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (Sequence[str]): + Only get facet for the given restricted values. For example, + when using "pickupInStore" as key and set restricted values + to ["store123", "store456"], only facets for "store123" and + "store456" are returned. Only supported on predefined + textual fields, custom textual attributes and fulfillments. + Maximum is 20. + + Must be set for the fulfillment facet keys: + + - pickupInStore + + - shipToStore + + - sameDayDelivery + + - nextDayDelivery + + - customFulfillment1 + + - customFulfillment2 + + - customFulfillment3 + + - customFulfillment4 + + - customFulfillment5 + prefixes (Sequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "categories" has three values "Women > Shoe", + "Women > Dress" and "Men > Shoe". If set + "prefixes" to "Women", the "categories" facet + will give only "Women > Shoe" and "Women > + Dress". Only supported on textual fields. + Maximum is 10. + contains (Sequence[str]): + Only get facet values that contains the given + strings. For example, suppose "categories" has + three values "Women > Shoe", "Women > Dress" and + "Men > Shoe". If set "contains" to "Shoe", the + "categories" facet will give only "Women > Shoe" + and "Men > Shoe". Only supported on textual + fields. Maximum is 10. + order_by (str): + The order in which [Facet.values][] are returned. + + Allowed values are: + + - "count desc", which means order by + [Facet.FacetValue.count][] descending. + + - "value desc", which means order by + [Facet.FacetValue.value][] descending. Only applies to + textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.intervals]; + [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] + are sorted in the order given by + [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.restricted_values]. + query (str): + The query that is used to compute facet for the given facet + key. When provided, it will override the default behavior of + facet computation. The query syntax is the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] + for detail syntax and limitations. Notice that there is no + limitation on + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + when query is specified. + + In the response, [FacetValue.value][] will be always "1" and + [FacetValue.count][] will be the number of results that + matches the query. + + For example, you can set a customized facet for + "shipToStore", where + [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] + is "customizedShipToStore", and + [FacetKey.query][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.query] + is "availability: ANY("IN_STOCK") AND shipToStore: + ANY("123")". Then the facet will count the products that are + both in stock and ship to store "123". + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + intervals = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes = proto.RepeatedField( + proto.STRING, + number=8, + ) + contains = proto.RepeatedField( + proto.STRING, + number=9, + ) + order_by = proto.Field( + proto.STRING, + number=4, + ) + query = proto.Field( + proto.STRING, + number=5, + ) + + facet_key = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.FacetSpec.FacetKey', + ) + limit = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position = proto.Field( + proto.BOOL, + number=4, + ) + + class DynamicFacetSpec(proto.Message): + r"""The specifications of dynamically generated facets. + + Attributes: + mode (google.cloud.retail_v2.types.SearchRequest.DynamicFacetSpec.Mode): + Mode of the DynamicFacet feature. Defaults to + [Mode.DISABLED][google.cloud.retail.v2.SearchRequest.DynamicFacetSpec.Mode.DISABLED] + if it's unset. + """ + class Mode(proto.Enum): + r"""Enum to control DynamicFacet mode""" + MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.DynamicFacetSpec.Mode', + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain items. + + Attributes: + condition_boost_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a product + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 20. + skip_boost_spec_validation (bool): + Whether to skip boostspec validation. If this field is set + to true, invalid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] + will be ignored and valid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] + will still be applied. + + This field is a member of `oneof`_ ``_skip_boost_spec_validation``. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to products which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": + + - (id: ANY("product_1", "product_2")) AND + (colorFamilies: ANY("Red","Blue")) + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition = proto.Field( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + skip_boost_spec_validation = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.retail.v2.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 3 + + condition = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.QueryExpansionSpec.Condition', + ) + pin_unexpanded_results = proto.Field( + proto.BOOL, + number=2, + ) + + class PersonalizationSpec(proto.Message): + r"""The specification for personalization. + + Attributes: + mode (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec.Mode): + Defaults to + [Mode.AUTO][google.cloud.retail.v2.SearchRequest.PersonalizationSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""The personalization mode of each search request.""" + MODE_UNSPECIFIED = 0 + AUTO = 1 + DISABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.PersonalizationSpec.Mode', + ) + + class SpellCorrectionSpec(proto.Message): + r"""The specification for query spell correction. + + Attributes: + mode (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec.Mode): + The mode under which spell correction should take effect to + replace the original search query. Default to + [Mode.AUTO][google.cloud.retail.v2.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""Enum describing under which mode spell correction should + occur. + """ + MODE_UNSPECIFIED = 0 + SUGGESTION_ONLY = 1 + AUTO = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.SpellCorrectionSpec.Mode', + ) + + placement = proto.Field( + proto.STRING, + number=1, + ) + branch = proto.Field( + proto.STRING, + number=2, + ) + query = proto.Field( + proto.STRING, + number=3, + ) + visitor_id = proto.Field( + proto.STRING, + number=4, + ) + user_info = proto.Field( + proto.MESSAGE, + number=5, + message=common.UserInfo, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + offset = proto.Field( + proto.INT32, + number=9, + ) + filter = proto.Field( + proto.STRING, + number=10, + ) + canonical_filter = proto.Field( + proto.STRING, + number=28, + ) + order_by = proto.Field( + proto.STRING, + number=11, + ) + facet_specs = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=FacetSpec, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=21, + message=DynamicFacetSpec, + ) + boost_spec = proto.Field( + proto.MESSAGE, + number=13, + message=BoostSpec, + ) + query_expansion_spec = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionSpec, + ) + variant_rollup_keys = proto.RepeatedField( + proto.STRING, + number=17, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=23, + ) + search_mode = proto.Field( + proto.ENUM, + number=31, + enum=SearchMode, + ) + personalization_spec = proto.Field( + proto.MESSAGE, + number=32, + message=PersonalizationSpec, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=34, + ) + spell_correction_spec = proto.Field( + proto.MESSAGE, + number=35, + optional=True, + message=SpellCorrectionSpec, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.retail.v2.SearchService.Search] + method. + + Attributes: + results (Sequence[google.cloud.retail_v2.types.SearchResponse.SearchResult]): + A list of matched items. The order represents + the ranking. + facets (Sequence[google.cloud.retail_v2.types.SearchResponse.Facet]): + Results of facets requested by user. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.retail.v2.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.retail.v2.SearchResponse.total_size] + that matches. + corrected_query (str): + Contains the spell corrected query, if found. If the spell + correction type is AUTOMATIC, then the search results are + based on corrected_query. Otherwise the original query will + be used for search. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting + from this search, which enables accurate attribution of + search model performance. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.retail.v2.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + query_expansion_info (google.cloud.retail_v2.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search is performed, and only + [redirect_uri][google.cloud.retail.v2.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] + are set in the response. + applied_controls (Sequence[str]): + The fully qualified resource name of applied + `controls `__. + invalid_condition_boost_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + The invalid + [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] + that are not applied during serving. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Product.id][google.cloud.retail.v2.Product.id] of the + searched [Product][google.cloud.retail.v2.Product]. + product (google.cloud.retail_v2.types.Product): + The product data snippet in the search response. Only + [Product.name][google.cloud.retail.v2.Product.name] is + guaranteed to be populated. + + [Product.variants][google.cloud.retail.v2.Product.variants] + contains the product variants that match the search query. + If there are multiple product variants matching the query, + top 5 most relevant product variants are returned and + ordered by relevancy. + + If relevancy can be deternmined, use + [matching_variant_fields][google.cloud.retail.v2.SearchResponse.SearchResult.matching_variant_fields] + to look up matched product variants fields. If relevancy + cannot be determined, e.g. when searching "shoe" all + products in a shoe product can be a match, 5 product + variants are returned but order is meaningless. + matching_variant_count (int): + The count of matched + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product]s. + matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): + If a [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] matches the search + query, this map indicates which + [Product][google.cloud.retail.v2.Product] fields are + matched. The key is the + [Product.name][google.cloud.retail.v2.Product.name], the + value is a field mask of the matched + [Product][google.cloud.retail.v2.Product] fields. If matched + attributes cannot be determined, this map will be empty. + + For example, a key "sku1" with field mask + "products.color_info" indicates there is a match between + "sku1" [ColorInfo][google.cloud.retail.v2.ColorInfo] and the + query. + variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): + The rollup matching + [variant][google.cloud.retail.v2.Product.Type.VARIANT] + [Product][google.cloud.retail.v2.Product] attributes. The + key is one of the + [SearchRequest.variant_rollup_keys][google.cloud.retail.v2.SearchRequest.variant_rollup_keys]. + The values are the merged and de-duplicated + [Product][google.cloud.retail.v2.Product] attributes. Notice + that the rollup values are respect filter. For example, when + filtering by "colorFamilies:ANY("red")" and rollup + "colorFamilies", only "red" is returned. + + For textual and numerical attributes, the rollup values is a + list of string or double values with type + [google.protobuf.ListValue][google.protobuf.ListValue]. For + example, if there are two variants with colors "red" and + "blue", the rollup values are + + :: + + { key: "colorFamilies" + value { + list_value { + values { string_value: "red" } + values { string_value: "blue" } + } + } + } + + For + [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], + the rollup values is a double value with type + [google.protobuf.Value][google.protobuf.Value]. For example, + ``{key: "pickupInStore.store1" value { number_value: 10 }}`` + means a there are 10 variants in this product are available + in the store "store1". + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + matching_variant_count = proto.Field( + proto.INT32, + number=3, + ) + matching_variant_fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + variant_rollup_values = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. E.g., "colorFamilies" + or "price" or "attributes.attr1". + values (Sequence[google.cloud.retail_v2.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Text value of a facet, such as "Black" for + facet "colorFamilies". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.retail_v2.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value = proto.Field( + proto.STRING, + number=1, + oneof='facet_value', + ) + interval = proto.Field( + proto.MESSAGE, + number=2, + oneof='facet_value', + message=common.Interval, + ) + count = proto.Field( + proto.INT64, + number=3, + ) + + key = proto.Field( + proto.STRING, + number=1, + ) + values = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SearchResponse.Facet.FacetValue', + ) + dynamic_facet = proto.Field( + proto.BOOL, + number=3, + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count = proto.Field( + proto.INT64, + number=2, + ) + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + corrected_query = proto.Field( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + next_page_token = proto.Field( + proto.STRING, + number=6, + ) + query_expansion_info = proto.Field( + proto.MESSAGE, + number=7, + message=QueryExpansionInfo, + ) + redirect_uri = proto.Field( + proto.STRING, + number=10, + ) + applied_controls = proto.RepeatedField( + proto.STRING, + number=12, + ) + invalid_condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py new file mode 100644 index 00000000..0d6b6823 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py @@ -0,0 +1,508 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import product as gcr_product +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'UserEvent', + 'ProductDetail', + 'CompletionDetail', + 'PurchaseTransaction', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Retail API needs + to know about how end users interact with customers' website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + - ``add-to-cart``: Products being added to cart. + - ``category-page-view``: Special pages such as sale or + promotion pages viewed. + - ``detail-page-view``: Products detail page viewed. + - ``home-page-view``: Homepage viewed. + - ``promotion-offered``: Promotion is offered to a user. + - ``promotion-not-offered``: Promotion is not offered to a + user. + - ``purchase-complete``: User finishing a purchase. + - ``search``: Product search. + - ``shopping-cart-page-view``: User viewing a shopping + cart. + visitor_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + Don't set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + The field should not contain PII or user-data. We recommend + to use Google Analytics `Client + ID `__ + for this field. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the sesion_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add visitor_id as prefix. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.retail.v2.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + experiment_ids (Sequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups + (e.g. using Retail API, using different + recommendation models). + attribution_token (str): + Highly recommended for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]. + This field enables accurate attribution of recommendation + model performance. + + The value must be a valid + [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] + for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]. + The value must be a valid + [SearchResponse.attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] + for user events that are the result of + [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. + + This token enables us to accurately attribute page view or + purchase back to the event and the particular predict + response containing this clicked/purchased product. If user + clicks on product K in the recommendation results, pass + [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] + as a URL parameter to product K's page. When recording + events on product K's page, log the + [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] + to this field. + product_details (Sequence[google.cloud.retail_v2.types.ProductDetail]): + The main product details related to the event. + + This field is optional except for the following event types: + + - ``add-to-cart`` + - ``detail-page-view`` + - ``purchase-complete`` + + In a ``search`` event, this field represents the products + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [product_details][google.cloud.retail.v2.UserEvent.product_details] + is desired. The end user may have not finished browsing the + whole page yet. + completion_detail (google.cloud.retail_v2.types.CompletionDetail): + The main auto-completion details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Retail API use those + custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - The key must be a UTF-8 encoded string with a length + limit of 5,000 characters. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a UTF-8 + encoded string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is traffic_channel, which is how a user arrives + at the site. Users can arrive at the site by coming to the + site directly, coming through Google search, or in other + ways. + cart_id (str): + The ID or name of the associated shopping cart. This ID is + used to associate multiple items added or present in the + cart before purchase. + + This can only be set for ``add-to-cart``, + ``purchase-complete``, or ``shopping-cart-page-view`` + events. + purchase_transaction (google.cloud.retail_v2.types.PurchaseTransaction): + A transaction represents the entire purchase transaction. + + Required for ``purchase-complete`` events. Other event types + should not set this field. Otherwise, an INVALID_ARGUMENT + error is returned. + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.retail.v2.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + At least one of + [search_query][google.cloud.retail.v2.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. + + See + [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + order_by (str): + The order in which products are returned. + + See + [SearchRequest.order_by][google.cloud.retail.v2.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.retail.v2.SearchRequest.offset] + for definition. + + If this field is negative, an INVALID_ARGUMENT is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + + Required for ``category-page-view`` events. At least one of + [search_query][google.cloud.retail.v2.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2.types.UserInfo): + User information. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. + page_view_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageViewId`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + """ + + event_type = proto.Field( + proto.STRING, + number=1, + ) + visitor_id = proto.Field( + proto.STRING, + number=2, + ) + session_id = proto.Field( + proto.STRING, + number=21, + ) + event_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + experiment_ids = proto.RepeatedField( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + product_details = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ProductDetail', + ) + completion_detail = proto.Field( + proto.MESSAGE, + number=22, + message='CompletionDetail', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=common.CustomAttribute, + ) + cart_id = proto.Field( + proto.STRING, + number=8, + ) + purchase_transaction = proto.Field( + proto.MESSAGE, + number=9, + message='PurchaseTransaction', + ) + search_query = proto.Field( + proto.STRING, + number=10, + ) + filter = proto.Field( + proto.STRING, + number=16, + ) + order_by = proto.Field( + proto.STRING, + number=17, + ) + offset = proto.Field( + proto.INT32, + number=18, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=11, + ) + user_info = proto.Field( + proto.MESSAGE, + number=12, + message=common.UserInfo, + ) + uri = proto.Field( + proto.STRING, + number=13, + ) + referrer_uri = proto.Field( + proto.STRING, + number=14, + ) + page_view_id = proto.Field( + proto.STRING, + number=15, + ) + + +class ProductDetail(proto.Message): + r"""Detailed product information associated with a user event. + + Attributes: + product (google.cloud.retail_v2.types.Product): + Required. [Product][google.cloud.retail.v2.Product] + information. + + Required field(s): + + - [Product.id][google.cloud.retail.v2.Product.id] + + Optional override field(s): + + - [Product.price_info][google.cloud.retail.v2.Product.price_info] + + If any supported optional fields are provided, we will treat + them as a full override when looking up product information + from the catalog. Thus, it is important to ensure that the + overriding fields are accurate and complete. + + All other product fields are ignored and instead populated + via catalog lookup after event ingestion. + quantity (google.protobuf.wrappers_pb2.Int32Value): + Quantity of the product associated with the user event. + + For example, this field will be 2 if two products are added + to the shopping cart for ``purchase-complete`` event. + Required for ``add-to-cart`` and ``purchase-complete`` event + types. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + quantity = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +class CompletionDetail(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + completion_attribution_token (str): + Completion attribution token in + [CompleteQueryResponse.attribution_token][google.cloud.retail.v2.CompleteQueryResponse.attribution_token]. + selected_suggestion (str): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2.CompleteQueryResponse.CompletionResult.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2.CompleteQueryResponse.CompletionResult.suggestion] + position, starting from 0. + """ + + completion_attribution_token = proto.Field( + proto.STRING, + number=1, + ) + selected_suggestion = proto.Field( + proto.STRING, + number=2, + ) + selected_position = proto.Field( + proto.INT32, + number=3, + ) + + +class PurchaseTransaction(proto.Message): + r"""A transaction represents the entire purchase transaction. + + Attributes: + id (str): + The transaction ID with a length limit of 128 + characters. + revenue (float): + Required. Total non-zero revenue or grand + total associated with the transaction. This + value include shipping, tax, or other + adjustments to total revenue that you want to + include as part of your revenue calculations. + tax (float): + All the taxes associated with the + transaction. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [revenue][google.cloud.retail.v2.PurchaseTransaction.revenue] + - [tax][google.cloud.retail.v2.PurchaseTransaction.tax] - + [cost][google.cloud.retail.v2.PurchaseTransaction.cost] + currency_code (str): + Required. Currency code. Use three-character + ISO-4217 code. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + revenue = proto.Field( + proto.FLOAT, + number=2, + ) + tax = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + currency_code = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py new file mode 100644 index 00000000..fcfc46d7 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2.types import user_event as gcr_user_event + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2', + manifest={ + 'WriteUserEventRequest', + 'CollectUserEventRequest', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'RejoinUserEventsMetadata', + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (google.cloud.retail_v2.types.UserEvent): + Required. User event to write. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for 3rd party requests. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.STRING, + number=2, + ) + uri = proto.Field( + proto.STRING, + number=3, + ) + ets = proto.Field( + proto.INT64, + number=4, + ) + + +class RejoinUserEventsRequest(proto.Message): + r"""Request message for RejoinUserEvents method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event_rejoin_scope (google.cloud.retail_v2.types.RejoinUserEventsRequest.UserEventRejoinScope): + The type of the user event rejoin to define the scope and + range of the user events to be rejoined with the latest + product catalog. Defaults to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not + set, or set to an invalid integer value. + """ + class UserEventRejoinScope(proto.Enum): + r"""The scope of user events to be rejoined with the latest product + catalog. If the rejoining aims at reducing number of unjoined + events, set UserEventRejoinScope to UNJOINED_EVENTS. If the + rejoining aims at correcting product catalog information in joined + events, set UserEventRejoinScope to JOINED_EVENTS. If all events + needs to be rejoined, set UserEventRejoinScope to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. + """ + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 + JOINED_EVENTS = 1 + UNJOINED_EVENTS = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event_rejoin_scope = proto.Field( + proto.ENUM, + number=2, + enum=UserEventRejoinScope, + ) + + +class RejoinUserEventsResponse(proto.Message): + r"""Response message for RejoinUserEvents method. + + Attributes: + rejoined_user_events_count (int): + Number of user events that were joined with + latest product catalog. + """ + + rejoined_user_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +class RejoinUserEventsMetadata(proto.Message): + r"""Metadata for RejoinUserEvents method. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py new file mode 100644 index 00000000..e7ab4118 --- /dev/null +++ b/owl-bot-staging/v2/noxfile.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.6", + "3.7", + "3.8", + "3.9", + "3.10", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==19.10b0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.9" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/retail_v2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py new file mode 100644 index 00000000..fb30eae6 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_GetDefaultBranch_async] +from google.cloud import retail_v2 + + +async def sample_get_default_branch(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py new file mode 100644 index 00000000..0af0ece9 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_GetDefaultBranch_sync] +from google.cloud import retail_v2 + + +def sample_get_default_branch(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py new file mode 100644 index 00000000..2a0930de --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_ListCatalogs_async] +from google.cloud import retail_v2 + + +async def sample_list_catalogs(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py new file mode 100644 index 00000000..2671a121 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_ListCatalogs_sync] +from google.cloud import retail_v2 + + +def sample_list_catalogs(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py new file mode 100644 index 00000000..f85e3ed8 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_SetDefaultBranch_async] +from google.cloud import retail_v2 + + +async def sample_set_default_branch(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + +# [END retail_v2_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py new file mode 100644 index 00000000..34371062 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_SetDefaultBranch_sync] +from google.cloud import retail_v2 + + +def sample_set_default_branch(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + +# [END retail_v2_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py new file mode 100644 index 00000000..2a2b3dde --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_UpdateCatalog_async] +from google.cloud import retail_v2 + + +async def sample_update_catalog(): + # Create a client + client = retail_v2.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py new file mode 100644 index 00000000..bf721cba --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CatalogService_UpdateCatalog_sync] +from google.cloud import retail_v2 + + +def sample_update_catalog(): + # Create a client + client = retail_v2.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py new file mode 100644 index 00000000..c72ecfdf --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CompletionService_CompleteQuery_async] +from google.cloud import retail_v2 + + +async def sample_complete_query(): + # Create a client + client = retail_v2.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py new file mode 100644 index 00000000..30b10016 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CompletionService_CompleteQuery_sync] +from google.cloud import retail_v2 + + +def sample_complete_query(): + # Create a client + client = retail_v2.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py new file mode 100644 index 00000000..75f45f91 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CompletionService_ImportCompletionData_async] +from google.cloud import retail_v2 + + +async def sample_import_completion_data(): + # Create a client + client = retail_v2.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py new file mode 100644 index 00000000..cc31057e --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_CompletionService_ImportCompletionData_sync] +from google.cloud import retail_v2 + + +def sample_import_completion_data(): + # Create a client + client = retail_v2.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py new file mode 100644 index 00000000..f46819c5 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_PredictionService_Predict_async] +from google.cloud import retail_v2 + + +async def sample_predict(): + # Create a client + client = retail_v2.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py new file mode 100644 index 00000000..ad37063f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_PredictionService_Predict_sync] +from google.cloud import retail_v2 + + +def sample_predict(): + # Create a client + client = retail_v2.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py new file mode 100644 index 00000000..ceea2869 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_AddFulfillmentPlaces_async] +from google.cloud import retail_v2 + + +async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py new file mode 100644 index 00000000..1739ec91 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_AddFulfillmentPlaces_sync] +from google.cloud import retail_v2 + + +def sample_add_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py new file mode 100644 index 00000000..6155d5ce --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_AddLocalInventories_async] +from google.cloud import retail_v2 + + +async def sample_add_local_inventories(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py new file mode 100644 index 00000000..b57dce2f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_AddLocalInventories_sync] +from google.cloud import retail_v2 + + +def sample_add_local_inventories(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py new file mode 100644 index 00000000..fe1cb991 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_CreateProduct_async] +from google.cloud import retail_v2 + + +async def sample_create_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py new file mode 100644 index 00000000..9cc154d9 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_CreateProduct_sync] +from google.cloud import retail_v2 + + +def sample_create_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py new file mode 100644 index 00000000..33318da7 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_DeleteProduct_async] +from google.cloud import retail_v2 + + +async def sample_delete_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + +# [END retail_v2_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py new file mode 100644 index 00000000..797690c6 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_DeleteProduct_sync] +from google.cloud import retail_v2 + + +def sample_delete_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + +# [END retail_v2_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py new file mode 100644 index 00000000..32ba279d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_GetProduct_async] +from google.cloud import retail_v2 + + +async def sample_get_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py new file mode 100644 index 00000000..62805768 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_GetProduct_sync] +from google.cloud import retail_v2 + + +def sample_get_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py new file mode 100644 index 00000000..390f0977 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_ImportProducts_async] +from google.cloud import retail_v2 + + +async def sample_import_products(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py new file mode 100644 index 00000000..fcd8c82f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_ImportProducts_sync] +from google.cloud import retail_v2 + + +def sample_import_products(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py new file mode 100644 index 00000000..5e85f948 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_ListProducts_async] +from google.cloud import retail_v2 + + +async def sample_list_products(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py new file mode 100644 index 00000000..30f7fd1f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_ListProducts_sync] +from google.cloud import retail_v2 + + +def sample_list_products(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py new file mode 100644 index 00000000..08172bf4 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async] +from google.cloud import retail_v2 + + +async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py new file mode 100644 index 00000000..37f86ba9 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync] +from google.cloud import retail_v2 + + +def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py new file mode 100644 index 00000000..762dab6d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_RemoveLocalInventories_async] +from google.cloud import retail_v2 + + +async def sample_remove_local_inventories(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py new file mode 100644 index 00000000..7aa52d5d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_RemoveLocalInventories_sync] +from google.cloud import retail_v2 + + +def sample_remove_local_inventories(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py new file mode 100644 index 00000000..62a24100 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_SetInventory_async] +from google.cloud import retail_v2 + + +async def sample_set_inventory(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2.Product() + inventory.title = "title_value" + + request = retail_v2.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py new file mode 100644 index 00000000..aa5a0539 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_SetInventory_sync] +from google.cloud import retail_v2 + + +def sample_set_inventory(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2.Product() + inventory.title = "title_value" + + request = retail_v2.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py new file mode 100644 index 00000000..9ea76295 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_UpdateProduct_async] +from google.cloud import retail_v2 + + +async def sample_update_product(): + # Create a client + client = retail_v2.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py new file mode 100644 index 00000000..866c7e7c --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_ProductService_UpdateProduct_sync] +from google.cloud import retail_v2 + + +def sample_update_product(): + # Create a client + client = retail_v2.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2.Product() + product.title = "title_value" + + request = retail_v2.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py new file mode 100644 index 00000000..ddebd9e8 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_SearchService_Search_async] +from google.cloud import retail_v2 + + +async def sample_search(): + # Create a client + client = retail_v2.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py new file mode 100644 index 00000000..fc20bb3d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_SearchService_Search_sync] +from google.cloud import retail_v2 + + +def sample_search(): + # Create a client + client = retail_v2.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 00000000..b8bb6a81 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_CollectUserEvent_async] +from google.cloud import retail_v2 + + +async def sample_collect_user_event(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 00000000..10b302e3 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_CollectUserEvent_sync] +from google.cloud import retail_v2 + + +def sample_collect_user_event(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py new file mode 100644 index 00000000..55ad399a --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_ImportUserEvents_async] +from google.cloud import retail_v2 + + +async def sample_import_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 00000000..835edec6 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_ImportUserEvents_sync] +from google.cloud import retail_v2 + + +def sample_import_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py new file mode 100644 index 00000000..1da1d39d --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_PurgeUserEvents_async] +from google.cloud import retail_v2 + + +async def sample_purge_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py new file mode 100644 index 00000000..48814171 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_PurgeUserEvents_sync] +from google.cloud import retail_v2 + + +def sample_purge_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py new file mode 100644 index 00000000..a2617cfe --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_RejoinUserEvents_async] +from google.cloud import retail_v2 + + +async def sample_rejoin_user_events(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py new file mode 100644 index 00000000..eb8ed62c --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_RejoinUserEvents_sync] +from google.cloud import retail_v2 + + +def sample_rejoin_user_events(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py new file mode 100644 index 00000000..82afc25a --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_WriteUserEvent_async] +from google.cloud import retail_v2 + + +async def sample_write_user_event(): + # Create a client + client = retail_v2.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 00000000..62336b25 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2_generated_UserEventService_WriteUserEvent_sync] +from google.cloud import retail_v2 + + +def sample_write_user_event(): + # Create a client + client = retail_v2.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json new file mode 100644 index 00000000..c6a55bd4 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json @@ -0,0 +1,3826 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.retail.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-cloud-retail" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2_generated_catalog_service_get_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_GetDefaultBranch_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_get_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2_generated_catalog_service_get_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_GetDefaultBranch_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_get_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ListCatalogsRequest" + }, + { + "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.retail_v2.services.catalog_service.pagers.ListCatalogsAsyncPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2_generated_catalog_service_list_catalogs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_ListCatalogs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_list_catalogs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ListCatalogsRequest" + }, + { + "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.retail_v2.services.catalog_service.pagers.ListCatalogsPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2_generated_catalog_service_list_catalogs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_ListCatalogs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_list_catalogs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2_generated_catalog_service_set_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_SetDefaultBranch_async", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_set_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2_generated_catalog_service_set_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_SetDefaultBranch_sync", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_set_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2.types.Catalog" + }, + { + "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.retail_v2.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2_generated_catalog_service_update_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_UpdateCatalog_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_update_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2.CatalogServiceClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2.types.Catalog" + }, + { + "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.retail_v2.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2_generated_catalog_service_update_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CatalogService_UpdateCatalog_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_catalog_service_update_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2_generated_completion_service_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CompletionService_CompleteQuery_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_completion_service_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2.CompletionServiceClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2_generated_completion_service_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CompletionService_CompleteQuery_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_completion_service_complete_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2_generated_completion_service_import_completion_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CompletionService_ImportCompletionData_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_completion_service_import_completion_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2.CompletionServiceClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2_generated_completion_service_import_completion_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_CompletionService_ImportCompletionData_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_completion_service_import_completion_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.PredictionServiceAsyncClient", + "shortName": "PredictionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.PredictionServiceAsyncClient.predict", + "method": { + "fullName": "google.cloud.retail.v2.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2_generated_prediction_service_predict_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_PredictionService_Predict_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_prediction_service_predict_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.PredictionServiceClient", + "shortName": "PredictionServiceClient" + }, + "fullName": "google.cloud.retail_v2.PredictionServiceClient.predict", + "method": { + "fullName": "google.cloud.retail.v2.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2_generated_prediction_service_predict_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_PredictionService_Predict_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_prediction_service_predict_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2_generated_product_service_add_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_AddFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_add_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2_generated_product_service_add_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_AddFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_add_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2_generated_product_service_add_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_AddLocalInventories_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_add_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2_generated_product_service_add_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_AddLocalInventories_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_add_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "name": "product_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.retail_v2.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2_generated_product_service_create_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_CreateProduct_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_create_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "name": "product_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.retail_v2.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2_generated_product_service_create_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_CreateProduct_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_create_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2_generated_product_service_delete_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_DeleteProduct_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_delete_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2_generated_product_service_delete_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_DeleteProduct_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_delete_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.GetProductRequest" + }, + { + "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.retail_v2.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2_generated_product_service_get_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_GetProduct_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_get_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.GetProductRequest" + }, + { + "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.retail_v2.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2_generated_product_service_get_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_GetProduct_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_get_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2_generated_product_service_import_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_ImportProducts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_import_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2_generated_product_service_import_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_ImportProducts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_import_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ListProductsRequest" + }, + { + "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.retail_v2.services.product_service.pagers.ListProductsAsyncPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2_generated_product_service_list_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_ListProducts_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_list_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ListProductsRequest" + }, + { + "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.retail_v2.services.product_service.pagers.ListProductsPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2_generated_product_service_list_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_ListProducts_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_list_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2_generated_product_service_remove_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_remove_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2_generated_product_service_remove_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_remove_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2_generated_product_service_remove_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_RemoveLocalInventories_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_remove_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2_generated_product_service_remove_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_RemoveLocalInventories_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_remove_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2_generated_product_service_set_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_SetInventory_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_set_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2_generated_product_service_set_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_SetInventory_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_set_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "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.retail_v2.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2_generated_product_service_update_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_UpdateProduct_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_update_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2.ProductServiceClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2.types.Product" + }, + { + "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.retail_v2.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2_generated_product_service_update_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_ProductService_UpdateProduct_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_product_service_update_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.SearchServiceAsyncClient.search", + "method": { + "fullName": "google.cloud.retail.v2.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2_generated_search_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_SearchService_Search_async", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_search_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.SearchServiceClient", + "shortName": "SearchServiceClient" + }, + "fullName": "google.cloud.retail_v2.SearchServiceClient.search", + "method": { + "fullName": "google.cloud.retail.v2.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.services.search_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2_generated_search_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_SearchService_Search_sync", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_search_service_search_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_CollectUserEvent_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_CollectUserEvent_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_ImportUserEvents_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_ImportUserEvents_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2_generated_user_event_service_purge_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_PurgeUserEvents_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_purge_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2_generated_user_event_service_purge_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_PurgeUserEvents_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_purge_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2_generated_user_event_service_rejoin_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_RejoinUserEvents_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_rejoin_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2_generated_user_event_service_rejoin_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_RejoinUserEvents_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_rejoin_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_WriteUserEvent_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2_generated_UserEventService_WriteUserEvent_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py new file mode 100644 index 00000000..9ed9d278 --- /dev/null +++ b/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py @@ -0,0 +1,199 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class retailCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), + 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'delete_product': ('name', ), + 'get_default_branch': ('catalog', ), + 'get_product': ('name', ), + 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), + 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), + 'import_user_events': ('parent', 'input_config', 'errors_config', ), + 'list_catalogs': ('parent', 'page_size', 'page_token', ), + 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', ), + 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), + 'purge_user_events': ('parent', 'filter', 'force', ), + 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), + 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), + 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), + 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', 'labels', 'spell_correction_spec', ), + 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), + 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), + 'update_catalog': ('catalog', 'update_mask', ), + 'update_product': ('product', 'update_mask', 'allow_missing', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=retailCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the retail client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2/setup.py b/owl-bot-staging/v2/setup.py new file mode 100644 index 00000000..1103510b --- /dev/null +++ b/owl-bot-staging/v2/setup.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-retail', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-retail", + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 2.8.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'googleapis-common-protos >= 1.55.0, <2.0.0dev', + 'proto-plus >= 1.19.7', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py new file mode 100644 index 00000000..ad47935c --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py @@ -0,0 +1,2317 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.catalog_service import CatalogServiceAsyncClient +from google.cloud.retail_v2.services.catalog_service import CatalogServiceClient +from google.cloud.retail_v2.services.catalog_service import pagers +from google.cloud.retail_v2.services.catalog_service import transports +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CatalogServiceClient._get_default_mtls_endpoint(None) is None + assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CatalogServiceGrpcTransport, "grpc"), + (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_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", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_catalog_service_client_get_transport_class(): + transport = CatalogServiceClient.get_transport_class() + available_transports = [ + transports.CatalogServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CatalogServiceClient.get_transport_class("grpc") + assert transport == transports.CatalogServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CatalogServiceClient, CatalogServiceAsyncClient +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_catalog_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ListCatalogsRequest, + dict, +]) +def test_list_catalogs(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_catalogs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalogs), + '__call__') as call: + client.list_catalogs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + +@pytest.mark.asyncio +async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_catalogs_async_from_dict(): + await test_list_catalogs_async(request_type=dict) + + +def test_list_catalogs_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = catalog_service.ListCatalogsResponse() + client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_catalogs( + 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_catalogs_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_catalogs_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_catalogs( + 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_catalogs_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + + +def test_list_catalogs_pager(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_catalogs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, catalog.Catalog) + for i in results) +def test_list_catalogs_pages(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = list(client.list_catalogs(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_catalogs_async_pager(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_catalogs(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, catalog.Catalog) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_catalogs_async_pages(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCatalogRequest, + dict, +]) +def test_update_catalog(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + ) + response = client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_catalog_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalog), + '__call__') as call: + client.update_catalog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + +@pytest.mark.asyncio +async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_catalog_async_from_dict(): + await test_update_catalog_async(request_type=dict) + + +def test_update_catalog_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = gcr_catalog.Catalog() + client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_catalog_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +def test_update_catalog_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_catalog_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.SetDefaultBranchRequest, + dict, +]) +def test_set_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_set_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + client.set_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_set_default_branch_async_from_dict(): + await test_set_default_branch_async(request_type=dict) + + +def test_set_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = None + client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_set_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_set_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetDefaultBranchRequest, + dict, +]) +def test_get_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + ) + response = client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +def test_get_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_default_branch), + '__call__') as call: + client.get_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + )) + response = await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +@pytest.mark.asyncio +async def test_get_default_branch_async_from_dict(): + await test_get_default_branch_async(request_type=dict) + + +def test_get_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = catalog_service.GetDefaultBranchResponse() + client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_get_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_get_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CatalogServiceClient.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 = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CatalogServiceGrpcTransport, + ) + +def test_catalog_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_catalog_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_catalogs', + 'update_catalog', + 'set_default_branch', + 'get_default_branch', + ) + 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_catalog_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.retail_v2.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport( + 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_catalog_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.retail_v2.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport() + adc.assert_called_once() + + +def test_catalog_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) + CatalogServiceClient() + 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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +def test_catalog_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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +def test_catalog_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.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_catalog_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_no_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_with_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_catalog_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcTransport( + 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_catalog_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcAsyncIOTransport( + 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_branch_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = CatalogServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = CatalogServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_branch_path(path) + assert expected == actual + +def test_catalog_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + } + path = CatalogServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CatalogServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = CatalogServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = CatalogServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CatalogServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CatalogServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CatalogServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = CatalogServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CatalogServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CatalogServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CatalogServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py new file mode 100644 index 00000000..daf312fe --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py @@ -0,0 +1,1501 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.completion_service import CompletionServiceAsyncClient +from google.cloud.retail_v2.services.completion_service import CompletionServiceClient +from google.cloud.retail_v2.services.completion_service import transports +from google.cloud.retail_v2.types import completion_service +from google.cloud.retail_v2.types import import_config +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CompletionServiceClient._get_default_mtls_endpoint(None) is None + assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CompletionServiceGrpcTransport, "grpc"), + (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_completion_service_client_get_transport_class(): + transport = CompletionServiceClient.get_transport_class() + available_transports = [ + transports.CompletionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CompletionServiceClient.get_transport_class("grpc") + assert transport == transports.CompletionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CompletionServiceClient, CompletionServiceAsyncClient +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_completion_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CompletionServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + ) + response = client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +def test_complete_query_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + client.complete_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + +@pytest.mark.asyncio +async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + )) + response = await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +@pytest.mark.asyncio +async def test_complete_query_async_from_dict(): + await test_complete_query_async(request_type=dict) + + +def test_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) + await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportCompletionDataRequest, + dict, +]) +def test_import_completion_data(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_completion_data_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + client.import_completion_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + +@pytest.mark.asyncio +async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_completion_data_async_from_dict(): + await test_import_completion_data_async(request_type=dict) + + +def test_import_completion_data_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # 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_completion_data_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CompletionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CompletionServiceGrpcTransport, + ) + +def test_completion_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_completion_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'complete_query', + 'import_completion_data', + ) + 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_completion_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_completion_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport() + adc.assert_called_once() + + +def test_completion_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CompletionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionServiceGrpcTransport, grpc_helpers), + (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_completion_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_no_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_with_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_completion_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_completion_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_completion_service_grpc_lro_client(): + client = CompletionServiceClient( + 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_completion_service_grpc_lro_async_client(): + client = CompletionServiceAsyncClient( + 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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CompletionServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CompletionServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CompletionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CompletionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = CompletionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CompletionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CompletionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CompletionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = CompletionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CompletionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CompletionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CompletionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CompletionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py new file mode 100644 index 00000000..08628b2d --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py @@ -0,0 +1,1329 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.prediction_service import PredictionServiceAsyncClient +from google.cloud.retail_v2.services.prediction_service import PredictionServiceClient +from google.cloud.retail_v2.services.prediction_service import transports +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import prediction_service +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import promotion +from google.cloud.retail_v2.types import user_event +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PredictionServiceClient._get_default_mtls_endpoint(None) is None + assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionServiceGrpcTransport, "grpc"), + (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_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", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_prediction_service_client_get_transport_class(): + transport = PredictionServiceClient.get_transport_class() + available_transports = [ + transports.PredictionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = PredictionServiceClient.get_transport_class("grpc") + assert transport == transports.PredictionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + PredictionServiceClient, PredictionServiceAsyncClient +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_prediction_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_service.PredictRequest, + dict, +]) +def test_predict(request_type, transport: str = 'grpc'): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + response = client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_predict_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + client.predict() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + +@pytest.mark.asyncio +async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + )) + response = await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +@pytest.mark.asyncio +async def test_predict_async_from_dict(): + await test_predict_async(request_type=dict) + + +def test_predict_field_headers(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_predict_field_headers_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) + await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = PredictionServiceClient.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 = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'predict', + ) + 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport( + 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport() + adc.assert_called_once() + + +def test_prediction_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) + PredictionServiceClient() + 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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +def test_prediction_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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +def test_prediction_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.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_prediction_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_no_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_with_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_prediction_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcTransport( + 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_prediction_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcAsyncIOTransport( + 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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_product_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + product = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + "branch": "winkle", + "product": "nautilus", + } + path = PredictionServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PredictionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = PredictionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = PredictionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = PredictionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PredictionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = PredictionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = PredictionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = PredictionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = PredictionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PredictionServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py new file mode 100644 index 00000000..6bd5f4bf --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py @@ -0,0 +1,4135 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.product_service import ProductServiceAsyncClient +from google.cloud.retail_v2.services.product_service import ProductServiceClient +from google.cloud.retail_v2.services.product_service import pagers +from google.cloud.retail_v2.services.product_service import transports +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service +from google.cloud.retail_v2.types import promotion +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProductServiceClient._get_default_mtls_endpoint(None) is None + assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProductServiceGrpcTransport, "grpc"), + (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_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", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_product_service_client_get_transport_class(): + transport = ProductServiceClient.get_transport_class() + available_transports = [ + transports.ProductServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ProductServiceClient.get_transport_class("grpc") + assert transport == transports.ProductServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_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(ProductServiceClient, '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(ProductServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ProductServiceClient, ProductServiceAsyncClient +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_product_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.CreateProductRequest, + dict, +]) +def test_create_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_create_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.create_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + +@pytest.mark.asyncio +async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_create_product_async_from_dict(): + await test_create_product_async(request_type=dict) + + +def test_create_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + + +def test_create_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + +@pytest.mark.asyncio +async def test_create_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_get_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.get_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + +@pytest.mark.asyncio +async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_get_product_async_from_dict(): + await test_get_product_async(request_type=dict) + + +def test_get_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = product.Product() + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.GetProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.GetProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.list_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + +@pytest.mark.asyncio +async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_products_async_from_dict(): + await test_list_products_async(request_type=dict) + + +def test_list_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = product_service.ListProductsResponse() + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products( + 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_products_flattened_error(): + client = ProductServiceClient( + credentials=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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products( + 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_products_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + + +def test_list_products_pager(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_products(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, product.Product) + for i in results) +def test_list_products_pages(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(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_products_async_pager(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(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, product.Product) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_products(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + product_service.UpdateProductRequest, + dict, +]) +def test_update_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_update_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.update_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + +@pytest.mark.asyncio +async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_update_product_async_from_dict(): + await test_update_product_async(request_type=dict) + + +def test_update_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +def test_update_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.DeleteProductRequest, + dict, +]) +def test_delete_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.delete_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + +@pytest.mark.asyncio +async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_product_async_from_dict(): + await test_delete_product_async(request_type=dict) + + +def test_delete_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = None + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportProductsRequest, + dict, +]) +def test_import_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.import_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + +@pytest.mark.asyncio +async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__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_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_products_async_from_dict(): + await test_import_products_async(request_type=dict) + + +def test_import_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + product_service.SetInventoryRequest, + dict, +]) +def test_set_inventory(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_inventory_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + client.set_inventory() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + +@pytest.mark.asyncio +async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_set_inventory_async_from_dict(): + await test_set_inventory_async(request_type=dict) + + +def test_set_inventory_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_inventory_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +def test_set_inventory_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_set_inventory_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_set_inventory_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_inventory_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddFulfillmentPlacesRequest, + dict, +]) +def test_add_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + client.add_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async_from_dict(): + await test_add_fulfillment_places_async(request_type=dict) + + +def test_add_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveFulfillmentPlacesRequest, + dict, +]) +def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + client.remove_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async_from_dict(): + await test_remove_fulfillment_places_async(request_type=dict) + + +def test_remove_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddLocalInventoriesRequest, + dict, +]) +def test_add_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + client.add_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_local_inventories_async_from_dict(): + await test_add_local_inventories_async(request_type=dict) + + +def test_add_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveLocalInventoriesRequest, + dict, +]) +def test_remove_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + client.remove_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_local_inventories_async_from_dict(): + await test_remove_local_inventories_async(request_type=dict) + + +def test_remove_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ProductServiceClient.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 = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProductServiceGrpcTransport, + ) + +def test_product_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_product_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.product_service.transports.ProductServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_product', + 'get_product', + 'list_products', + 'update_product', + 'delete_product', + 'import_products', + 'set_inventory', + 'add_fulfillment_places', + 'remove_fulfillment_places', + 'add_local_inventories', + 'remove_local_inventories', + ) + 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_product_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.retail_v2.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport( + 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_product_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.retail_v2.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport() + adc.assert_called_once() + + +def test_product_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) + ProductServiceClient() + 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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + ], +) +def test_product_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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + ], +) +def test_product_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.ProductServiceGrpcTransport, grpc_helpers), + (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_product_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_no_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_with_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_product_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcTransport( + 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_product_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcAsyncIOTransport( + 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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_product_service_grpc_lro_client(): + client = ProductServiceClient( + 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_product_service_grpc_lro_async_client(): + client = ProductServiceAsyncClient( + 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" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = ProductServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = ProductServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = ProductServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = ProductServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProductServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ProductServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProductServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ProductServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProductServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ProductServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ProductServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ProductServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ProductServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ProductServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ProductServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py new file mode 100644 index 00000000..dd102323 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py @@ -0,0 +1,1546 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.search_service import SearchServiceAsyncClient +from google.cloud.retail_v2.services.search_service import SearchServiceClient +from google.cloud.retail_v2.services.search_service import pagers +from google.cloud.retail_v2.services.search_service import transports +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import search_service +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SearchServiceClient._get_default_mtls_endpoint(None) is None + assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SearchServiceGrpcTransport, "grpc"), + (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_search_service_client_get_transport_class(): + transport = SearchServiceClient.get_transport_class() + available_transports = [ + transports.SearchServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SearchServiceClient.get_transport_class("grpc") + assert transport == transports.SearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SearchServiceClient, SearchServiceAsyncClient +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SearchServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + search_service.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + + +def test_search_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = search_service.SearchResponse() + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_search_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('placement', ''), + )), + ) + pager = client.search(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_async_pager(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = SearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_search_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_search_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport() + adc.assert_called_once() + + +def test_search_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SearchServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SearchServiceGrpcTransport, grpc_helpers), + (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_search_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_no_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_with_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_branch_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = SearchServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = SearchServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = SearchServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = SearchServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py new file mode 100644 index 00000000..e6c54dee --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py @@ -0,0 +1,2038 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.retail_v2.services.user_event_service import UserEventServiceClient +from google.cloud.retail_v2.services.user_event_service import transports +from google.cloud.retail_v2.types import common +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import promotion +from google.cloud.retail_v2.types import purge_config +from google.cloud.retail_v2.types import user_event +from google.cloud.retail_v2.types import user_event_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + ) + response = client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +def test_write_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) + await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeUserEventsRequest, + dict, +]) +def test_purge_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + client.purge_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + +@pytest.mark.asyncio +async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_user_events_async_from_dict(): + await test_purge_user_events_async(request_type=dict) + + +def test_purge_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_purge_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.RejoinUserEventsRequest, + dict, +]) +def test_rejoin_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_rejoin_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + client.rejoin_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + +@pytest.mark.asyncio +async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_rejoin_user_events_async_from_dict(): + await test_rejoin_user_events_async(request_type=dict) + + +def test_rejoin_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_rejoin_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'purge_user_events', + 'import_user_events', + 'rejoin_user_events', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_user_event_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_user_event_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +def test_user_event_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + UserEventServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = UserEventServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = UserEventServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_product_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + product = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + "branch": "whelk", + "product": "octopus", + } + path = UserEventServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/.coveragerc b/owl-bot-staging/v2alpha/.coveragerc new file mode 100644 index 00000000..a8b114f0 --- /dev/null +++ b/owl-bot-staging/v2alpha/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/retail/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2alpha/.flake8 b/owl-bot-staging/v2alpha/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v2alpha/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v2alpha/MANIFEST.in b/owl-bot-staging/v2alpha/MANIFEST.in new file mode 100644 index 00000000..3ee710cc --- /dev/null +++ b/owl-bot-staging/v2alpha/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/retail *.py +recursive-include google/cloud/retail_v2alpha *.py diff --git a/owl-bot-staging/v2alpha/README.rst b/owl-bot-staging/v2alpha/README.rst new file mode 100644 index 00000000..cb039760 --- /dev/null +++ b/owl-bot-staging/v2alpha/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Retail API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Retail API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2alpha/docs/conf.py b/owl-bot-staging/v2alpha/docs/conf.py new file mode 100644 index 00000000..5be9eb4b --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-retail documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-retail" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-retail-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-retail.tex", + u"google-cloud-retail Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-retail", + u"Google Cloud Retail Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-retail", + u"google-cloud-retail Documentation", + author, + "google-cloud-retail", + "GAPIC library for Google Cloud Retail API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v2alpha/docs/index.rst b/owl-bot-staging/v2alpha/docs/index.rst new file mode 100644 index 00000000..dc0a2096 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + retail_v2alpha/services + retail_v2alpha/types diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst new file mode 100644 index 00000000..745d0cf4 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst @@ -0,0 +1,10 @@ +CatalogService +-------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.catalog_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.catalog_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst new file mode 100644 index 00000000..3a276433 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst @@ -0,0 +1,6 @@ +CompletionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.completion_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst new file mode 100644 index 00000000..36aaf9b6 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst @@ -0,0 +1,10 @@ +ControlService +-------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.control_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.control_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst new file mode 100644 index 00000000..b659cf98 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst @@ -0,0 +1,6 @@ +PredictionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.prediction_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst new file mode 100644 index 00000000..acbb336e --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst @@ -0,0 +1,10 @@ +ProductService +-------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.product_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.product_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst new file mode 100644 index 00000000..ad4c486d --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst @@ -0,0 +1,10 @@ +SearchService +------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst new file mode 100644 index 00000000..edeb8cfc --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst @@ -0,0 +1,13 @@ +Services for Google Cloud Retail v2alpha API +============================================ +.. toctree:: + :maxdepth: 2 + + catalog_service + completion_service + control_service + prediction_service + product_service + search_service + serving_config_service + user_event_service diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst new file mode 100644 index 00000000..c1516860 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst @@ -0,0 +1,10 @@ +ServingConfigService +-------------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.serving_config_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2alpha.services.serving_config_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst new file mode 100644 index 00000000..c1445ad6 --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Retail v2alpha API +========================================= + +.. automodule:: google.cloud.retail_v2alpha.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst new file mode 100644 index 00000000..8c56485c --- /dev/null +++ b/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst @@ -0,0 +1,6 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.retail_v2alpha.services.user_event_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py new file mode 100644 index 00000000..a17a283b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.retail_v2alpha.services.catalog_service.client import CatalogServiceClient +from google.cloud.retail_v2alpha.services.catalog_service.async_client import CatalogServiceAsyncClient +from google.cloud.retail_v2alpha.services.completion_service.client import CompletionServiceClient +from google.cloud.retail_v2alpha.services.completion_service.async_client import CompletionServiceAsyncClient +from google.cloud.retail_v2alpha.services.control_service.client import ControlServiceClient +from google.cloud.retail_v2alpha.services.control_service.async_client import ControlServiceAsyncClient +from google.cloud.retail_v2alpha.services.prediction_service.client import PredictionServiceClient +from google.cloud.retail_v2alpha.services.prediction_service.async_client import PredictionServiceAsyncClient +from google.cloud.retail_v2alpha.services.product_service.client import ProductServiceClient +from google.cloud.retail_v2alpha.services.product_service.async_client import ProductServiceAsyncClient +from google.cloud.retail_v2alpha.services.search_service.client import SearchServiceClient +from google.cloud.retail_v2alpha.services.search_service.async_client import SearchServiceAsyncClient +from google.cloud.retail_v2alpha.services.serving_config_service.client import ServingConfigServiceClient +from google.cloud.retail_v2alpha.services.serving_config_service.async_client import ServingConfigServiceAsyncClient +from google.cloud.retail_v2alpha.services.user_event_service.client import UserEventServiceClient +from google.cloud.retail_v2alpha.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.retail_v2alpha.types.catalog import AttributesConfig +from google.cloud.retail_v2alpha.types.catalog import Catalog +from google.cloud.retail_v2alpha.types.catalog import CatalogAttribute +from google.cloud.retail_v2alpha.types.catalog import CompletionConfig +from google.cloud.retail_v2alpha.types.catalog import MerchantCenterLink +from google.cloud.retail_v2alpha.types.catalog import MerchantCenterLinkingConfig +from google.cloud.retail_v2alpha.types.catalog import ProductLevelConfig +from google.cloud.retail_v2alpha.types.catalog_service import AddCatalogAttributeRequest +from google.cloud.retail_v2alpha.types.catalog_service import GetAttributesConfigRequest +from google.cloud.retail_v2alpha.types.catalog_service import GetCompletionConfigRequest +from google.cloud.retail_v2alpha.types.catalog_service import GetDefaultBranchRequest +from google.cloud.retail_v2alpha.types.catalog_service import GetDefaultBranchResponse +from google.cloud.retail_v2alpha.types.catalog_service import ListCatalogsRequest +from google.cloud.retail_v2alpha.types.catalog_service import ListCatalogsResponse +from google.cloud.retail_v2alpha.types.catalog_service import RemoveCatalogAttributeRequest +from google.cloud.retail_v2alpha.types.catalog_service import ReplaceCatalogAttributeRequest +from google.cloud.retail_v2alpha.types.catalog_service import SetDefaultBranchRequest +from google.cloud.retail_v2alpha.types.catalog_service import UpdateAttributesConfigRequest +from google.cloud.retail_v2alpha.types.catalog_service import UpdateCatalogRequest +from google.cloud.retail_v2alpha.types.catalog_service import UpdateCompletionConfigRequest +from google.cloud.retail_v2alpha.types.common import Audience +from google.cloud.retail_v2alpha.types.common import ColorInfo +from google.cloud.retail_v2alpha.types.common import Condition +from google.cloud.retail_v2alpha.types.common import CustomAttribute +from google.cloud.retail_v2alpha.types.common import FulfillmentInfo +from google.cloud.retail_v2alpha.types.common import Image +from google.cloud.retail_v2alpha.types.common import Interval +from google.cloud.retail_v2alpha.types.common import LocalInventory +from google.cloud.retail_v2alpha.types.common import PriceInfo +from google.cloud.retail_v2alpha.types.common import Rating +from google.cloud.retail_v2alpha.types.common import Rule +from google.cloud.retail_v2alpha.types.common import UserInfo +from google.cloud.retail_v2alpha.types.common import AttributeConfigLevel +from google.cloud.retail_v2alpha.types.common import SearchSolutionUseCase +from google.cloud.retail_v2alpha.types.common import SolutionType +from google.cloud.retail_v2alpha.types.completion_service import CompleteQueryRequest +from google.cloud.retail_v2alpha.types.completion_service import CompleteQueryResponse +from google.cloud.retail_v2alpha.types.control import Control +from google.cloud.retail_v2alpha.types.control_service import CreateControlRequest +from google.cloud.retail_v2alpha.types.control_service import DeleteControlRequest +from google.cloud.retail_v2alpha.types.control_service import GetControlRequest +from google.cloud.retail_v2alpha.types.control_service import ListControlsRequest +from google.cloud.retail_v2alpha.types.control_service import ListControlsResponse +from google.cloud.retail_v2alpha.types.control_service import UpdateControlRequest +from google.cloud.retail_v2alpha.types.export_config import ExportErrorsConfig +from google.cloud.retail_v2alpha.types.export_config import ExportMetadata +from google.cloud.retail_v2alpha.types.export_config import ExportProductsResponse +from google.cloud.retail_v2alpha.types.export_config import ExportUserEventsResponse +from google.cloud.retail_v2alpha.types.import_config import BigQuerySource +from google.cloud.retail_v2alpha.types.import_config import CompletionDataInputConfig +from google.cloud.retail_v2alpha.types.import_config import GcsSource +from google.cloud.retail_v2alpha.types.import_config import ImportCompletionDataRequest +from google.cloud.retail_v2alpha.types.import_config import ImportCompletionDataResponse +from google.cloud.retail_v2alpha.types.import_config import ImportErrorsConfig +from google.cloud.retail_v2alpha.types.import_config import ImportMetadata +from google.cloud.retail_v2alpha.types.import_config import ImportProductsRequest +from google.cloud.retail_v2alpha.types.import_config import ImportProductsResponse +from google.cloud.retail_v2alpha.types.import_config import ImportUserEventsRequest +from google.cloud.retail_v2alpha.types.import_config import ImportUserEventsResponse +from google.cloud.retail_v2alpha.types.import_config import ProductInlineSource +from google.cloud.retail_v2alpha.types.import_config import ProductInputConfig +from google.cloud.retail_v2alpha.types.import_config import UserEventImportSummary +from google.cloud.retail_v2alpha.types.import_config import UserEventInlineSource +from google.cloud.retail_v2alpha.types.import_config import UserEventInputConfig +from google.cloud.retail_v2alpha.types.prediction_service import PredictRequest +from google.cloud.retail_v2alpha.types.prediction_service import PredictResponse +from google.cloud.retail_v2alpha.types.product import Product +from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesMetadata +from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesRequest +from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesResponse +from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesMetadata +from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesRequest +from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesResponse +from google.cloud.retail_v2alpha.types.product_service import CreateProductRequest +from google.cloud.retail_v2alpha.types.product_service import DeleteProductRequest +from google.cloud.retail_v2alpha.types.product_service import GetProductRequest +from google.cloud.retail_v2alpha.types.product_service import ListProductsRequest +from google.cloud.retail_v2alpha.types.product_service import ListProductsResponse +from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesMetadata +from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesRequest +from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesResponse +from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesMetadata +from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesRequest +from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesResponse +from google.cloud.retail_v2alpha.types.product_service import SetInventoryMetadata +from google.cloud.retail_v2alpha.types.product_service import SetInventoryRequest +from google.cloud.retail_v2alpha.types.product_service import SetInventoryResponse +from google.cloud.retail_v2alpha.types.product_service import UpdateProductRequest +from google.cloud.retail_v2alpha.types.promotion import Promotion +from google.cloud.retail_v2alpha.types.purge_config import PurgeMetadata +from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsMetadata +from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsRequest +from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsResponse +from google.cloud.retail_v2alpha.types.purge_config import PurgeUserEventsRequest +from google.cloud.retail_v2alpha.types.purge_config import PurgeUserEventsResponse +from google.cloud.retail_v2alpha.types.search_service import SearchRequest +from google.cloud.retail_v2alpha.types.search_service import SearchResponse +from google.cloud.retail_v2alpha.types.serving_config import ServingConfig +from google.cloud.retail_v2alpha.types.serving_config_service import AddControlRequest +from google.cloud.retail_v2alpha.types.serving_config_service import CreateServingConfigRequest +from google.cloud.retail_v2alpha.types.serving_config_service import DeleteServingConfigRequest +from google.cloud.retail_v2alpha.types.serving_config_service import GetServingConfigRequest +from google.cloud.retail_v2alpha.types.serving_config_service import ListServingConfigsRequest +from google.cloud.retail_v2alpha.types.serving_config_service import ListServingConfigsResponse +from google.cloud.retail_v2alpha.types.serving_config_service import RemoveControlRequest +from google.cloud.retail_v2alpha.types.serving_config_service import UpdateServingConfigRequest +from google.cloud.retail_v2alpha.types.user_event import CompletionDetail +from google.cloud.retail_v2alpha.types.user_event import ProductDetail +from google.cloud.retail_v2alpha.types.user_event import PurchaseTransaction +from google.cloud.retail_v2alpha.types.user_event import UserEvent +from google.cloud.retail_v2alpha.types.user_event_service import CollectUserEventRequest +from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsMetadata +from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsRequest +from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsResponse +from google.cloud.retail_v2alpha.types.user_event_service import WriteUserEventRequest + +__all__ = ('CatalogServiceClient', + 'CatalogServiceAsyncClient', + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', + 'ControlServiceClient', + 'ControlServiceAsyncClient', + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', + 'ProductServiceClient', + 'ProductServiceAsyncClient', + 'SearchServiceClient', + 'SearchServiceAsyncClient', + 'ServingConfigServiceClient', + 'ServingConfigServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'AttributesConfig', + 'Catalog', + 'CatalogAttribute', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'ProductLevelConfig', + 'AddCatalogAttributeRequest', + 'GetAttributesConfigRequest', + 'GetCompletionConfigRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + 'SetDefaultBranchRequest', + 'UpdateAttributesConfigRequest', + 'UpdateCatalogRequest', + 'UpdateCompletionConfigRequest', + 'Audience', + 'ColorInfo', + 'Condition', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'Rule', + 'UserInfo', + 'AttributeConfigLevel', + 'SearchSolutionUseCase', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Control', + 'CreateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + 'UpdateControlRequest', + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeProductsMetadata', + 'PurgeProductsRequest', + 'PurgeProductsResponse', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'ServingConfig', + 'AddControlRequest', + 'CreateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'RemoveControlRequest', + 'UpdateServingConfigRequest', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail/py.typed b/owl-bot-staging/v2alpha/google/cloud/retail/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py new file mode 100644 index 00000000..e515a173 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.catalog_service import CatalogServiceClient +from .services.catalog_service import CatalogServiceAsyncClient +from .services.completion_service import CompletionServiceClient +from .services.completion_service import CompletionServiceAsyncClient +from .services.control_service import ControlServiceClient +from .services.control_service import ControlServiceAsyncClient +from .services.prediction_service import PredictionServiceClient +from .services.prediction_service import PredictionServiceAsyncClient +from .services.product_service import ProductServiceClient +from .services.product_service import ProductServiceAsyncClient +from .services.search_service import SearchServiceClient +from .services.search_service import SearchServiceAsyncClient +from .services.serving_config_service import ServingConfigServiceClient +from .services.serving_config_service import ServingConfigServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.catalog import AttributesConfig +from .types.catalog import Catalog +from .types.catalog import CatalogAttribute +from .types.catalog import CompletionConfig +from .types.catalog import MerchantCenterLink +from .types.catalog import MerchantCenterLinkingConfig +from .types.catalog import ProductLevelConfig +from .types.catalog_service import AddCatalogAttributeRequest +from .types.catalog_service import GetAttributesConfigRequest +from .types.catalog_service import GetCompletionConfigRequest +from .types.catalog_service import GetDefaultBranchRequest +from .types.catalog_service import GetDefaultBranchResponse +from .types.catalog_service import ListCatalogsRequest +from .types.catalog_service import ListCatalogsResponse +from .types.catalog_service import RemoveCatalogAttributeRequest +from .types.catalog_service import ReplaceCatalogAttributeRequest +from .types.catalog_service import SetDefaultBranchRequest +from .types.catalog_service import UpdateAttributesConfigRequest +from .types.catalog_service import UpdateCatalogRequest +from .types.catalog_service import UpdateCompletionConfigRequest +from .types.common import Audience +from .types.common import ColorInfo +from .types.common import Condition +from .types.common import CustomAttribute +from .types.common import FulfillmentInfo +from .types.common import Image +from .types.common import Interval +from .types.common import LocalInventory +from .types.common import PriceInfo +from .types.common import Rating +from .types.common import Rule +from .types.common import UserInfo +from .types.common import AttributeConfigLevel +from .types.common import SearchSolutionUseCase +from .types.common import SolutionType +from .types.completion_service import CompleteQueryRequest +from .types.completion_service import CompleteQueryResponse +from .types.control import Control +from .types.control_service import CreateControlRequest +from .types.control_service import DeleteControlRequest +from .types.control_service import GetControlRequest +from .types.control_service import ListControlsRequest +from .types.control_service import ListControlsResponse +from .types.control_service import UpdateControlRequest +from .types.export_config import ExportErrorsConfig +from .types.export_config import ExportMetadata +from .types.export_config import ExportProductsResponse +from .types.export_config import ExportUserEventsResponse +from .types.import_config import BigQuerySource +from .types.import_config import CompletionDataInputConfig +from .types.import_config import GcsSource +from .types.import_config import ImportCompletionDataRequest +from .types.import_config import ImportCompletionDataResponse +from .types.import_config import ImportErrorsConfig +from .types.import_config import ImportMetadata +from .types.import_config import ImportProductsRequest +from .types.import_config import ImportProductsResponse +from .types.import_config import ImportUserEventsRequest +from .types.import_config import ImportUserEventsResponse +from .types.import_config import ProductInlineSource +from .types.import_config import ProductInputConfig +from .types.import_config import UserEventImportSummary +from .types.import_config import UserEventInlineSource +from .types.import_config import UserEventInputConfig +from .types.prediction_service import PredictRequest +from .types.prediction_service import PredictResponse +from .types.product import Product +from .types.product_service import AddFulfillmentPlacesMetadata +from .types.product_service import AddFulfillmentPlacesRequest +from .types.product_service import AddFulfillmentPlacesResponse +from .types.product_service import AddLocalInventoriesMetadata +from .types.product_service import AddLocalInventoriesRequest +from .types.product_service import AddLocalInventoriesResponse +from .types.product_service import CreateProductRequest +from .types.product_service import DeleteProductRequest +from .types.product_service import GetProductRequest +from .types.product_service import ListProductsRequest +from .types.product_service import ListProductsResponse +from .types.product_service import RemoveFulfillmentPlacesMetadata +from .types.product_service import RemoveFulfillmentPlacesRequest +from .types.product_service import RemoveFulfillmentPlacesResponse +from .types.product_service import RemoveLocalInventoriesMetadata +from .types.product_service import RemoveLocalInventoriesRequest +from .types.product_service import RemoveLocalInventoriesResponse +from .types.product_service import SetInventoryMetadata +from .types.product_service import SetInventoryRequest +from .types.product_service import SetInventoryResponse +from .types.product_service import UpdateProductRequest +from .types.promotion import Promotion +from .types.purge_config import PurgeMetadata +from .types.purge_config import PurgeProductsMetadata +from .types.purge_config import PurgeProductsRequest +from .types.purge_config import PurgeProductsResponse +from .types.purge_config import PurgeUserEventsRequest +from .types.purge_config import PurgeUserEventsResponse +from .types.search_service import SearchRequest +from .types.search_service import SearchResponse +from .types.serving_config import ServingConfig +from .types.serving_config_service import AddControlRequest +from .types.serving_config_service import CreateServingConfigRequest +from .types.serving_config_service import DeleteServingConfigRequest +from .types.serving_config_service import GetServingConfigRequest +from .types.serving_config_service import ListServingConfigsRequest +from .types.serving_config_service import ListServingConfigsResponse +from .types.serving_config_service import RemoveControlRequest +from .types.serving_config_service import UpdateServingConfigRequest +from .types.user_event import CompletionDetail +from .types.user_event import ProductDetail +from .types.user_event import PurchaseTransaction +from .types.user_event import UserEvent +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import RejoinUserEventsMetadata +from .types.user_event_service import RejoinUserEventsRequest +from .types.user_event_service import RejoinUserEventsResponse +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CatalogServiceAsyncClient', + 'CompletionServiceAsyncClient', + 'ControlServiceAsyncClient', + 'PredictionServiceAsyncClient', + 'ProductServiceAsyncClient', + 'SearchServiceAsyncClient', + 'ServingConfigServiceAsyncClient', + 'UserEventServiceAsyncClient', +'AddCatalogAttributeRequest', +'AddControlRequest', +'AddFulfillmentPlacesMetadata', +'AddFulfillmentPlacesRequest', +'AddFulfillmentPlacesResponse', +'AddLocalInventoriesMetadata', +'AddLocalInventoriesRequest', +'AddLocalInventoriesResponse', +'AttributeConfigLevel', +'AttributesConfig', +'Audience', +'BigQuerySource', +'Catalog', +'CatalogAttribute', +'CatalogServiceClient', +'CollectUserEventRequest', +'ColorInfo', +'CompleteQueryRequest', +'CompleteQueryResponse', +'CompletionConfig', +'CompletionDataInputConfig', +'CompletionDetail', +'CompletionServiceClient', +'Condition', +'Control', +'ControlServiceClient', +'CreateControlRequest', +'CreateProductRequest', +'CreateServingConfigRequest', +'CustomAttribute', +'DeleteControlRequest', +'DeleteProductRequest', +'DeleteServingConfigRequest', +'ExportErrorsConfig', +'ExportMetadata', +'ExportProductsResponse', +'ExportUserEventsResponse', +'FulfillmentInfo', +'GcsSource', +'GetAttributesConfigRequest', +'GetCompletionConfigRequest', +'GetControlRequest', +'GetDefaultBranchRequest', +'GetDefaultBranchResponse', +'GetProductRequest', +'GetServingConfigRequest', +'Image', +'ImportCompletionDataRequest', +'ImportCompletionDataResponse', +'ImportErrorsConfig', +'ImportMetadata', +'ImportProductsRequest', +'ImportProductsResponse', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'Interval', +'ListCatalogsRequest', +'ListCatalogsResponse', +'ListControlsRequest', +'ListControlsResponse', +'ListProductsRequest', +'ListProductsResponse', +'ListServingConfigsRequest', +'ListServingConfigsResponse', +'LocalInventory', +'MerchantCenterLink', +'MerchantCenterLinkingConfig', +'PredictRequest', +'PredictResponse', +'PredictionServiceClient', +'PriceInfo', +'Product', +'ProductDetail', +'ProductInlineSource', +'ProductInputConfig', +'ProductLevelConfig', +'ProductServiceClient', +'Promotion', +'PurchaseTransaction', +'PurgeMetadata', +'PurgeProductsMetadata', +'PurgeProductsRequest', +'PurgeProductsResponse', +'PurgeUserEventsRequest', +'PurgeUserEventsResponse', +'Rating', +'RejoinUserEventsMetadata', +'RejoinUserEventsRequest', +'RejoinUserEventsResponse', +'RemoveCatalogAttributeRequest', +'RemoveControlRequest', +'RemoveFulfillmentPlacesMetadata', +'RemoveFulfillmentPlacesRequest', +'RemoveFulfillmentPlacesResponse', +'RemoveLocalInventoriesMetadata', +'RemoveLocalInventoriesRequest', +'RemoveLocalInventoriesResponse', +'ReplaceCatalogAttributeRequest', +'Rule', +'SearchRequest', +'SearchResponse', +'SearchServiceClient', +'SearchSolutionUseCase', +'ServingConfig', +'ServingConfigServiceClient', +'SetDefaultBranchRequest', +'SetInventoryMetadata', +'SetInventoryRequest', +'SetInventoryResponse', +'SolutionType', +'UpdateAttributesConfigRequest', +'UpdateCatalogRequest', +'UpdateCompletionConfigRequest', +'UpdateControlRequest', +'UpdateProductRequest', +'UpdateServingConfigRequest', +'UserEvent', +'UserEventImportSummary', +'UserEventInlineSource', +'UserEventInputConfig', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json new file mode 100644 index 00000000..543e36d6 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json @@ -0,0 +1,561 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.retail_v2alpha", + "protoPackage": "google.cloud.retail.v2alpha", + "schema": "1.0", + "services": { + "CatalogService": { + "clients": { + "grpc": { + "libraryClient": "CatalogServiceClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "add_catalog_attribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "get_attributes_config" + ] + }, + "GetCompletionConfig": { + "methods": [ + "get_completion_config" + ] + }, + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "remove_catalog_attribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "replace_catalog_attribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "update_attributes_config" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "update_completion_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CatalogServiceAsyncClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "add_catalog_attribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "get_attributes_config" + ] + }, + "GetCompletionConfig": { + "methods": [ + "get_completion_config" + ] + }, + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "remove_catalog_attribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "replace_catalog_attribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "update_attributes_config" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "update_completion_config" + ] + } + } + } + } + }, + "CompletionService": { + "clients": { + "grpc": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CompletionServiceAsyncClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + } + } + }, + "ControlService": { + "clients": { + "grpc": { + "libraryClient": "ControlServiceClient", + "rpcs": { + "CreateControl": { + "methods": [ + "create_control" + ] + }, + "DeleteControl": { + "methods": [ + "delete_control" + ] + }, + "GetControl": { + "methods": [ + "get_control" + ] + }, + "ListControls": { + "methods": [ + "list_controls" + ] + }, + "UpdateControl": { + "methods": [ + "update_control" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ControlServiceAsyncClient", + "rpcs": { + "CreateControl": { + "methods": [ + "create_control" + ] + }, + "DeleteControl": { + "methods": [ + "delete_control" + ] + }, + "GetControl": { + "methods": [ + "get_control" + ] + }, + "ListControls": { + "methods": [ + "list_controls" + ] + }, + "UpdateControl": { + "methods": [ + "update_control" + ] + } + } + } + } + }, + "PredictionService": { + "clients": { + "grpc": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionServiceAsyncClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + } + } + }, + "ProductService": { + "clients": { + "grpc": { + "libraryClient": "ProductServiceClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "PurgeProducts": { + "methods": [ + "purge_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductServiceAsyncClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "PurgeProducts": { + "methods": [ + "purge_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + } + } + }, + "SearchService": { + "clients": { + "grpc": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SearchServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + }, + "ServingConfigService": { + "clients": { + "grpc": { + "libraryClient": "ServingConfigServiceClient", + "rpcs": { + "AddControl": { + "methods": [ + "add_control" + ] + }, + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, + "RemoveControl": { + "methods": [ + "remove_control" + ] + }, + "UpdateServingConfig": { + "methods": [ + "update_serving_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServingConfigServiceAsyncClient", + "rpcs": { + "AddControl": { + "methods": [ + "add_control" + ] + }, + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, + "RemoveControl": { + "methods": [ + "remove_control" + ] + }, + "UpdateServingConfig": { + "methods": [ + "update_serving_config" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py new file mode 100644 index 00000000..d276b897 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CatalogServiceClient +from .async_client import CatalogServiceAsyncClient + +__all__ = ( + 'CatalogServiceClient', + 'CatalogServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py new file mode 100644 index 00000000..e828ae6f --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py @@ -0,0 +1,1352 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.catalog_service import pagers +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport +from .client import CatalogServiceClient + + +class CatalogServiceAsyncClient: + """Service for managing catalog configuration.""" + + _client: CatalogServiceClient + + DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT + + attributes_config_path = staticmethod(CatalogServiceClient.attributes_config_path) + parse_attributes_config_path = staticmethod(CatalogServiceClient.parse_attributes_config_path) + branch_path = staticmethod(CatalogServiceClient.branch_path) + parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) + catalog_path = staticmethod(CatalogServiceClient.catalog_path) + parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) + completion_config_path = staticmethod(CatalogServiceClient.completion_config_path) + parse_completion_config_path = staticmethod(CatalogServiceClient.parse_completion_config_path) + common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CatalogServiceClient.common_project_path) + parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) + common_location_path = staticmethod(CatalogServiceClient.common_location_path) + parse_common_location_path = staticmethod(CatalogServiceClient.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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CatalogServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsAsyncPager: + r"""Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_list_catalogs(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + parent (:class:`str`): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2alpha.Catalog]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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsAsyncPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.ListCatalogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_catalogs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCatalogsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_catalog(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2alpha.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2alpha.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] + method. + catalog (:class:`google.cloud.retail_v2alpha.types.Catalog`): + Required. The + [Catalog][google.cloud.retail.v2alpha.Catalog] to + update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2alpha.Catalog], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Catalog][google.cloud.retail.v2alpha.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2alpha.Catalog] to + update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_catalog, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_set_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (:class:`str`): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.SetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (:class:`str`): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # 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_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_completion_config(self, + request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Gets a + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] + method. + name (:class:`str`): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + + 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.retail_v2alpha.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetCompletionConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_completion_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_completion_config(self, + request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, + *, + completion_config: catalog.CompletionConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Updates the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + completion_config = retail_v2alpha.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2alpha.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = await client.update_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] + method. + completion_config (:class:`google.cloud.retail_v2alpha.types.CompletionConfig`): + Required. The + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``completion_config`` 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 + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([completion_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCompletionConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if completion_config is not None: + request.completion_config = completion_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_completion_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("completion_config.name", request.completion_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_attributes_config(self, + request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Gets an + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] + method. + name (:class:`str`): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + + 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.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetAttributesConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_attributes_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_attributes_config(self, + request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, + *, + attributes_config: catalog.AttributesConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Updates the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + attributes_config = retail_v2alpha.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2alpha.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = await client.update_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] + method. + attributes_config (:class:`google.cloud.retail_v2alpha.types.AttributesConfig`): + Required. The + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. + + This corresponds to the ``attributes_config`` 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 + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attributes_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateAttributesConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attributes_config is not None: + request.attributes_config = attributes_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_attributes_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config.name", request.attributes_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_catalog_attribute(self, + request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Adds the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_add_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.AddCatalogAttributeRequest(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.add_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_catalog_attribute(self, + request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Removes the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = await client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.RemoveCatalogAttributeRequest(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.remove_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def replace_catalog_attribute(self, + request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Replaces the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.ReplaceCatalogAttributeRequest(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.replace_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py new file mode 100644 index 00000000..85a7d228 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py @@ -0,0 +1,1582 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.catalog_service import pagers +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CatalogServiceGrpcTransport +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +class CatalogServiceClientMeta(type): + """Metaclass for the CatalogService 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[CatalogServiceTransport]] + _transport_registry["grpc"] = CatalogServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CatalogServiceTransport]: + """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): + """Service for managing catalog configuration.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CatalogServiceClient: 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: + CatalogServiceClient: 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) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def attributes_config_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified attributes_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_attributes_config_path(path: str) -> Dict[str,str]: + """Parses a attributes_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/attributesConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def completion_config_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified completion_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_completion_config_path(path: str) -> Dict[str,str]: + """Parses a completion_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/completionConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CatalogServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CatalogServiceTransport): + # transport is a CatalogServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsPager: + r"""Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_list_catalogs(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2alpha.Catalog]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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ListCatalogsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ListCatalogsRequest): + request = catalog_service.ListCatalogsRequest(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_catalogs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCatalogsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_catalog(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2alpha.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2alpha.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] + method. + catalog (google.cloud.retail_v2alpha.types.Catalog): + Required. The + [Catalog][google.cloud.retail.v2alpha.Catalog] to + update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2alpha.Catalog], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Catalog][google.cloud.retail.v2alpha.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2alpha.Catalog] to + update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCatalogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCatalogRequest): + request = catalog_service.UpdateCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + 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_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_set_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.SetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.SetDefaultBranchRequest): + request = catalog_service.SetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetDefaultBranchRequest): + request = catalog_service.GetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_completion_config(self, + request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Gets a + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] + method. + name (str): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + + 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.retail_v2alpha.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetCompletionConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetCompletionConfigRequest): + request = catalog_service.GetCompletionConfigRequest(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_completion_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_completion_config(self, + request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, + *, + completion_config: catalog.CompletionConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Updates the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + completion_config = retail_v2alpha.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2alpha.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = client.update_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] + method. + completion_config (google.cloud.retail_v2alpha.types.CompletionConfig): + Required. The + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``completion_config`` 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 + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([completion_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCompletionConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCompletionConfigRequest): + request = catalog_service.UpdateCompletionConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if completion_config is not None: + request.completion_config = completion_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_completion_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("completion_config.name", request.completion_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_attributes_config(self, + request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Gets an + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] + method. + name (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + + 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.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetAttributesConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetAttributesConfigRequest): + request = catalog_service.GetAttributesConfigRequest(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_attributes_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_attributes_config(self, + request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, + *, + attributes_config: catalog.AttributesConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Updates the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + attributes_config = retail_v2alpha.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2alpha.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = client.update_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] + method. + attributes_config (google.cloud.retail_v2alpha.types.AttributesConfig): + Required. The + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. + + This corresponds to the ``attributes_config`` 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 + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attributes_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateAttributesConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateAttributesConfigRequest): + request = catalog_service.UpdateAttributesConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attributes_config is not None: + request.attributes_config = attributes_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_attributes_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config.name", request.attributes_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_catalog_attribute(self, + request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Adds the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_add_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.AddCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.AddCatalogAttributeRequest): + request = catalog_service.AddCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_catalog_attribute(self, + request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Removes the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.RemoveCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.RemoveCatalogAttributeRequest): + request = catalog_service.RemoveCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def replace_catalog_attribute(self, + request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Replaces the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ReplaceCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ReplaceCatalogAttributeRequest): + request = catalog_service.ReplaceCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.replace_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py new file mode 100644 index 00000000..f78d4bfa --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog_service + + +class ListCatalogsPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` + 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[..., catalog_service.ListCatalogsResponse], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2alpha.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + for page in self.pages: + yield from page.catalogs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCatalogsAsyncPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` + 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[catalog_service.ListCatalogsResponse]], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2alpha.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + async def async_generator(): + async for page in self.pages: + for response in page.catalogs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py new file mode 100644 index 00000000..0cffa336 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 CatalogServiceTransport +from .grpc import CatalogServiceGrpcTransport +from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] +_transport_registry['grpc'] = CatalogServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport + +__all__ = ( + 'CatalogServiceTransport', + 'CatalogServiceGrpcTransport', + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py new file mode 100644 index 00000000..8a244fb4 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py @@ -0,0 +1,297 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CatalogServiceTransport(abc.ABC): + """Abstract transport class for CatalogService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_catalogs: gapic_v1.method.wrap_method( + self.list_catalogs, + default_timeout=None, + client_info=client_info, + ), + self.update_catalog: gapic_v1.method.wrap_method( + self.update_catalog, + default_timeout=None, + client_info=client_info, + ), + self.set_default_branch: gapic_v1.method.wrap_method( + self.set_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_default_branch: gapic_v1.method.wrap_method( + self.get_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_completion_config: gapic_v1.method.wrap_method( + self.get_completion_config, + default_timeout=None, + client_info=client_info, + ), + self.update_completion_config: gapic_v1.method.wrap_method( + self.update_completion_config, + default_timeout=None, + client_info=client_info, + ), + self.get_attributes_config: gapic_v1.method.wrap_method( + self.get_attributes_config, + default_timeout=None, + client_info=client_info, + ), + self.update_attributes_config: gapic_v1.method.wrap_method( + self.update_attributes_config, + default_timeout=None, + client_info=client_info, + ), + self.add_catalog_attribute: gapic_v1.method.wrap_method( + self.add_catalog_attribute, + default_timeout=None, + client_info=client_info, + ), + self.remove_catalog_attribute: gapic_v1.method.wrap_method( + self.remove_catalog_attribute, + default_timeout=None, + client_info=client_info, + ), + self.replace_catalog_attribute: gapic_v1.method.wrap_method( + self.replace_catalog_attribute, + 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Union[ + catalog_service.ListCatalogsResponse, + Awaitable[catalog_service.ListCatalogsResponse] + ]]: + raise NotImplementedError() + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Union[ + gcr_catalog.Catalog, + Awaitable[gcr_catalog.Catalog] + ]]: + raise NotImplementedError() + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Union[ + catalog_service.GetDefaultBranchResponse, + Awaitable[catalog_service.GetDefaultBranchResponse] + ]]: + raise NotImplementedError() + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + Union[ + catalog.CompletionConfig, + Awaitable[catalog.CompletionConfig] + ]]: + raise NotImplementedError() + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + Union[ + catalog.CompletionConfig, + Awaitable[catalog.CompletionConfig] + ]]: + raise NotImplementedError() + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CatalogServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py new file mode 100644 index 00000000..4ebe0ff0 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py @@ -0,0 +1,600 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO + + +class CatalogServiceGrpcTransport(CatalogServiceTransport): + """gRPC backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + catalog_service.ListCatalogsResponse]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + ~.ListCatalogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + gcr_catalog.Catalog]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + ~.Catalog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + empty_pb2.Empty]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + ~.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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + catalog_service.GetDefaultBranchResponse]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + ~.GetDefaultBranchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + catalog.CompletionConfig]: + r"""Return a callable for the get completion config method over gRPC. + + Gets a + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. + + Returns: + Callable[[~.GetCompletionConfigRequest], + ~.CompletionConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetCompletionConfig', + request_serializer=catalog_service.GetCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['get_completion_config'] + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + catalog.CompletionConfig]: + r"""Return a callable for the update completion config method over gRPC. + + Updates the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. + + Returns: + Callable[[~.UpdateCompletionConfigRequest], + ~.CompletionConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateCompletionConfig', + request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['update_completion_config'] + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + catalog.AttributesConfig]: + r"""Return a callable for the get attributes config method over gRPC. + + Gets an + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + Returns: + Callable[[~.GetAttributesConfigRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetAttributesConfig', + request_serializer=catalog_service.GetAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['get_attributes_config'] + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + catalog.AttributesConfig]: + r"""Return a callable for the update attributes config method over gRPC. + + Updates the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + Returns: + Callable[[~.UpdateAttributesConfigRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateAttributesConfig', + request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['update_attributes_config'] + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the add catalog attribute method over gRPC. + + Adds the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.AddCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_catalog_attribute' not in self._stubs: + self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/AddCatalogAttribute', + request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['add_catalog_attribute'] + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the remove catalog attribute method over gRPC. + + Removes the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.RemoveCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_catalog_attribute' not in self._stubs: + self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/RemoveCatalogAttribute', + request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['remove_catalog_attribute'] + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the replace catalog attribute method over gRPC. + + Replaces the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.ReplaceCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_catalog_attribute' not in self._stubs: + self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/ReplaceCatalogAttribute', + request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['replace_catalog_attribute'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CatalogServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..15eacf16 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py @@ -0,0 +1,599 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CatalogServiceGrpcTransport + + +class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): + """gRPC AsyncIO backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Awaitable[catalog_service.ListCatalogsResponse]]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + Awaitable[~.ListCatalogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Awaitable[gcr_catalog.Catalog]]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + Awaitable[~.Catalog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + 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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Awaitable[catalog_service.GetDefaultBranchResponse]]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + Awaitable[~.GetDefaultBranchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + Awaitable[catalog.CompletionConfig]]: + r"""Return a callable for the get completion config method over gRPC. + + Gets a + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. + + Returns: + Callable[[~.GetCompletionConfigRequest], + Awaitable[~.CompletionConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetCompletionConfig', + request_serializer=catalog_service.GetCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['get_completion_config'] + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + Awaitable[catalog.CompletionConfig]]: + r"""Return a callable for the update completion config method over gRPC. + + Updates the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. + + Returns: + Callable[[~.UpdateCompletionConfigRequest], + Awaitable[~.CompletionConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateCompletionConfig', + request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['update_completion_config'] + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the get attributes config method over gRPC. + + Gets an + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + Returns: + Callable[[~.GetAttributesConfigRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/GetAttributesConfig', + request_serializer=catalog_service.GetAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['get_attributes_config'] + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the update attributes config method over gRPC. + + Updates the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + Returns: + Callable[[~.UpdateAttributesConfigRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/UpdateAttributesConfig', + request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['update_attributes_config'] + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the add catalog attribute method over gRPC. + + Adds the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.AddCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_catalog_attribute' not in self._stubs: + self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/AddCatalogAttribute', + request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['add_catalog_attribute'] + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the remove catalog attribute method over gRPC. + + Removes the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.RemoveCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_catalog_attribute' not in self._stubs: + self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/RemoveCatalogAttribute', + request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['remove_catalog_attribute'] + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the replace catalog attribute method over gRPC. + + Replaces the specified + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.ReplaceCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_catalog_attribute' not in self._stubs: + self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CatalogService/ReplaceCatalogAttribute', + request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['replace_catalog_attribute'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py new file mode 100644 index 00000000..b8af95bd --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CompletionServiceClient +from .async_client import CompletionServiceAsyncClient + +__all__ = ( + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py new file mode 100644 index 00000000..74888568 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .client import CompletionServiceClient + + +class CompletionServiceAsyncClient: + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: CompletionServiceClient + + DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(CompletionServiceClient.catalog_path) + parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) + common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CompletionServiceClient.common_project_path) + parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) + common_location_path = staticmethod(CompletionServiceClient.common_location_path) + parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CompletionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_complete_query(): + # Create a client + client = retail_v2alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_query, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_import_completion_data(): + # Create a client + client = retail_v2alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2alpha.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. + 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. + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_completion_data, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py new file mode 100644 index 00000000..6e783e95 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CompletionServiceGrpcTransport +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +class CompletionServiceClientMeta(type): + """Metaclass for the CompletionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] + _transport_registry["grpc"] = CompletionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CompletionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CompletionServiceClient(metaclass=CompletionServiceClientMeta): + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CompletionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CompletionServiceTransport): + # transport is a CompletionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_complete_query(): + # Create a client + client = retail_v2alpha.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a completion_service.CompleteQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, completion_service.CompleteQueryRequest): + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_import_completion_data(): + # Create a client + client = retail_v2alpha.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2alpha.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. + 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. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportCompletionDataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportCompletionDataRequest): + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_completion_data] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py new file mode 100644 index 00000000..a0c9542f --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CompletionServiceTransport +from .grpc import CompletionServiceGrpcTransport +from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] +_transport_registry['grpc'] = CompletionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport + +__all__ = ( + 'CompletionServiceTransport', + 'CompletionServiceGrpcTransport', + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py new file mode 100644 index 00000000..2e16e808 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CompletionServiceTransport(abc.ABC): + """Abstract transport class for CompletionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.complete_query: gapic_v1.method.wrap_method( + self.complete_query, + default_timeout=None, + client_info=client_info, + ), + self.import_completion_data: gapic_v1.method.wrap_method( + self.import_completion_data, + 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Union[ + completion_service.CompleteQueryResponse, + Awaitable[completion_service.CompleteQueryResponse] + ]]: + raise NotImplementedError() + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CompletionServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py new file mode 100644 index 00000000..dd953c63 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py @@ -0,0 +1,325 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO + + +class CompletionServiceGrpcTransport(CompletionServiceTransport): + """gRPC backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + ~.CompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + operations_pb2.Operation]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CompletionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..726b0e6e --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py @@ -0,0 +1,324 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CompletionServiceGrpcTransport + + +class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): + """gRPC AsyncIO backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Awaitable[completion_service.CompleteQueryResponse]]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + Awaitable[~.CompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + 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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py new file mode 100644 index 00000000..e9a7be2f --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ControlServiceClient +from .async_client import ControlServiceAsyncClient + +__all__ = ( + 'ControlServiceClient', + 'ControlServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py new file mode 100644 index 00000000..e32d838b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py @@ -0,0 +1,744 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.control_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.cloud.retail_v2alpha.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport +from .client import ControlServiceClient + + +class ControlServiceAsyncClient: + """Service for modifying Control.""" + + _client: ControlServiceClient + + DEFAULT_ENDPOINT = ControlServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ControlServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(ControlServiceClient.catalog_path) + parse_catalog_path = staticmethod(ControlServiceClient.parse_catalog_path) + control_path = staticmethod(ControlServiceClient.control_path) + parse_control_path = staticmethod(ControlServiceClient.parse_control_path) + common_billing_account_path = staticmethod(ControlServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ControlServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ControlServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ControlServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ControlServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ControlServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ControlServiceClient.common_project_path) + parse_common_project_path = staticmethod(ControlServiceClient.parse_common_project_path) + common_location_path = staticmethod(ControlServiceClient.common_location_path) + parse_common_location_path = staticmethod(ControlServiceClient.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: + ControlServiceAsyncClient: The constructed client. + """ + return ControlServiceClient.from_service_account_info.__func__(ControlServiceAsyncClient, 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: + ControlServiceAsyncClient: The constructed client. + """ + return ControlServiceClient.from_service_account_file.__func__(ControlServiceAsyncClient, 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 variabel 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 ControlServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ControlServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ControlServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ControlServiceClient).get_transport_class, type(ControlServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ControlServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the control service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ControlServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ControlServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_control(self, + request: Union[control_service.CreateControlRequest, dict] = None, + *, + parent: str = None, + control: gcr_control.Control = None, + control_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Creates a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_create_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = await client.create_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateControlRequest, dict]): + The request object. Request for CreateControl method. + parent (:class:`str`): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control (:class:`google.cloud.retail_v2alpha.types.Control`): + Required. The Control to create. + This corresponds to the ``control`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control_id (:class:`str`): + Required. The ID to use for the Control, which will + become the final component of the Control's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``control_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.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, control, control_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.CreateControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if control is not None: + request.control = control + if control_id is not None: + request.control_id = control_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_control(self, + request: Union[control_service.DeleteControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_delete_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteControlRequest( + name="name_value", + ) + + # Make the request + await client.delete_control(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteControlRequest, dict]): + The request object. Request for DeleteControl method. + name (:class:`str`): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.DeleteControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_control(self, + request: Union[control_service.UpdateControlRequest, dict] = None, + *, + control: gcr_control.Control = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Updates a Control. + + [Control][google.cloud.retail.v2alpha.Control] cannot be set to + a different oneof field, if so an INVALID_ARGUMENT is returned. + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.UpdateControlRequest( + control=control, + ) + + # Make the request + response = await client.update_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateControlRequest, dict]): + The request object. Request for UpdateControl method. + control (:class:`google.cloud.retail_v2alpha.types.Control`): + Required. The Control to update. + This corresponds to the ``control`` 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 + [Control][google.cloud.retail.v2alpha.Control] to + update. The following are NOT supported: + + - [Control.name][google.cloud.retail.v2alpha.Control.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([control, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.UpdateControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if control is not None: + request.control = control + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("control.name", request.control.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_control(self, + request: Union[control_service.GetControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> control.Control: + r"""Gets a Control. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetControlRequest( + name="name_value", + ) + + # Make the request + response = await client.get_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetControlRequest, dict]): + The request object. Request for GetControl method. + name (:class:`str`): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.GetControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_controls(self, + request: Union[control_service.ListControlsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListControlsAsyncPager: + r"""Lists all Controls linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_list_controls(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListControlsRequest, dict]): + The request object. Request for ListControls method. + parent (:class:`str`): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.control_service.pagers.ListControlsAsyncPager: + Response for ListControls method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.ListControlsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_controls, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListControlsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ControlServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py new file mode 100644 index 00000000..0981fa86 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py @@ -0,0 +1,953 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.control_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.cloud.retail_v2alpha.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ControlServiceGrpcTransport +from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport + + +class ControlServiceClientMeta(type): + """Metaclass for the ControlService 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[ControlServiceTransport]] + _transport_registry["grpc"] = ControlServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ControlServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ControlServiceTransport]: + """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 ControlServiceClient(metaclass=ControlServiceClientMeta): + """Service for modifying Control.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ControlServiceClient: 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: + ControlServiceClient: 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) -> ControlServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ControlServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def control_path(project: str,location: str,catalog: str,control: str,) -> str: + """Returns a fully-qualified control string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) + + @staticmethod + def parse_control_path(path: str) -> Dict[str,str]: + """Parses a control path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/controls/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ControlServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the control service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ControlServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ControlServiceTransport): + # transport is a ControlServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_control(self, + request: Union[control_service.CreateControlRequest, dict] = None, + *, + parent: str = None, + control: gcr_control.Control = None, + control_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Creates a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_create_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = client.create_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateControlRequest, dict]): + The request object. Request for CreateControl method. + parent (str): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control (google.cloud.retail_v2alpha.types.Control): + Required. The Control to create. + This corresponds to the ``control`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control_id (str): + Required. The ID to use for the Control, which will + become the final component of the Control's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``control_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.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, control, control_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.CreateControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.CreateControlRequest): + request = control_service.CreateControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if control is not None: + request.control = control + if control_id is not None: + request.control_id = control_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_control(self, + request: Union[control_service.DeleteControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_delete_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteControlRequest( + name="name_value", + ) + + # Make the request + client.delete_control(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteControlRequest, dict]): + The request object. Request for DeleteControl method. + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.DeleteControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.DeleteControlRequest): + request = control_service.DeleteControlRequest(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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_control(self, + request: Union[control_service.UpdateControlRequest, dict] = None, + *, + control: gcr_control.Control = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Updates a Control. + + [Control][google.cloud.retail.v2alpha.Control] cannot be set to + a different oneof field, if so an INVALID_ARGUMENT is returned. + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.UpdateControlRequest( + control=control, + ) + + # Make the request + response = client.update_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateControlRequest, dict]): + The request object. Request for UpdateControl method. + control (google.cloud.retail_v2alpha.types.Control): + Required. The Control to update. + This corresponds to the ``control`` 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 + [Control][google.cloud.retail.v2alpha.Control] to + update. The following are NOT supported: + + - [Control.name][google.cloud.retail.v2alpha.Control.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([control, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.UpdateControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.UpdateControlRequest): + request = control_service.UpdateControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if control is not None: + request.control = control + 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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("control.name", request.control.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_control(self, + request: Union[control_service.GetControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> control.Control: + r"""Gets a Control. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetControlRequest( + name="name_value", + ) + + # Make the request + response = client.get_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetControlRequest, dict]): + The request object. Request for GetControl method. + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.GetControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.GetControlRequest): + request = control_service.GetControlRequest(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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_controls(self, + request: Union[control_service.ListControlsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListControlsPager: + r"""Lists all Controls linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_list_controls(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListControlsRequest, dict]): + The request object. Request for ListControls method. + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.control_service.pagers.ListControlsPager: + Response for ListControls method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.ListControlsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.ListControlsRequest): + request = control_service.ListControlsRequest(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_controls] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListControlsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ControlServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py new file mode 100644 index 00000000..d1c28748 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control_service + + +class ListControlsPager: + """A pager for iterating through ``list_controls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``controls`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListControls`` requests and continue to iterate + through the ``controls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` + 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[..., control_service.ListControlsResponse], + request: control_service.ListControlsRequest, + response: control_service.ListControlsResponse, + *, + 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.retail_v2alpha.types.ListControlsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListControlsResponse): + 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 = control_service.ListControlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[control_service.ListControlsResponse]: + 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[control.Control]: + for page in self.pages: + yield from page.controls + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListControlsAsyncPager: + """A pager for iterating through ``list_controls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``controls`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListControls`` requests and continue to iterate + through the ``controls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` + 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[control_service.ListControlsResponse]], + request: control_service.ListControlsRequest, + response: control_service.ListControlsResponse, + *, + 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.retail_v2alpha.types.ListControlsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListControlsResponse): + 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 = control_service.ListControlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[control_service.ListControlsResponse]: + 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[control.Control]: + async def async_generator(): + async for page in self.pages: + for response in page.controls: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py new file mode 100644 index 00000000..3622876b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ControlServiceTransport +from .grpc import ControlServiceGrpcTransport +from .grpc_asyncio import ControlServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ControlServiceTransport]] +_transport_registry['grpc'] = ControlServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ControlServiceGrpcAsyncIOTransport + +__all__ = ( + 'ControlServiceTransport', + 'ControlServiceGrpcTransport', + 'ControlServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py new file mode 100644 index 00000000..ef91c3df --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ControlServiceTransport(abc.ABC): + """Abstract transport class for ControlService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_control: gapic_v1.method.wrap_method( + self.create_control, + default_timeout=None, + client_info=client_info, + ), + self.delete_control: gapic_v1.method.wrap_method( + self.delete_control, + default_timeout=None, + client_info=client_info, + ), + self.update_control: gapic_v1.method.wrap_method( + self.update_control, + default_timeout=None, + client_info=client_info, + ), + self.get_control: gapic_v1.method.wrap_method( + self.get_control, + default_timeout=None, + client_info=client_info, + ), + self.list_controls: gapic_v1.method.wrap_method( + self.list_controls, + 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 create_control(self) -> Callable[ + [control_service.CreateControlRequest], + Union[ + gcr_control.Control, + Awaitable[gcr_control.Control] + ]]: + raise NotImplementedError() + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + Union[ + gcr_control.Control, + Awaitable[gcr_control.Control] + ]]: + raise NotImplementedError() + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + Union[ + control.Control, + Awaitable[control.Control] + ]]: + raise NotImplementedError() + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + Union[ + control_service.ListControlsResponse, + Awaitable[control_service.ListControlsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ControlServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py new file mode 100644 index 00000000..121caf7d --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py @@ -0,0 +1,382 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO + + +class ControlServiceGrpcTransport(ControlServiceTransport): + """gRPC backend transport for ControlService. + + Service for modifying Control. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_control(self) -> Callable[ + [control_service.CreateControlRequest], + gcr_control.Control]: + r"""Return a callable for the create control method over gRPC. + + Creates a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['create_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/CreateControl', + request_serializer=control_service.CreateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['create_control'] + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete control method over gRPC. + + Deletes a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteControlRequest], + ~.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_control' not in self._stubs: + self._stubs['delete_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/DeleteControl', + request_serializer=control_service.DeleteControlRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_control'] + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + gcr_control.Control]: + r"""Return a callable for the update control method over gRPC. + + Updates a Control. + + [Control][google.cloud.retail.v2alpha.Control] cannot be set to + a different oneof field, if so an INVALID_ARGUMENT is returned. + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['update_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/UpdateControl', + request_serializer=control_service.UpdateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['update_control'] + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + control.Control]: + r"""Return a callable for the get control method over gRPC. + + Gets a Control. + + Returns: + Callable[[~.GetControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['get_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/GetControl', + request_serializer=control_service.GetControlRequest.serialize, + response_deserializer=control.Control.deserialize, + ) + return self._stubs['get_control'] + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + control_service.ListControlsResponse]: + r"""Return a callable for the list controls method over gRPC. + + Lists all Controls linked to this catalog. + + Returns: + Callable[[~.ListControlsRequest], + ~.ListControlsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_controls' not in self._stubs: + self._stubs['list_controls'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/ListControls', + request_serializer=control_service.ListControlsRequest.serialize, + response_deserializer=control_service.ListControlsResponse.deserialize, + ) + return self._stubs['list_controls'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ControlServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..9703924c --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ControlServiceGrpcTransport + + +class ControlServiceGrpcAsyncIOTransport(ControlServiceTransport): + """gRPC AsyncIO backend transport for ControlService. + + Service for modifying Control. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_control(self) -> Callable[ + [control_service.CreateControlRequest], + Awaitable[gcr_control.Control]]: + r"""Return a callable for the create control method over gRPC. + + Creates a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['create_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/CreateControl', + request_serializer=control_service.CreateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['create_control'] + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete control method over gRPC. + + Deletes a Control. + + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteControlRequest], + 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_control' not in self._stubs: + self._stubs['delete_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/DeleteControl', + request_serializer=control_service.DeleteControlRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_control'] + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + Awaitable[gcr_control.Control]]: + r"""Return a callable for the update control method over gRPC. + + Updates a Control. + + [Control][google.cloud.retail.v2alpha.Control] cannot be set to + a different oneof field, if so an INVALID_ARGUMENT is returned. + If the [Control][google.cloud.retail.v2alpha.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['update_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/UpdateControl', + request_serializer=control_service.UpdateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['update_control'] + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + Awaitable[control.Control]]: + r"""Return a callable for the get control method over gRPC. + + Gets a Control. + + Returns: + Callable[[~.GetControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['get_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/GetControl', + request_serializer=control_service.GetControlRequest.serialize, + response_deserializer=control.Control.deserialize, + ) + return self._stubs['get_control'] + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + Awaitable[control_service.ListControlsResponse]]: + r"""Return a callable for the list controls method over gRPC. + + Lists all Controls linked to this catalog. + + Returns: + Callable[[~.ListControlsRequest], + Awaitable[~.ListControlsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_controls' not in self._stubs: + self._stubs['list_controls'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ControlService/ListControls', + request_serializer=control_service.ListControlsRequest.serialize, + response_deserializer=control_service.ListControlsResponse.deserialize, + ) + return self._stubs['list_controls'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ControlServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py new file mode 100644 index 00000000..7c079c80 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import PredictionServiceClient +from .async_client import PredictionServiceAsyncClient + +__all__ = ( + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py new file mode 100644 index 00000000..b9255f77 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport +from .client import PredictionServiceClient + + +class PredictionServiceAsyncClient: + """Service for making recommendation prediction.""" + + _client: PredictionServiceClient + + DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT + + product_path = staticmethod(PredictionServiceClient.product_path) + parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) + common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(PredictionServiceClient.common_project_path) + parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) + common_location_path = staticmethod(PredictionServiceClient.common_location_path) + parse_common_location_path = staticmethod(PredictionServiceClient.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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PredictionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_predict(): + # Create a client + client = retail_v2alpha.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + request = prediction_service.PredictRequest(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.predict, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py new file mode 100644 index 00000000..1cb0e419 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py @@ -0,0 +1,480 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionServiceGrpcTransport +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +class PredictionServiceClientMeta(type): + """Metaclass for the PredictionService 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[PredictionServiceTransport]] + _transport_registry["grpc"] = PredictionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PredictionServiceTransport]: + """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): + """Service for making recommendation prediction.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PredictionServiceClient: 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: + PredictionServiceClient: 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) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PredictionServiceTransport): + # transport is a PredictionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_predict(): + # Create a client + client = retail_v2alpha.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a prediction_service.PredictRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_service.PredictRequest): + request = prediction_service.PredictRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.predict] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py new file mode 100644 index 00000000..bb65c664 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PredictionServiceTransport +from .grpc import PredictionServiceGrpcTransport +from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] +_transport_registry['grpc'] = PredictionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport + +__all__ = ( + 'PredictionServiceTransport', + 'PredictionServiceGrpcTransport', + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py new file mode 100644 index 00000000..a5424c9e --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PredictionServiceTransport(abc.ABC): + """Abstract transport class for PredictionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.predict: gapic_v1.method.wrap_method( + self.predict, + 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + Union[ + prediction_service.PredictResponse, + Awaitable[prediction_service.PredictResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'PredictionServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py new file mode 100644 index 00000000..0e227d35 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py @@ -0,0 +1,264 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO + + +class PredictionServiceGrpcTransport(PredictionServiceTransport): + """gRPC backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + prediction_service.PredictResponse]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + ~.PredictResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'PredictionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..26a9ecfc --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import PredictionServiceGrpcTransport + + +class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): + """gRPC AsyncIO backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + Awaitable[prediction_service.PredictResponse]]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + Awaitable[~.PredictResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py new file mode 100644 index 00000000..0fa6330a --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ProductServiceClient +from .async_client import ProductServiceAsyncClient + +__all__ = ( + 'ProductServiceClient', + 'ProductServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py new file mode 100644 index 00000000..2933dcb8 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py @@ -0,0 +1,1804 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.services.product_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import purge_config +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport +from .client import ProductServiceClient + + +class ProductServiceAsyncClient: + """Service for ingesting [Product][google.cloud.retail.v2alpha.Product] + information of the customer's website. + """ + + _client: ProductServiceClient + + DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(ProductServiceClient.branch_path) + parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) + product_path = staticmethod(ProductServiceClient.product_path) + parse_product_path = staticmethod(ProductServiceClient.parse_product_path) + common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProductServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProductServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProductServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProductServiceClient.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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ProductServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ProductServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_create_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`google.cloud.retail_v2alpha.types.Product`): + Required. The + [Product][google.cloud.retail.v2alpha.Product] to + create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + Required. The ID to use for the + [Product][google.cloud.retail.v2alpha.Product], which + will become the final component of the + [Product.name][google.cloud.retail.v2alpha.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This field must be unique among all + [Product][google.cloud.retail.v2alpha.Product]s with the + same + [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Product][google.cloud.retail.v2alpha.Product] 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.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_list_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2alpha.Product]s under + this branch, regardless of whether or not this branch + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.product_service.pagers.ListProductsAsyncPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (:class:`google.cloud.retail_v2alpha.types.Product`): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2alpha.Product] to + update. The immutable and output only fields are NOT + supported. If not set, all supported fields (the fields + that are neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_delete_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2alpha.Product] to + delete can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product] member + nor a + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] with more + than one + [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2alpha.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def purge_products(self, + request: Union[purge_config.PurgeProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Permanently deletes all selected + [Product][google.cloud.retail.v2alpha.Product]s under a branch. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed offline. Depending on the + number of [Product][google.cloud.retail.v2alpha.Product]s, this + operation could take hours to complete. Before the operation + completes, some [Product][google.cloud.retail.v2alpha.Product]s + may still be returned by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Depending on the number of + [Product][google.cloud.retail.v2alpha.Product]s, this operation + could take hours to complete. To get a sample of + [Product][google.cloud.retail.v2alpha.Product]s that would be + deleted, set + [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] + to false. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_purge_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeProductsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PurgeProductsRequest, dict]): + The request object. Request message for PurgeProducts + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.PurgeProductsResponse` Response of the PurgeProductsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeProductsResponse, + metadata_type=purge_config.PurgeProductsMetadata, + ) + + # Done; return the response. + return response + + async def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2alpha.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2alpha.Product]s to be + successfully updated. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_import_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2alpha.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2alpha.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_set_inventory(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2alpha.Product() + inventory.title = "title_value" + + request = retail_v2alpha.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (:class:`google.cloud.retail_v2alpha.types.Product`): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product] named in + [Product.name][google.cloud.retail.v2alpha.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2alpha.Product] to + update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.SetInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_inventory, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + async def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [AddFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_add_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [AddLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_remove_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py new file mode 100644 index 00000000..6206989b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py @@ -0,0 +1,2008 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.services.product_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import purge_config +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductServiceGrpcTransport +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +class ProductServiceClientMeta(type): + """Metaclass for the ProductService 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[ProductServiceTransport]] + _transport_registry["grpc"] = ProductServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ProductServiceTransport]: + """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 ProductServiceClient(metaclass=ProductServiceClientMeta): + """Service for ingesting [Product][google.cloud.retail.v2alpha.Product] + information of the customer's website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProductServiceClient: 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: + ProductServiceClient: 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) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ProductServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProductServiceTransport): + # transport is a ProductServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_create_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (google.cloud.retail_v2alpha.types.Product): + Required. The + [Product][google.cloud.retail.v2alpha.Product] to + create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2alpha.Product], which + will become the final component of the + [Product.name][google.cloud.retail.v2alpha.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This field must be unique among all + [Product][google.cloud.retail.v2alpha.Product]s with the + same + [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.CreateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.CreateProductRequest): + request = product_service.CreateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Product][google.cloud.retail.v2alpha.Product] 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.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.GetProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.GetProductRequest): + request = product_service.GetProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_list_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2alpha.Product]s under + this branch, regardless of whether or not this branch + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.product_service.pagers.ListProductsPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.ListProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.ListProductsRequest): + request = product_service.ListProductsRequest(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_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (google.cloud.retail_v2alpha.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2alpha.Product] to + update. The immutable and output only fields are NOT + supported. If not set, all supported fields (the fields + that are neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.UpdateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.UpdateProductRequest): + request = product_service.UpdateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + 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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2alpha.Product]. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_delete_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2alpha.Product] to + delete can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product] member + nor a + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] with more + than one + [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2alpha.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.DeleteProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.DeleteProductRequest): + request = product_service.DeleteProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def purge_products(self, + request: Union[purge_config.PurgeProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Permanently deletes all selected + [Product][google.cloud.retail.v2alpha.Product]s under a branch. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed offline. Depending on the + number of [Product][google.cloud.retail.v2alpha.Product]s, this + operation could take hours to complete. Before the operation + completes, some [Product][google.cloud.retail.v2alpha.Product]s + may still be returned by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Depending on the number of + [Product][google.cloud.retail.v2alpha.Product]s, this operation + could take hours to complete. To get a sample of + [Product][google.cloud.retail.v2alpha.Product]s that would be + deleted, set + [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] + to false. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_purge_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeProductsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PurgeProductsRequest, dict]): + The request object. Request message for PurgeProducts + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.PurgeProductsResponse` Response of the PurgeProductsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeProductsRequest): + request = purge_config.PurgeProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeProductsResponse, + metadata_type=purge_config.PurgeProductsMetadata, + ) + + # Done; return the response. + return response + + def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2alpha.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2alpha.Product]s to be + successfully updated. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_import_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2alpha.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportProductsRequest): + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2alpha.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_set_inventory(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2alpha.Product() + inventory.title = "title_value" + + request = retail_v2alpha.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (google.cloud.retail_v2alpha.types.Product): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product] named in + [Product.name][google.cloud.retail.v2alpha.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2alpha.Product] to + update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.SetInventoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.SetInventoryRequest): + request = product_service.SetInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_add_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [AddFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddFulfillmentPlacesRequest): + request = product_service.AddFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): + request = product_service.RemoveFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_add_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [AddLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddLocalInventoriesRequest): + request = product_service.AddLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_remove_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveLocalInventoriesRequest): + request = product_service.RemoveLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py new file mode 100644 index 00000000..5e235009 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product_service + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` + 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[..., product_service.ListProductsResponse], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2alpha.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[product_service.ListProductsResponse]: + 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[product.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` + 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[product_service.ListProductsResponse]], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2alpha.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: + 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[product.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py new file mode 100644 index 00000000..db824dec --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ProductServiceTransport +from .grpc import ProductServiceGrpcTransport +from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] +_transport_registry['grpc'] = ProductServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport + +__all__ = ( + 'ProductServiceTransport', + 'ProductServiceGrpcTransport', + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py new file mode 100644 index 00000000..fe69ccf2 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import purge_config +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ProductServiceTransport(abc.ABC): + """Abstract transport class for ProductService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_product: gapic_v1.method.wrap_method( + self.create_product, + default_timeout=None, + client_info=client_info, + ), + self.get_product: gapic_v1.method.wrap_method( + self.get_product, + default_timeout=None, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + default_timeout=None, + client_info=client_info, + ), + self.update_product: gapic_v1.method.wrap_method( + self.update_product, + default_timeout=None, + client_info=client_info, + ), + self.delete_product: gapic_v1.method.wrap_method( + self.delete_product, + default_timeout=None, + client_info=client_info, + ), + self.purge_products: gapic_v1.method.wrap_method( + self.purge_products, + default_timeout=None, + client_info=client_info, + ), + self.import_products: gapic_v1.method.wrap_method( + self.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.set_inventory: gapic_v1.method.wrap_method( + self.set_inventory, + default_timeout=None, + client_info=client_info, + ), + self.add_fulfillment_places: gapic_v1.method.wrap_method( + self.add_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.remove_fulfillment_places: gapic_v1.method.wrap_method( + self.remove_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.add_local_inventories: gapic_v1.method.wrap_method( + self.add_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.remove_local_inventories: gapic_v1.method.wrap_method( + self.remove_local_inventories, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Union[ + product.Product, + Awaitable[product.Product] + ]]: + raise NotImplementedError() + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Union[ + product_service.ListProductsResponse, + Awaitable[product_service.ListProductsResponse] + ]]: + raise NotImplementedError() + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def purge_products(self) -> Callable[ + [purge_config.PurgeProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProductServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py new file mode 100644 index 00000000..72a1777c --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py @@ -0,0 +1,726 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import purge_config +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO + + +class ProductServiceGrpcTransport(ProductServiceTransport): + """gRPC backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2alpha.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + gcr_product.Product]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.CreateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + product.Product]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + product_service.ListProductsResponse]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + gcr_product.Product]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + ~.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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def purge_products(self) -> Callable[ + [purge_config.PurgeProductsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge products method over gRPC. + + Permanently deletes all selected + [Product][google.cloud.retail.v2alpha.Product]s under a branch. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed offline. Depending on the + number of [Product][google.cloud.retail.v2alpha.Product]s, this + operation could take hours to complete. Before the operation + completes, some [Product][google.cloud.retail.v2alpha.Product]s + may still be returned by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Depending on the number of + [Product][google.cloud.retail.v2alpha.Product]s, this operation + could take hours to complete. To get a sample of + [Product][google.cloud.retail.v2alpha.Product]s that would be + deleted, set + [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] + to false. + + Returns: + Callable[[~.PurgeProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_products' not in self._stubs: + self._stubs['purge_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/PurgeProducts', + request_serializer=purge_config.PurgeProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_products'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2alpha.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2alpha.Product]s to be + successfully updated. + + Returns: + Callable[[~.ImportProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + operations_pb2.Operation]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2alpha.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProductServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..f130d491 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py @@ -0,0 +1,725 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import purge_config +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductServiceGrpcTransport + + +class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): + """gRPC AsyncIO backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2alpha.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.CreateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Awaitable[product.Product]]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Awaitable[product_service.ListProductsResponse]]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2alpha.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + 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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def purge_products(self) -> Callable[ + [purge_config.PurgeProductsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge products method over gRPC. + + Permanently deletes all selected + [Product][google.cloud.retail.v2alpha.Product]s under a branch. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed offline. Depending on the + number of [Product][google.cloud.retail.v2alpha.Product]s, this + operation could take hours to complete. Before the operation + completes, some [Product][google.cloud.retail.v2alpha.Product]s + may still be returned by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Depending on the number of + [Product][google.cloud.retail.v2alpha.Product]s, this operation + could take hours to complete. To get a sample of + [Product][google.cloud.retail.v2alpha.Product]s that would be + deleted, set + [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] + to false. + + Returns: + Callable[[~.PurgeProductsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_products' not in self._stubs: + self._stubs['purge_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/PurgeProducts', + request_serializer=purge_config.PurgeProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_products'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2alpha.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2alpha.Product]s to be + successfully updated. + + Returns: + Callable[[~.ImportProductsRequest], + 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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2alpha.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + 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 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + 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 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2alpha.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + 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 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2alpha.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2alpha.Product] queried by + [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + 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 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py new file mode 100644 index 00000000..2f63fc22 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SearchServiceClient +from .async_client import SearchServiceAsyncClient + +__all__ = ( + 'SearchServiceClient', + 'SearchServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py new file mode 100644 index 00000000..d39b3203 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.search_service import pagers +from google.cloud.retail_v2alpha.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .client import SearchServiceClient + + +class SearchServiceAsyncClient: + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: SearchServiceClient + + DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(SearchServiceClient.branch_path) + parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + product_path = staticmethod(SearchServiceClient.product_path) + parse_product_path = staticmethod(SearchServiceClient.parse_product_path) + common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(SearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SearchServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAsyncPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_search(): + # Create a client + client = retail_v2alpha.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.search_service.pagers.SearchAsyncPager: + Response message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py new file mode 100644 index 00000000..4786889b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py @@ -0,0 +1,513 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.search_service import pagers +from google.cloud.retail_v2alpha.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SearchServiceGrpcTransport +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +class SearchServiceClientMeta(type): + """Metaclass for the SearchService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] + _transport_registry["grpc"] = SearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SearchServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SearchServiceClient(metaclass=SearchServiceClientMeta): + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SearchServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SearchServiceTransport): + # transport is a SearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_search(): + # Create a client + client = retail_v2alpha.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.search_service.pagers.SearchPager: + Response message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a search_service.SearchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py new file mode 100644 index 00000000..7487beee --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import search_service + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2alpha.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2alpha.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py new file mode 100644 index 00000000..7917cd1d --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SearchServiceTransport +from .grpc import SearchServiceGrpcTransport +from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] +_transport_registry['grpc'] = SearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport + +__all__ = ( + 'SearchServiceTransport', + 'SearchServiceGrpcTransport', + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py new file mode 100644 index 00000000..f986834a --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import search_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SearchServiceTransport(abc.ABC): + """Abstract transport class for SearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search: gapic_v1.method.wrap_method( + self.search, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Union[ + search_service.SearchResponse, + Awaitable[search_service.SearchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SearchServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py new file mode 100644 index 00000000..04e76b79 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py @@ -0,0 +1,270 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO + + +class SearchServiceGrpcTransport(SearchServiceTransport): + """gRPC backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..26b52d69 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SearchServiceGrpcTransport + + +class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): + """gRPC AsyncIO backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Awaitable[search_service.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py new file mode 100644 index 00000000..d1a0a023 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ServingConfigServiceClient +from .async_client import ServingConfigServiceAsyncClient + +__all__ = ( + 'ServingConfigServiceClient', + 'ServingConfigServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py new file mode 100644 index 00000000..4f047853 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py @@ -0,0 +1,954 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.serving_config_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport +from .client import ServingConfigServiceClient + + +class ServingConfigServiceAsyncClient: + """Service for modifying ServingConfig.""" + + _client: ServingConfigServiceClient + + DEFAULT_ENDPOINT = ServingConfigServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ServingConfigServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(ServingConfigServiceClient.catalog_path) + parse_catalog_path = staticmethod(ServingConfigServiceClient.parse_catalog_path) + serving_config_path = staticmethod(ServingConfigServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(ServingConfigServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(ServingConfigServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ServingConfigServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ServingConfigServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ServingConfigServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ServingConfigServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ServingConfigServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ServingConfigServiceClient.common_project_path) + parse_common_project_path = staticmethod(ServingConfigServiceClient.parse_common_project_path) + common_location_path = staticmethod(ServingConfigServiceClient.common_location_path) + parse_common_location_path = staticmethod(ServingConfigServiceClient.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: + ServingConfigServiceAsyncClient: The constructed client. + """ + return ServingConfigServiceClient.from_service_account_info.__func__(ServingConfigServiceAsyncClient, 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: + ServingConfigServiceAsyncClient: The constructed client. + """ + return ServingConfigServiceClient.from_service_account_file.__func__(ServingConfigServiceAsyncClient, 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 variabel 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 ServingConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ServingConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ServingConfigServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ServingConfigServiceClient).get_transport_class, type(ServingConfigServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ServingConfigServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the serving config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ServingConfigServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ServingConfigServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_serving_config(self, + request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, + *, + parent: str = None, + serving_config: gcr_serving_config.ServingConfig = None, + serving_config_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_create_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = await client.create_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateServingConfigRequest, dict]): + The request object. Request for CreateServingConfig + method. + parent (:class:`str`): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config (:class:`google.cloud.retail_v2alpha.types.ServingConfig`): + Required. The ServingConfig to + create. + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config_id (:class:`str`): + Required. The ID to use for the ServingConfig, which + will become the final component of the ServingConfig's + resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``serving_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, serving_config, serving_config_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.CreateServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if serving_config is not None: + request.serving_config = serving_config + if serving_config_id is not None: + request.serving_config_id = serving_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_serving_config(self, + request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_delete_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_serving_config(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteServingConfigRequest, dict]): + The request object. Request for DeleteServingConfig + method. + name (:class:`str`): + Required. The resource name of the ServingConfig to + delete. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.DeleteServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_serving_config(self, + request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, + *, + serving_config: gcr_serving_config.ServingConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Updates a ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_update_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = await client.update_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateServingConfigRequest, dict]): + The request object. Request for UpdateServingConfig + method. + serving_config (:class:`google.cloud.retail_v2alpha.types.ServingConfig`): + Required. The ServingConfig to + update. + + This corresponds to the ``serving_config`` 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 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.UpdateServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config.name", request.serving_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_serving_config(self, + request: Union[serving_config_service.GetServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> serving_config.ServingConfig: + r"""Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_get_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetServingConfigRequest, dict]): + The request object. Request for GetServingConfig method. + name (:class:`str`): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.GetServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_serving_configs(self, + request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServingConfigsAsyncPager: + r"""Lists all ServingConfigs linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_list_serving_configs(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListServingConfigsRequest, dict]): + The request object. Request for ListServingConfigs + method. + parent (:class:`str`): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsAsyncPager: + Response for ListServingConfigs + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.ListServingConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_serving_configs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServingConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_control(self, + request: Union[serving_config_service.AddControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_add_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.add_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddControlRequest, dict]): + The request object. Request for AddControl method. + serving_config (:class:`str`): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.AddControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_control(self, + request: Union[serving_config_service.RemoveControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_remove_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.remove_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveControlRequest, dict]): + The request object. Request for RemoveControl method. + serving_config (:class:`str`): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.RemoveControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServingConfigServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py new file mode 100644 index 00000000..d9d8e276 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py @@ -0,0 +1,1163 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2alpha.services.serving_config_service import pagers +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ServingConfigServiceGrpcTransport +from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport + + +class ServingConfigServiceClientMeta(type): + """Metaclass for the ServingConfigService 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[ServingConfigServiceTransport]] + _transport_registry["grpc"] = ServingConfigServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ServingConfigServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ServingConfigServiceTransport]: + """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 ServingConfigServiceClient(metaclass=ServingConfigServiceClientMeta): + """Service for modifying ServingConfig.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServingConfigServiceClient: 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: + ServingConfigServiceClient: 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) -> ServingConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ServingConfigServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,catalog: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ServingConfigServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the serving config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ServingConfigServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ServingConfigServiceTransport): + # transport is a ServingConfigServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_serving_config(self, + request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, + *, + parent: str = None, + serving_config: gcr_serving_config.ServingConfig = None, + serving_config_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_create_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = client.create_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CreateServingConfigRequest, dict]): + The request object. Request for CreateServingConfig + method. + parent (str): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config (google.cloud.retail_v2alpha.types.ServingConfig): + Required. The ServingConfig to + create. + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config_id (str): + Required. The ID to use for the ServingConfig, which + will become the final component of the ServingConfig's + resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``serving_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, serving_config, serving_config_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.CreateServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.CreateServingConfigRequest): + request = serving_config_service.CreateServingConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if serving_config is not None: + request.serving_config = serving_config + if serving_config_id is not None: + request.serving_config_id = serving_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_serving_config(self, + request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_delete_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_serving_config(request=request) + + Args: + request (Union[google.cloud.retail_v2alpha.types.DeleteServingConfigRequest, dict]): + The request object. Request for DeleteServingConfig + method. + name (str): + Required. The resource name of the ServingConfig to + delete. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.DeleteServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.DeleteServingConfigRequest): + request = serving_config_service.DeleteServingConfigRequest(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_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_serving_config(self, + request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, + *, + serving_config: gcr_serving_config.ServingConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Updates a ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_update_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = client.update_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.UpdateServingConfigRequest, dict]): + The request object. Request for UpdateServingConfig + method. + serving_config (google.cloud.retail_v2alpha.types.ServingConfig): + Required. The ServingConfig to + update. + + This corresponds to the ``serving_config`` 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 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.UpdateServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.UpdateServingConfigRequest): + request = serving_config_service.UpdateServingConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config.name", request.serving_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_serving_config(self, + request: Union[serving_config_service.GetServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> serving_config.ServingConfig: + r"""Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_get_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.GetServingConfigRequest, dict]): + The request object. Request for GetServingConfig method. + name (str): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.GetServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.GetServingConfigRequest): + request = serving_config_service.GetServingConfigRequest(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_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_serving_configs(self, + request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServingConfigsPager: + r"""Lists all ServingConfigs linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_list_serving_configs(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ListServingConfigsRequest, dict]): + The request object. Request for ListServingConfigs + method. + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsPager: + Response for ListServingConfigs + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.ListServingConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.ListServingConfigsRequest): + request = serving_config_service.ListServingConfigsRequest(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_serving_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListServingConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_control(self, + request: Union[serving_config_service.AddControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_add_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.add_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.AddControlRequest, dict]): + The request object. Request for AddControl method. + serving_config (str): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.AddControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.AddControlRequest): + request = serving_config_service.AddControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_control(self, + request: Union[serving_config_service.RemoveControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_remove_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.remove_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RemoveControlRequest, dict]): + The request object. Request for RemoveControl method. + serving_config (str): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.RemoveControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.RemoveControlRequest): + request = serving_config_service.RemoveControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServingConfigServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py new file mode 100644 index 00000000..8c4975b7 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config_service + + +class ListServingConfigsPager: + """A pager for iterating through ``list_serving_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``serving_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServingConfigs`` requests and continue to iterate + through the ``serving_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` + 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[..., serving_config_service.ListServingConfigsResponse], + request: serving_config_service.ListServingConfigsRequest, + response: serving_config_service.ListServingConfigsResponse, + *, + 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.retail_v2alpha.types.ListServingConfigsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListServingConfigsResponse): + 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 = serving_config_service.ListServingConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[serving_config_service.ListServingConfigsResponse]: + 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[serving_config.ServingConfig]: + for page in self.pages: + yield from page.serving_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServingConfigsAsyncPager: + """A pager for iterating through ``list_serving_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``serving_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServingConfigs`` requests and continue to iterate + through the ``serving_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` + 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[serving_config_service.ListServingConfigsResponse]], + request: serving_config_service.ListServingConfigsRequest, + response: serving_config_service.ListServingConfigsResponse, + *, + 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.retail_v2alpha.types.ListServingConfigsRequest): + The initial request object. + response (google.cloud.retail_v2alpha.types.ListServingConfigsResponse): + 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 = serving_config_service.ListServingConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[serving_config_service.ListServingConfigsResponse]: + 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[serving_config.ServingConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.serving_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py new file mode 100644 index 00000000..3726ac83 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ServingConfigServiceTransport +from .grpc import ServingConfigServiceGrpcTransport +from .grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ServingConfigServiceTransport]] +_transport_registry['grpc'] = ServingConfigServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ServingConfigServiceGrpcAsyncIOTransport + +__all__ = ( + 'ServingConfigServiceTransport', + 'ServingConfigServiceGrpcTransport', + 'ServingConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py new file mode 100644 index 00000000..94052dd6 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ServingConfigServiceTransport(abc.ABC): + """Abstract transport class for ServingConfigService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_serving_config: gapic_v1.method.wrap_method( + self.create_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_serving_config: gapic_v1.method.wrap_method( + self.delete_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.update_serving_config: gapic_v1.method.wrap_method( + self.update_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.get_serving_config: gapic_v1.method.wrap_method( + self.get_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.list_serving_configs: gapic_v1.method.wrap_method( + self.list_serving_configs, + default_timeout=None, + client_info=client_info, + ), + self.add_control: gapic_v1.method.wrap_method( + self.add_control, + default_timeout=None, + client_info=client_info, + ), + self.remove_control: gapic_v1.method.wrap_method( + self.remove_control, + 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 create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + Union[ + serving_config.ServingConfig, + Awaitable[serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + Union[ + serving_config_service.ListServingConfigsResponse, + Awaitable[serving_config_service.ListServingConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ServingConfigServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py new file mode 100644 index 00000000..0acec25b --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py @@ -0,0 +1,440 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO + + +class ServingConfigServiceGrpcTransport(ServingConfigServiceTransport): + """gRPC backend transport for ServingConfigService. + + Service for modifying ServingConfig. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the create serving config method over gRPC. + + Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + Returns: + Callable[[~.CreateServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/CreateServingConfig', + request_serializer=serving_config_service.CreateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['create_serving_config'] + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete serving config method over gRPC. + + Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.DeleteServingConfigRequest], + ~.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_serving_config' not in self._stubs: + self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/DeleteServingConfig', + request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_serving_config'] + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the update serving config method over gRPC. + + Updates a ServingConfig. + + Returns: + Callable[[~.UpdateServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/UpdateServingConfig', + request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['update_serving_config'] + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + serving_config.ServingConfig]: + r"""Return a callable for the get serving config method over gRPC. + + Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.GetServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/GetServingConfig', + request_serializer=serving_config_service.GetServingConfigRequest.serialize, + response_deserializer=serving_config.ServingConfig.deserialize, + ) + return self._stubs['get_serving_config'] + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + serving_config_service.ListServingConfigsResponse]: + r"""Return a callable for the list serving configs method over gRPC. + + Lists all ServingConfigs linked to this catalog. + + Returns: + Callable[[~.ListServingConfigsRequest], + ~.ListServingConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: + self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/ListServingConfigs', + request_serializer=serving_config_service.ListServingConfigsRequest.serialize, + response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, + ) + return self._stubs['list_serving_configs'] + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the add control method over gRPC. + + Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + Returns: + Callable[[~.AddControlRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_control' not in self._stubs: + self._stubs['add_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/AddControl', + request_serializer=serving_config_service.AddControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['add_control'] + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the remove control method over gRPC. + + Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + Returns: + Callable[[~.RemoveControlRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_control' not in self._stubs: + self._stubs['remove_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/RemoveControl', + request_serializer=serving_config_service.RemoveControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['remove_control'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ServingConfigServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..e3d2ccca --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py @@ -0,0 +1,439 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ServingConfigServiceGrpcTransport + + +class ServingConfigServiceGrpcAsyncIOTransport(ServingConfigServiceTransport): + """gRPC AsyncIO backend transport for ServingConfigService. + + Service for modifying ServingConfig. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the create serving config method over gRPC. + + Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + Returns: + Callable[[~.CreateServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/CreateServingConfig', + request_serializer=serving_config_service.CreateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['create_serving_config'] + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete serving config method over gRPC. + + Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.DeleteServingConfigRequest], + 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_serving_config' not in self._stubs: + self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/DeleteServingConfig', + request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_serving_config'] + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the update serving config method over gRPC. + + Updates a ServingConfig. + + Returns: + Callable[[~.UpdateServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/UpdateServingConfig', + request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['update_serving_config'] + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + Awaitable[serving_config.ServingConfig]]: + r"""Return a callable for the get serving config method over gRPC. + + Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.GetServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/GetServingConfig', + request_serializer=serving_config_service.GetServingConfigRequest.serialize, + response_deserializer=serving_config.ServingConfig.deserialize, + ) + return self._stubs['get_serving_config'] + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + Awaitable[serving_config_service.ListServingConfigsResponse]]: + r"""Return a callable for the list serving configs method over gRPC. + + Lists all ServingConfigs linked to this catalog. + + Returns: + Callable[[~.ListServingConfigsRequest], + Awaitable[~.ListServingConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: + self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/ListServingConfigs', + request_serializer=serving_config_service.ListServingConfigsRequest.serialize, + response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, + ) + return self._stubs['list_serving_configs'] + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the add control method over gRPC. + + Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + Returns: + Callable[[~.AddControlRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_control' not in self._stubs: + self._stubs['add_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/AddControl', + request_serializer=serving_config_service.AddControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['add_control'] + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the remove control method over gRPC. + + Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + Returns: + Callable[[~.RemoveControlRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_control' not in self._stubs: + self._stubs['remove_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.ServingConfigService/RemoveControl', + request_serializer=serving_config_service.RemoveControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['remove_control'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ServingConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py new file mode 100644 index 00000000..5f5171c1 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py new file mode 100644 index 00000000..1f08ee18 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py @@ -0,0 +1,730 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on the customer + website. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(UserEventServiceClient.catalog_path) + parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) + product_path = staticmethod(UserEventServiceClient.product_path) + parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_write_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_collect_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_purge_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_import_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2alpha.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + async def sample_rejoin_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py new file mode 100644 index 00000000..98d272ff --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py @@ -0,0 +1,930 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[UserEventServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on the customer + website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_write_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2alpha.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_collect_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_purge_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeUserEventsRequest): + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_import_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2alpha.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2alpha + + def sample_rejoin_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2alpha.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2alpha.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.RejoinUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.RejoinUserEventsRequest): + request = user_event_service.RejoinUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py new file mode 100644 index 00000000..f53ee5d7 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py new file mode 100644 index 00000000..efd2f034 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py @@ -0,0 +1,235 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.rejoin_user_events: gapic_v1.method.wrap_method( + self.rejoin_user_events, + 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 write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + user_event.UserEvent, + Awaitable[user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py new file mode 100644 index 00000000..3ca23eca --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..72c6083a --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + 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 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2alpha.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py new file mode 100644 index 00000000..aa87618d --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py @@ -0,0 +1,284 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .catalog import ( + AttributesConfig, + Catalog, + CatalogAttribute, + CompletionConfig, + MerchantCenterLink, + MerchantCenterLinkingConfig, + ProductLevelConfig, +) +from .catalog_service import ( + AddCatalogAttributeRequest, + GetAttributesConfigRequest, + GetCompletionConfigRequest, + GetDefaultBranchRequest, + GetDefaultBranchResponse, + ListCatalogsRequest, + ListCatalogsResponse, + RemoveCatalogAttributeRequest, + ReplaceCatalogAttributeRequest, + SetDefaultBranchRequest, + UpdateAttributesConfigRequest, + UpdateCatalogRequest, + UpdateCompletionConfigRequest, +) +from .common import ( + Audience, + ColorInfo, + Condition, + CustomAttribute, + FulfillmentInfo, + Image, + Interval, + LocalInventory, + PriceInfo, + Rating, + Rule, + UserInfo, + AttributeConfigLevel, + SearchSolutionUseCase, + SolutionType, +) +from .completion_service import ( + CompleteQueryRequest, + CompleteQueryResponse, +) +from .control import ( + Control, +) +from .control_service import ( + CreateControlRequest, + DeleteControlRequest, + GetControlRequest, + ListControlsRequest, + ListControlsResponse, + UpdateControlRequest, +) +from .export_config import ( + ExportErrorsConfig, + ExportMetadata, + ExportProductsResponse, + ExportUserEventsResponse, +) +from .import_config import ( + BigQuerySource, + CompletionDataInputConfig, + GcsSource, + ImportCompletionDataRequest, + ImportCompletionDataResponse, + ImportErrorsConfig, + ImportMetadata, + ImportProductsRequest, + ImportProductsResponse, + ImportUserEventsRequest, + ImportUserEventsResponse, + ProductInlineSource, + ProductInputConfig, + UserEventImportSummary, + UserEventInlineSource, + UserEventInputConfig, +) +from .prediction_service import ( + PredictRequest, + PredictResponse, +) +from .product import ( + Product, +) +from .product_service import ( + AddFulfillmentPlacesMetadata, + AddFulfillmentPlacesRequest, + AddFulfillmentPlacesResponse, + AddLocalInventoriesMetadata, + AddLocalInventoriesRequest, + AddLocalInventoriesResponse, + CreateProductRequest, + DeleteProductRequest, + GetProductRequest, + ListProductsRequest, + ListProductsResponse, + RemoveFulfillmentPlacesMetadata, + RemoveFulfillmentPlacesRequest, + RemoveFulfillmentPlacesResponse, + RemoveLocalInventoriesMetadata, + RemoveLocalInventoriesRequest, + RemoveLocalInventoriesResponse, + SetInventoryMetadata, + SetInventoryRequest, + SetInventoryResponse, + UpdateProductRequest, +) +from .promotion import ( + Promotion, +) +from .purge_config import ( + PurgeMetadata, + PurgeProductsMetadata, + PurgeProductsRequest, + PurgeProductsResponse, + PurgeUserEventsRequest, + PurgeUserEventsResponse, +) +from .search_service import ( + SearchRequest, + SearchResponse, +) +from .serving_config import ( + ServingConfig, +) +from .serving_config_service import ( + AddControlRequest, + CreateServingConfigRequest, + DeleteServingConfigRequest, + GetServingConfigRequest, + ListServingConfigsRequest, + ListServingConfigsResponse, + RemoveControlRequest, + UpdateServingConfigRequest, +) +from .user_event import ( + CompletionDetail, + ProductDetail, + PurchaseTransaction, + UserEvent, +) +from .user_event_service import ( + CollectUserEventRequest, + RejoinUserEventsMetadata, + RejoinUserEventsRequest, + RejoinUserEventsResponse, + WriteUserEventRequest, +) + +__all__ = ( + 'AttributesConfig', + 'Catalog', + 'CatalogAttribute', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'ProductLevelConfig', + 'AddCatalogAttributeRequest', + 'GetAttributesConfigRequest', + 'GetCompletionConfigRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + 'SetDefaultBranchRequest', + 'UpdateAttributesConfigRequest', + 'UpdateCatalogRequest', + 'UpdateCompletionConfigRequest', + 'Audience', + 'ColorInfo', + 'Condition', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'Rule', + 'UserInfo', + 'AttributeConfigLevel', + 'SearchSolutionUseCase', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Control', + 'CreateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + 'UpdateControlRequest', + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeProductsMetadata', + 'PurgeProductsRequest', + 'PurgeProductsResponse', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'ServingConfig', + 'AddControlRequest', + 'CreateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'RemoveControlRequest', + 'UpdateServingConfigRequest', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py new file mode 100644 index 00000000..1e4a7ab5 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py @@ -0,0 +1,528 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'ProductLevelConfig', + 'CatalogAttribute', + 'AttributesConfig', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'Catalog', + }, +) + + +class ProductLevelConfig(proto.Message): + r"""Configures what level the product should be uploaded with + regards to how users will be send events and how predictions + will be made. + + Attributes: + ingestion_product_type (str): + The type of [Product][google.cloud.retail.v2alpha.Product]s + allowed to be ingested into the catalog. Acceptable values + are: + + - ``primary`` (default): You can ingest + [Product][google.cloud.retail.v2alpha.Product]s of all + types. When ingesting a + [Product][google.cloud.retail.v2alpha.Product], its type + will default to + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + if unset. + - ``variant``: You can only ingest + [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s. This + means + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] + cannot be empty. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``variant`` and + [merchant_center_product_id_field][google.cloud.retail.v2alpha.ProductLevelConfig.merchant_center_product_id_field] + is ``itemGroupId``, an INVALID_ARGUMENT error is returned. + + See `Using product + levels `__ + for more details. + merchant_center_product_id_field (str): + Which field of `Merchant Center + Product `__ + should be imported as + [Product.id][google.cloud.retail.v2alpha.Product.id]. + Acceptable values are: + + - ``offerId`` (default): Import ``offerId`` as the product + ID. + - ``itemGroupId``: Import ``itemGroupId`` as the product + ID. Notice that Retail API will choose one item from the + ones with the same ``itemGroupId``, and use it to + represent the item group. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``itemGroupId`` and + [ingestion_product_type][google.cloud.retail.v2alpha.ProductLevelConfig.ingestion_product_type] + is ``variant``, an INVALID_ARGUMENT error is returned. + + See `Using product + levels `__ + for more details. + """ + + ingestion_product_type = proto.Field( + proto.STRING, + number=1, + ) + merchant_center_product_id_field = proto.Field( + proto.STRING, + number=2, + ) + + +class CatalogAttribute(proto.Message): + r"""Catalog level attribute config for an attribute. For example, + if customers want to enable/disable facet for a specific + attribute. + + Attributes: + key (str): + Required. Attribute name. For example: ``color``, + ``brands``, ``attributes.custom_attribute``, such as + ``attributes.xyz``. + in_use (bool): + Output only. Indicates whether this attribute has been used + by any products. ``True`` if at least one + [Product][google.cloud.retail.v2alpha.Product] is using this + attribute in + [Product.attributes][google.cloud.retail.v2alpha.Product.attributes]. + Otherwise, this field is ``False``. + + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + can be pre-loaded by using [AddCatalogAttribute][], + [ImportCatalogAttributes][], or [UpdateAttributesConfig][] + APIs. This field is ``False`` for pre-loaded + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s. + + Only + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s + that are not in use by products can be deleted. + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s + that are in use by products cannot be deleted; however, + their configuration properties will reset to default values + upon removal request. + + After catalog changes, it takes about 10 minutes for this + field to update. + type_ (google.cloud.retail_v2alpha.types.CatalogAttribute.AttributeType): + Output only. The type of this attribute. This is derived + from the attribute in + [Product.attributes][google.cloud.retail.v2alpha.Product.attributes]. + indexable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.IndexableOption): + When + [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] + is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if INDEXABLE_ENABLED + attribute values are indexed so that it can be filtered, + faceted, or boosted in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + dynamic_facetable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.DynamicFacetableOption): + If DYNAMIC_FACETABLE_ENABLED, attribute values are available + for dynamic facet. Could only be DYNAMIC_FACETABLE_DISABLED + if + [CatalogAttribute.indexable_option][google.cloud.retail.v2alpha.CatalogAttribute.indexable_option] + is INDEXABLE_DISABLED. Otherwise, an INVALID_ARGUMENT error + is returned. + searchable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.SearchableOption): + When + [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] + is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if SEARCHABLE_ENABLED, + attribute values are searchable by text queries in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + If SEARCHABLE_ENABLED but attribute type is numerical, + attribute values will not be searchable by text queries in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], + as there are no text values associated to numerical + attributes. + """ + class AttributeType(proto.Enum): + r"""The type of an attribute.""" + UNKNOWN = 0 + TEXTUAL = 1 + NUMERICAL = 2 + + class IndexableOption(proto.Enum): + r"""The status of the indexable option of a catalog attribute.""" + INDEXABLE_OPTION_UNSPECIFIED = 0 + INDEXABLE_ENABLED = 1 + INDEXABLE_DISABLED = 2 + + class DynamicFacetableOption(proto.Enum): + r"""The status of the dynamic facetable option of a catalog + attribute. + """ + DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 + DYNAMIC_FACETABLE_ENABLED = 1 + DYNAMIC_FACETABLE_DISABLED = 2 + + class SearchableOption(proto.Enum): + r"""The status of the searchable option of a catalog attribute.""" + SEARCHABLE_OPTION_UNSPECIFIED = 0 + SEARCHABLE_ENABLED = 1 + SEARCHABLE_DISABLED = 2 + + key = proto.Field( + proto.STRING, + number=1, + ) + in_use = proto.Field( + proto.BOOL, + number=9, + ) + type_ = proto.Field( + proto.ENUM, + number=10, + enum=AttributeType, + ) + indexable_option = proto.Field( + proto.ENUM, + number=5, + enum=IndexableOption, + ) + dynamic_facetable_option = proto.Field( + proto.ENUM, + number=6, + enum=DynamicFacetableOption, + ) + searchable_option = proto.Field( + proto.ENUM, + number=7, + enum=SearchableOption, + ) + + +class AttributesConfig(proto.Message): + r"""Catalog level attribute config. + + Attributes: + name (str): + Required. Immutable. The fully qualified resource name of + the attribute config. Format: + ``projects/*/locations/*/catalogs/*/attributesConfig`` + catalog_attributes (Mapping[str, google.cloud.retail_v2alpha.types.CatalogAttribute]): + Enable attribute(s) config at catalog level. For example, + indexable, dynamic_facetable, or searchable for each + attribute. + + The key is catalog attribute's name. For example: ``color``, + ``brands``, ``attributes.custom_attribute``, such as + ``attributes.xyz``. + + The maximum number of catalog attributes allowed in a + request is 1000. + attribute_config_level (google.cloud.retail_v2alpha.types.AttributeConfigLevel): + Output only. The + [AttributeConfigLevel][google.cloud.retail.v2alpha.AttributeConfigLevel] + used for this catalog. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + catalog_attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='CatalogAttribute', + ) + attribute_config_level = proto.Field( + proto.ENUM, + number=3, + enum=common.AttributeConfigLevel, + ) + + +class CompletionConfig(proto.Message): + r"""Catalog level autocomplete config for customers to customize + autocomplete feature's settings. + + Attributes: + name (str): + Required. Immutable. Fully qualified name + ``projects/*/locations/*/catalogs/*/completionConfig`` + matching_order (str): + Specifies the matching order for autocomplete suggestions, + e.g., a query consisting of 'sh' with 'out-of-order' + specified would suggest "women's shoes", whereas a query of + 'red s' with 'exact-prefix' specified would suggest "red + shoes". Currently supported values: + + - 'out-of-order' + - 'exact-prefix' + + Default value: 'exact-prefix'. + max_suggestions (int): + The maximum number of autocomplete + suggestions returned per term. The maximum + allowed max suggestions is 20. Default value is + 20. If left unset or set to 0, then will + fallback to default value. + min_prefix_length (int): + The minimum number of characters needed to be + typed in order to get suggestions. Default value + is 2. If left unset or set to 0, then will + fallback to default value. + auto_learning (bool): + If set to true, the auto learning function is enabled. Auto + learning uses user data to generate suggestions using ML + techniques. Default value is false. Only after enabling auto + learning can users use ``cloud-retail`` data in + [CompleteQueryRequest][google.cloud.retail.v2alpha.CompleteQueryRequest]. + suggestions_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the + autocomplete phrases uploaded by the customer. + last_suggestions_import_operation (str): + Output only. Name of the LRO corresponding to the latest + suggestion terms list import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + denylist_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the / + autocomplete denylist phrases uploaded by the + customer. + last_denylist_import_operation (str): + Output only. LRO corresponding to the latest denylist + import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + allowlist_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the + autocomplete allowlist phrases uploaded by the + customer. + last_allowlist_import_operation (str): + Output only. LRO corresponding to the latest allowlist + import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + matching_order = proto.Field( + proto.STRING, + number=2, + ) + max_suggestions = proto.Field( + proto.INT32, + number=3, + ) + min_prefix_length = proto.Field( + proto.INT32, + number=4, + ) + auto_learning = proto.Field( + proto.BOOL, + number=11, + ) + suggestions_input_config = proto.Field( + proto.MESSAGE, + number=5, + message=import_config.CompletionDataInputConfig, + ) + last_suggestions_import_operation = proto.Field( + proto.STRING, + number=6, + ) + denylist_input_config = proto.Field( + proto.MESSAGE, + number=7, + message=import_config.CompletionDataInputConfig, + ) + last_denylist_import_operation = proto.Field( + proto.STRING, + number=8, + ) + allowlist_input_config = proto.Field( + proto.MESSAGE, + number=9, + message=import_config.CompletionDataInputConfig, + ) + last_allowlist_import_operation = proto.Field( + proto.STRING, + number=10, + ) + + +class MerchantCenterLink(proto.Message): + r"""Represents a link between a Merchant Center account and a + branch. Once a link is established, products from the linked + merchant center account will be streamed to the linked branch. + + Attributes: + merchant_center_account_id (int): + Required. The linked `Merchant center account + id `__. + The account must be a standalone account or a sub-account of + a MCA. + branch_id (str): + The branch id (e.g. 0/1/2) within this catalog that products + from merchant_center_account_id are streamed to. When + updating this field, an empty value will use the currently + configured default branch. However, changing the default + branch later on won't change the linked branch here. + + A single branch id can only have one linked merchant center + account id. + destinations (Sequence[str]): + String representing the destination to import for, all if + left empty. List of possible values can be found here. + [https://support.google.com/merchants/answer/7501026] List + of allowed string values: "Shopping_ads", + "Buy_on_google_listings", "Display_ads", "Local_inventory + \_ads", "Free_listings", "Free_local_listings" NOTE: The + string values are case sensitive. + region_code (str): + Region code of offers to accept. 2-letter Uppercase ISO + 3166-1 alpha-2 code. List of values can be found + `here `__ + under the ``region`` tag. If left blank no region filtering + will be performed. + + Example value: ``US``. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. ISO + 639-1. + + This specifies the language of offers in Merchant Center + that will be accepted. If empty no language filtering will + be performed. + + Example value: ``en``. + """ + + merchant_center_account_id = proto.Field( + proto.INT64, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + destinations = proto.RepeatedField( + proto.STRING, + number=3, + ) + region_code = proto.Field( + proto.STRING, + number=4, + ) + language_code = proto.Field( + proto.STRING, + number=5, + ) + + +class MerchantCenterLinkingConfig(proto.Message): + r"""Configures Merchant Center linking. + Links contained in the config will be used to sync data from a + Merchant Center account to a Cloud Retail branch. + + Attributes: + links (Sequence[google.cloud.retail_v2alpha.types.MerchantCenterLink]): + Links between Merchant Center accounts and + branches. + """ + + links = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MerchantCenterLink', + ) + + +class Catalog(proto.Message): + r"""The catalog configuration. + + Attributes: + name (str): + Required. Immutable. The fully qualified + resource name of the catalog. + display_name (str): + Required. Immutable. The catalog display name. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + product_level_config (google.cloud.retail_v2alpha.types.ProductLevelConfig): + Required. The product level configuration. + merchant_center_linking_config (google.cloud.retail_v2alpha.types.MerchantCenterLinkingConfig): + The Merchant Center linking configuration. + Once a link is added, the data stream from + Merchant Center to Cloud Retail will be enabled + automatically. The requester must have access to + the merchant center account in order to make + changes to this field. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + product_level_config = proto.Field( + proto.MESSAGE, + number=4, + message='ProductLevelConfig', + ) + merchant_center_linking_config = proto.Field( + proto.MESSAGE, + number=6, + message='MerchantCenterLinkingConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py new file mode 100644 index 00000000..21d9b1c2 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py @@ -0,0 +1,453 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'UpdateCatalogRequest', + 'SetDefaultBranchRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'GetCompletionConfigRequest', + 'UpdateCompletionConfigRequest', + 'GetAttributesConfigRequest', + 'UpdateAttributesConfigRequest', + 'AddCatalogAttributeRequest', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + }, +) + + +class ListCatalogsRequest(proto.Message): + r"""Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + + Attributes: + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2alpha.Catalog]s under this + location, regardless of whether or not this location exists, + a PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [Catalog][google.cloud.retail.v2alpha.Catalog]s to return. + If unspecified, defaults to 50. The maximum allowed value is + 1000. Values above 1000 will be coerced to 1000. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [ListCatalogsResponse.next_page_token][google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token], + received from a previous + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCatalogsResponse(proto.Message): + r"""Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] + method. + + Attributes: + catalogs (Sequence[google.cloud.retail_v2alpha.types.Catalog]): + All the customer's + [Catalog][google.cloud.retail.v2alpha.Catalog]s. + next_page_token (str): + A token that can be sent as + [ListCatalogsRequest.page_token][google.cloud.retail.v2alpha.ListCatalogsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + catalogs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateCatalogRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] + method. + + Attributes: + catalog (google.cloud.retail_v2alpha.types.Catalog): + Required. The [Catalog][google.cloud.retail.v2alpha.Catalog] + to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2alpha.Catalog], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2alpha.Catalog] 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 + [Catalog][google.cloud.retail.v2alpha.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + catalog = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class SetDefaultBranchRequest(proto.Message): + r"""Request message to set a specified branch as new default_branch. + + Attributes: + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + branch_id (str): + The final component of the resource name of a branch. + + This field must be one of "0", "1" or "2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If there are no sufficient active products in the targeted + branch and + [force][google.cloud.retail.v2alpha.SetDefaultBranchRequest.force] + is not set, a FAILED_PRECONDITION error is returned. + note (str): + Some note on this request, this can be retrieved by + [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch] + before next valid default branch set occurs. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + force (bool): + If set to true, it permits switching to a branch with + [branch_id][google.cloud.retail.v2alpha.SetDefaultBranchRequest.branch_id] + even if it has no sufficient active products. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + force = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetDefaultBranchRequest(proto.Message): + r"""Request message to show which branch is currently the default + branch. + + Attributes: + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDefaultBranchResponse(proto.Message): + r"""Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. + + Attributes: + branch (str): + Full resource name of the branch id currently + set as default branch. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when this branch is set to default. + note (str): + This corresponds to + [SetDefaultBranchRequest.note][google.cloud.retail.v2alpha.SetDefaultBranchRequest.note] + field, when this branch was set as default. + """ + + branch = proto.Field( + proto.STRING, + number=1, + ) + set_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + + +class GetCompletionConfigRequest(proto.Message): + r"""Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] + method. + + Attributes: + name (str): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateCompletionConfigRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] + method. + + Attributes: + completion_config (google.cloud.retail_v2alpha.types.CompletionConfig): + Required. The + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + 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 + [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + """ + + completion_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.CompletionConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetAttributesConfigRequest(proto.Message): + r"""Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] + method. + + Attributes: + name (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAttributesConfigRequest(proto.Message): + r"""Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] + method. + + Attributes: + attributes_config (google.cloud.retail_v2alpha.types.AttributesConfig): + Required. The + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + """ + + attributes_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.AttributesConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class AddCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + catalog_attribute (google.cloud.retail_v2alpha.types.CatalogAttribute): + Required. The + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to add. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + catalog_attribute = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_catalog.CatalogAttribute, + ) + + +class RemoveCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + key (str): + Required. The attribute name key of the + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to remove. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + key = proto.Field( + proto.STRING, + number=2, + ) + + +class ReplaceCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + catalog_attribute (google.cloud.retail_v2alpha.types.CatalogAttribute): + Required. The updated + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + to update. The following are NOT supported: + + - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key] + + If not set, all supported fields are updated. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + catalog_attribute = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_catalog.CatalogAttribute, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py new file mode 100644 index 00000000..25fa2861 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py @@ -0,0 +1,1179 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'AttributeConfigLevel', + 'SolutionType', + 'SearchSolutionUseCase', + 'Condition', + 'Rule', + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'LocalInventory', + }, +) + + +class AttributeConfigLevel(proto.Enum): + r"""At which level we offer configuration for attributes.""" + ATTRIBUTE_CONFIG_LEVEL_UNSPECIFIED = 0 + PRODUCT_LEVEL_ATTRIBUTE_CONFIG = 1 + CATALOG_LEVEL_ATTRIBUTE_CONFIG = 2 + + +class SolutionType(proto.Enum): + r"""The type of solution.""" + SOLUTION_TYPE_UNSPECIFIED = 0 + SOLUTION_TYPE_RECOMMENDATION = 1 + SOLUTION_TYPE_SEARCH = 2 + + +class SearchSolutionUseCase(proto.Enum): + r"""The use case of Cloud Retail Search.""" + SEARCH_SOLUTION_USE_CASE_UNSPECIFIED = 0 + SEARCH_SOLUTION_USE_CASE_SEARCH = 1 + SEARCH_SOLUTION_USE_CASE_BROWSE = 2 + + +class Condition(proto.Message): + r"""Metadata that is used to define a condition that triggers an action. + A valid condition must specify at least one of 'query_terms' or + 'products_filter'. If multiple fields are specified, the condition + is met if all the fields are satisfied e.g. if a set of query terms + and product_filter are set, then only items matching the + product_filter for requests with a query matching the query terms + wil get boosted. + + Attributes: + query_terms (Sequence[google.cloud.retail_v2alpha.types.Condition.QueryTerm]): + A list (up to 10 entries) of terms to match + the query on. If not specified, match all + queries. If many query terms are specified, the + condition is matched if any of the terms is a + match (i.e. using the OR operator). + active_time_range (Sequence[google.cloud.retail_v2alpha.types.Condition.TimeRange]): + Range of time(s) specifying when Condition is + active. Condition true if any time range + matches. + """ + + class QueryTerm(proto.Message): + r"""Query terms that we want to match on. + + Attributes: + value (str): + The value of the term to match on. + Value cannot be empty. + Value can have at most 3 terms if specified as a + partial match. Each space separated string is + considered as one term. Example) "a b c" is 3 + terms and allowed, " a b c d" is 4 terms and not + allowed for partial match. + full_match (bool): + Whether this is supposed to be a full or + partial match. + """ + + value = proto.Field( + proto.STRING, + number=1, + ) + full_match = proto.Field( + proto.BOOL, + number=2, + ) + + class TimeRange(proto.Message): + r"""Used for time-dependent conditions. + Example: Want to have rule applied for week long sale. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start of time range. Range is inclusive. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End of time range. Range is inclusive. + """ + + start_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + query_terms = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=QueryTerm, + ) + active_time_range = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TimeRange, + ) + + +class Rule(proto.Message): + r"""A rule is a condition-action pair + + - A condition defines when a rule is to be triggered. + - An action specifies what occurs on that trigger. Currently only + boost rules are supported. Currently only supported by the search + endpoint. + + 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: + boost_action (google.cloud.retail_v2alpha.types.Rule.BoostAction): + A boost action. + + This field is a member of `oneof`_ ``action``. + redirect_action (google.cloud.retail_v2alpha.types.Rule.RedirectAction): + Redirects a shopper to a specific page. + + This field is a member of `oneof`_ ``action``. + oneway_synonyms_action (google.cloud.retail_v2alpha.types.Rule.OnewaySynonymsAction): + Treats specific term as a synonym with a + group of terms. Group of terms will not be + treated as synonyms with the specific term. + + This field is a member of `oneof`_ ``action``. + do_not_associate_action (google.cloud.retail_v2alpha.types.Rule.DoNotAssociateAction): + Prevents term from being associated with + other terms. + + This field is a member of `oneof`_ ``action``. + replacement_action (google.cloud.retail_v2alpha.types.Rule.ReplacementAction): + Replaces specific terms in the query. + + This field is a member of `oneof`_ ``action``. + ignore_action (google.cloud.retail_v2alpha.types.Rule.IgnoreAction): + Ignores specific terms from query during + search. + + This field is a member of `oneof`_ ``action``. + filter_action (google.cloud.retail_v2alpha.types.Rule.FilterAction): + Filters results. + + This field is a member of `oneof`_ ``action``. + twoway_synonyms_action (google.cloud.retail_v2alpha.types.Rule.TwowaySynonymsAction): + Treats a set of terms as synonyms of one + another. + + This field is a member of `oneof`_ ``action``. + condition (google.cloud.retail_v2alpha.types.Condition): + Required. The condition that triggers the + rule. If the condition is empty, the rule will + always apply. + """ + + class BoostAction(proto.Message): + r"""A boost action to apply to results matching condition + specified above. + + Attributes: + boost (float): + Strength of the condition boost, which must be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + products_filter (str): + The filter can have a max size of 5000 characters. An + expression which specifies which products to apply an action + to. The syntax and supported fields are the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": *(id: + ANY("product_1", "product_2"))* *AND* *(colorFamilies: + ANY("Red", "Blue"))* + """ + + boost = proto.Field( + proto.FLOAT, + number=1, + ) + products_filter = proto.Field( + proto.STRING, + number=2, + ) + + class FilterAction(proto.Message): + r"""- Rule Condition: + + - No [Condition][query_terms] provided is a global match. + - 1 or more [Condition][query_terms] provided is combined with + OR operator. + + - Action Input: The request query and filter that will be applied + to the retrieved products, in addition to any filters already + provided with the SearchRequest. The AND operator is used to + combine the query's existing filters with the filter rule(s). + NOTE: May result in 0 results when filters conflict. + - Action Result: Filters the returned objects to be ONLY those that + passed the filter. + + Attributes: + filter (str): + A filter to apply on the matching condition results. + Supported features: + + - [filter][google.cloud.retail.v2alpha.Rule.FilterAction.filter] + must be set. + - Filter syntax is identical to + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter]. + See more details at the Retail Search `user + guide `__. + - To filter products with product ID "product_1" or + "product_2", and color "Red" or "Blue": *(id: + ANY("product_1", "product_2"))* *AND* *(colorFamilies: + ANY("Red", "Blue"))* + """ + + filter = proto.Field( + proto.STRING, + number=1, + ) + + class RedirectAction(proto.Message): + r"""Redirects a shopper to a specific page. + + - Rule Condition: + + - Must specify [Condition][query_terms]. + + - Action Input: Request Query + - Action Result: Redirects shopper to provided uri. + + Attributes: + redirect_uri (str): + URL must have length equal or less than 2000 + characters. + """ + + redirect_uri = proto.Field( + proto.STRING, + number=1, + ) + + class TwowaySynonymsAction(proto.Message): + r"""Creates a set of terms that will be treated as synonyms of each + other. Example: synonyms of "sneakers" and "shoes". + + - "sneakers" will use a synonym of "shoes". + - "shoes" will use a synonym of "sneakers". + + Attributes: + synonyms (Sequence[str]): + Defines a set of synonyms. + Can specify up to 100 synonyms. + Must specify at least 2 synonyms. + """ + + synonyms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class OnewaySynonymsAction(proto.Message): + r"""Maps a set of terms to a set of synonyms. Set of synonyms will be + treated as synonyms of each query term only. ``query_terms`` will + not be treated as synonyms of each other. Example: "sneakers" will + use a synonym of "shoes". "shoes" will not use a synonym of + "sneakers". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. + Will treat synonyms as their synonyms. + Not themselves synonyms of the synonyms. + Can specify up to 100 terms. + synonyms (Sequence[str]): + Defines a set of synonyms. + Cannot contain duplicates. + Can specify up to 100 synonyms. + oneway_terms (Sequence[str]): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=3, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=4, + ) + oneway_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class DoNotAssociateAction(proto.Message): + r"""Prevents ``query_term`` from being associated with specified terms + during search. Example: Don't associate "gShoe" and "cheap". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. Will not consider + do_not_associate_terms for search if in search query. Can + specify up to 100 terms. + do_not_associate_terms (Sequence[str]): + Cannot contain duplicates or the query term. + Can specify up to 100 terms. + terms (Sequence[str]): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + do_not_associate_terms = proto.RepeatedField( + proto.STRING, + number=3, + ) + terms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class ReplacementAction(proto.Message): + r"""Replaces a term in the query. Multiple replacement candidates can be + specified. All ``query_terms`` will be replaced with the replacement + term. Example: Replace "gShoe" with "google shoe". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. + Will be replaced by replacement term. + Can specify up to 100 terms. + replacement_term (str): + Term that will be used for replacement. + term (str): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + replacement_term = proto.Field( + proto.STRING, + number=3, + ) + term = proto.Field( + proto.STRING, + number=1, + ) + + class IgnoreAction(proto.Message): + r"""Prevents a term in the query from being used in search. + Example: Don't search for "shoddy". + + Attributes: + ignore_terms (Sequence[str]): + Terms to ignore in the search query. + """ + + ignore_terms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + boost_action = proto.Field( + proto.MESSAGE, + number=2, + oneof='action', + message=BoostAction, + ) + redirect_action = proto.Field( + proto.MESSAGE, + number=3, + oneof='action', + message=RedirectAction, + ) + oneway_synonyms_action = proto.Field( + proto.MESSAGE, + number=6, + oneof='action', + message=OnewaySynonymsAction, + ) + do_not_associate_action = proto.Field( + proto.MESSAGE, + number=7, + oneof='action', + message=DoNotAssociateAction, + ) + replacement_action = proto.Field( + proto.MESSAGE, + number=8, + oneof='action', + message=ReplacementAction, + ) + ignore_action = proto.Field( + proto.MESSAGE, + number=9, + oneof='action', + message=IgnoreAction, + ) + filter_action = proto.Field( + proto.MESSAGE, + number=10, + oneof='action', + message=FilterAction, + ) + twoway_synonyms_action = proto.Field( + proto.MESSAGE, + number=11, + oneof='action', + message=TwowaySynonymsAction, + ) + condition = proto.Field( + proto.MESSAGE, + number=1, + message='Condition', + ) + + +class Audience(proto.Message): + r"""An intended audience of the + [Product][google.cloud.retail.v2alpha.Product] for whom it's sold. + + Attributes: + genders (Sequence[str]): + The genders of the audience. Strongly encouraged to use the + standard values: "male", "female", "unisex". + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `gender `__. + Schema.org property + `Product.audience.suggestedGender `__. + age_groups (Sequence[str]): + The age groups of the audience. Strongly encouraged to use + the standard values: "newborn" (up to 3 months old), + "infant" (3–12 months old), "toddler" (1–5 years old), + "kids" (5–13 years old), "adult" (typically teens or older). + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `age_group `__. + Schema.org property + `Product.audience.suggestedMinAge `__ + and + `Product.audience.suggestedMaxAge `__. + """ + + genders = proto.RepeatedField( + proto.STRING, + number=1, + ) + age_groups = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class ColorInfo(proto.Message): + r"""The color information of a + [Product][google.cloud.retail.v2alpha.Product]. + + Attributes: + color_families (Sequence[str]): + The standard color families. Strongly recommended to use the + following standard color groups: "Red", "Pink", "Orange", + "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", + "White", "Gray", "Black" and "Mixed". Normally it is + expected to have only 1 color family. May consider using + single "Mixed" instead of multiple values. + + A maximum of 5 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + colors (Sequence[str]): + The color display names, which may be different from + standard color family names, such as the color aliases used + in the website frontend. Normally it is expected to have + only 1 color. May consider using single "Mixed" instead of + multiple values. + + A maximum of 25 colors are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + """ + + color_families = proto.RepeatedField( + proto.STRING, + number=1, + ) + colors = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in + [Product][google.cloud.retail.v2alpha.Product]. + + Attributes: + text (Sequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an INVALID_ARGUMENT + error is returned. + + Exactly one of + [text][google.cloud.retail.v2alpha.CustomAttribute.text] or + [numbers][google.cloud.retail.v2alpha.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + numbers (Sequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [text][google.cloud.retail.v2alpha.CustomAttribute.text] or + [numbers][google.cloud.retail.v2alpha.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + searchable (bool): + This field will only be used when + [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] + of the [Catalog][google.cloud.retail.v2alpha.Catalog] is + 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute + values are searchable by text queries in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2alpha.UserEvent]. + + Only set if type + [text][google.cloud.retail.v2alpha.CustomAttribute.text] is + set. Otherwise, a INVALID_ARGUMENT error is returned. + + This field is a member of `oneof`_ ``_searchable``. + indexable (bool): + This field will only be used when + [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] + of the [Catalog][google.cloud.retail.v2alpha.Catalog] is + 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute + values are indexed, so that it can be filtered, faceted or + boosted in + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2alpha.UserEvent]. + + See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter], + [SearchRequest.facet_specs][google.cloud.retail.v2alpha.SearchRequest.facet_specs] + and + [SearchRequest.boost_spec][google.cloud.retail.v2alpha.SearchRequest.boost_spec] + for more details. + + This field is a member of `oneof`_ ``_indexable``. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + searchable = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + indexable = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + +class FulfillmentInfo(proto.Message): + r"""Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + Attributes: + type_ (str): + The fulfillment type, including commonly used types (such as + pickup in store and same day delivery), and custom types. + Customers have to map custom types to their display names + before rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + place_ids (Sequence[str]): + The IDs for this + [type][google.cloud.retail.v2alpha.FulfillmentInfo.type], + such as the store IDs for + [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2alpha.FulfillmentInfo.type] + or the region IDs for + [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2alpha.FulfillmentInfo.type]. + + A maximum of 3000 values are allowed. Each value must be a + string with a length limit of 30 characters, matching the + pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". + Otherwise, an INVALID_ARGUMENT error is returned. + """ + + type_ = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class Image(proto.Message): + r"""[Product][google.cloud.retail.v2alpha.Product] image. + Recommendations AI and Retail Search do not use product images to + improve prediction and search results. However, product images can + be returned in results, and are shown in prediction or search + previews in the console. + + Attributes: + uri (str): + Required. URI of the image. + + This field must be a valid UTF-8 encoded URI with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + height (int): + Height of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + width (int): + Width of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + height = proto.Field( + proto.INT32, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + + +class Interval(proto.Message): + r"""A floating point interval. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum = proto.Field( + proto.DOUBLE, + number=1, + oneof='min', + ) + exclusive_minimum = proto.Field( + proto.DOUBLE, + number=2, + oneof='min', + ) + maximum = proto.Field( + proto.DOUBLE, + number=3, + oneof='max', + ) + exclusive_maximum = proto.Field( + proto.DOUBLE, + number=4, + oneof='max', + ) + + +class PriceInfo(proto.Message): + r"""The price information of a + [Product][google.cloud.retail.v2alpha.Product]. + + Attributes: + currency_code (str): + The 3-letter currency code defined in `ISO + 4217 `__. + + If this field is an unrecognizable currency code, an + INVALID_ARGUMENT error is returned. + + The + [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s with the + same + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] + must share the same + [currency_code][google.cloud.retail.v2alpha.PriceInfo.currency_code]. + Otherwise, a FAILED_PRECONDITION error is returned. + price (float): + Price of the product. + + Google Merchant Center property + `price `__. + Schema.org property + `Offer.price `__. + original_price (float): + Price of the product without any discount. If zero, by + default set to be the + [price][google.cloud.retail.v2alpha.PriceInfo.price]. + cost (float): + The costs associated with the sale of a particular product. + Used for gross profit reporting. + + - Profit = + [price][google.cloud.retail.v2alpha.PriceInfo.price] - + [cost][google.cloud.retail.v2alpha.PriceInfo.cost] + + Google Merchant Center property + `cost_of_goods_sold `__. + price_effective_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2alpha.PriceInfo.price] starts + to be effective. This can be set as a future timestamp, and + the [price][google.cloud.retail.v2alpha.PriceInfo.price] is + only used for search after + [price_effective_time][google.cloud.retail.v2alpha.PriceInfo.price_effective_time]. + If so, the + [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + is used before + [price_effective_time][google.cloud.retail.v2alpha.PriceInfo.price_effective_time]. + + Do not set if + [price][google.cloud.retail.v2alpha.PriceInfo.price] is + always effective because it will cause additional latency + during search. + price_expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2alpha.PriceInfo.price] stops + to be effective. The + [price][google.cloud.retail.v2alpha.PriceInfo.price] is used + for search before + [price_expire_time][google.cloud.retail.v2alpha.PriceInfo.price_expire_time]. + If this field is set, the + [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + is used after + [price_expire_time][google.cloud.retail.v2alpha.PriceInfo.price_expire_time]. + + Do not set if + [price][google.cloud.retail.v2alpha.PriceInfo.price] is + always effective because it will cause additional latency + during search. + price_range (google.cloud.retail_v2alpha.types.PriceInfo.PriceRange): + Output only. The price range of all the child + [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s grouped + together on the + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]. Only + populated for + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct]. + Do not set this field in API requests. + """ + + class PriceRange(proto.Message): + r"""The price range of all + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. + + Attributes: + price (google.cloud.retail_v2alpha.types.Interval): + The inclusive + [Product.pricing_info.price][google.cloud.retail.v2alpha.PriceInfo.price] + interval of all + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] having the + same + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. + original_price (google.cloud.retail_v2alpha.types.Interval): + The inclusive + [Product.pricing_info.original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] + internal of all + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] having the + same + [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. + """ + + price = proto.Field( + proto.MESSAGE, + number=1, + message='Interval', + ) + original_price = proto.Field( + proto.MESSAGE, + number=2, + message='Interval', + ) + + currency_code = proto.Field( + proto.STRING, + number=1, + ) + price = proto.Field( + proto.FLOAT, + number=2, + ) + original_price = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + price_effective_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + price_expire_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + price_range = proto.Field( + proto.MESSAGE, + number=7, + message=PriceRange, + ) + + +class Rating(proto.Message): + r"""The rating of a [Product][google.cloud.retail.v2alpha.Product]. + + Attributes: + rating_count (int): + The total number of ratings. This value is independent of + the value of + [rating_histogram][google.cloud.retail.v2alpha.Rating.rating_histogram]. + + This value must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + average_rating (float): + The average rating of the + [Product][google.cloud.retail.v2alpha.Product]. + + The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT + error is returned. + rating_histogram (Sequence[int]): + List of rating counts per rating value (index = rating - 1). + The list is empty if there is no rating. If the list is + non-empty, its size is always 5. Otherwise, an + INVALID_ARGUMENT error is returned. + + For example, [41, 14, 13, 47, 303]. It means that the + [Product][google.cloud.retail.v2alpha.Product] got 41 + ratings with 1 star, 14 ratings with 2 star, and so on. + """ + + rating_count = proto.Field( + proto.INT32, + number=1, + ) + average_rating = proto.Field( + proto.FLOAT, + number=2, + ) + rating_histogram = proto.RepeatedField( + proto.INT32, + number=3, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. + + Always use a hashed value for this ID. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + ip_address (str): + The end user's IP address. This field is used to extract + location information for personalization. + + This field must be either an IPv4 address (e.g. + "104.133.9.80") or an IPv6 address (e.g. + "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an + INVALID_ARGUMENT error is returned. + + This should not be set when: + + - setting + [SearchRequest.user_info][google.cloud.retail.v2alpha.SearchRequest.user_info]. + - using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2alpha.UserInfo.direct_user_request] + is set. + user_agent (str): + User agent as included in the HTTP header. Required for + getting + [SearchResponse.sponsored_results][google.cloud.retail.v2alpha.SearchResponse.sponsored_results]. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2alpha.UserInfo.direct_user_request] + is set. + direct_user_request (bool): + True if the request is made directly from the end user, in + which case the + [ip_address][google.cloud.retail.v2alpha.UserInfo.ip_address] + and + [user_agent][google.cloud.retail.v2alpha.UserInfo.user_agent] + can be populated from the HTTP request. This flag should be + set only if the API request is made directly from the end + user such as a mobile app (and not if a gateway or a server + is processing and pushing the user events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent]. + """ + + user_id = proto.Field( + proto.STRING, + number=1, + ) + ip_address = proto.Field( + proto.STRING, + number=2, + ) + user_agent = proto.Field( + proto.STRING, + number=3, + ) + direct_user_request = proto.Field( + proto.BOOL, + number=4, + ) + + +class LocalInventory(proto.Message): + r"""The inventory information at a place (e.g. a store) + identified by a place ID. + + Attributes: + place_id (str): + The place ID for the current set of inventory + information. + price_info (google.cloud.retail_v2alpha.types.PriceInfo): + Product price and cost information. + + Google Merchant Center property + `price `__. + attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): + Additional local inventory attributes, for example, store + name, promotion tags, etc. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - At most 30 attributes are allowed. + - The key must be a UTF-8 encoded string with a length + limit of 32 characters. + - The key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis + or KEY_1_LIKE_THIS. + - The attribute values must be of the same type (text or + number). + - Only 1 value is allowed for each attribute. + - For text values, the length limit is 256 UTF-8 + characters. + - The attribute does not support search. The ``searchable`` + field should be unset or set to false. + - The max summed total bytes of custom attribute keys and + values per product is 5MiB. + fulfillment_types (Sequence[str]): + Input only. Supported fulfillment types. Valid fulfillment + type values include commonly used types (such as pickup in + store and same day delivery), and custom types. Customers + have to map custom types to their display names before + rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + All the elements must be distinct. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + place_id = proto.Field( + proto.STRING, + number=1, + ) + price_info = proto.Field( + proto.MESSAGE, + number=2, + message='PriceInfo', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='CustomAttribute', + ) + fulfillment_types = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py new file mode 100644 index 00000000..f3bb27b3 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'CompleteQueryRequest', + 'CompleteQueryResponse', + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Auto-complete parameters. + + Attributes: + catalog (str): + Required. Catalog for which the completion is performed. + + Full resource name of catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + query (str): + Required. The query used to generate + suggestions. + The maximum number of allowed characters is 255. + visitor_id (str): + Required field. A unique identifier for tracking visitors. + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + language_codes (Sequence[str]): + The language filters applied to the output suggestions. If + set, it should contain the language of the query. If not + set, suggestions are returned without considering language + restrictions. This is the BCP-47 language code, such as + "en-US" or "sr-Latn". For more information, see `Tags for + Identifying + Languages `__. The + maximum number of language codes is 3. + device_type (str): + The device type context for completion suggestions. It is + useful to apply different suggestions on different device + types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the + suggestions are across all device types. + + Supported formats: + + - ``UNKNOWN_DEVICE_TYPE`` + + - ``DESKTOP`` + + - ``MOBILE`` + + - A customized string starts with ``OTHER_``, e.g. + ``OTHER_IPHONE``. + dataset (str): + Determines which dataset to use for fetching completion. + "user-data" will use the imported dataset through + [CompletionService.ImportCompletionData][google.cloud.retail.v2alpha.CompletionService.ImportCompletionData]. + "cloud-retail" will use the dataset generated by cloud + retail based on user events. If leave empty, it will use the + "user-data". + + Current supported values: + + - user-data + + - cloud-retail This option requires additional + allowlisting. Before using cloud-retail, contact Cloud + Retail support team first. + max_suggestions (int): + Completion max suggestions. If left unset or set to 0, then + will fallback to the configured value + [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions]. + + The maximum allowed max suggestions is 20. If it is set + higher, it will be capped by 20. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + visitor_id = proto.Field( + proto.STRING, + number=7, + ) + language_codes = proto.RepeatedField( + proto.STRING, + number=3, + ) + device_type = proto.Field( + proto.STRING, + number=4, + ) + dataset = proto.Field( + proto.STRING, + number=6, + ) + max_suggestions = proto.Field( + proto.INT32, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response of the auto-complete query. + + Attributes: + completion_results (Sequence[google.cloud.retail_v2alpha.types.CompleteQueryResponse.CompletionResult]): + Results of the matching suggestions. The + result list is ordered and the first result is + top suggestion. + attribution_token (str): + A unique complete token. This should be included in the + [UserEvent.completion_detail][google.cloud.retail.v2alpha.UserEvent.completion_detail] + for search events resulting from this completion, which + enables accurate attribution of complete model performance. + recent_search_results (Sequence[google.cloud.retail_v2alpha.types.CompleteQueryResponse.RecentSearchResult]): + Matched recent searches of this user. The maximum number of + recent searches is 10. This field is a restricted feature. + Contact Retail Search support team if you are interested in + enabling it. + + This feature is only available when + [CompleteQueryRequest.visitor_id][google.cloud.retail.v2alpha.CompleteQueryRequest.visitor_id] + field is set and + [UserEvent][google.cloud.retail.v2alpha.UserEvent] is + imported. The recent searches satisfy the follow rules: + + - They are ordered from latest to oldest. + - They are matched with + [CompleteQueryRequest.query][google.cloud.retail.v2alpha.CompleteQueryRequest.query] + case insensitively. + - They are transformed to lower cases. + - They are UTF-8 safe. + + Recent searches are deduplicated. More recent searches will + be reserved when duplication happens. + """ + + class CompletionResult(proto.Message): + r"""Resource that represents completion results. + + Attributes: + suggestion (str): + The suggestion for the query. + attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): + Custom attributes for the suggestion term. + + - For "user-data", the attributes are additional custom + attributes ingested through BigQuery. + - For "cloud-retail", the attributes are product attributes + generated by Cloud Retail. + """ + + suggestion = proto.Field( + proto.STRING, + number=1, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=common.CustomAttribute, + ) + + class RecentSearchResult(proto.Message): + r"""Recent search of this user. + + Attributes: + recent_search (str): + The recent search query. + """ + + recent_search = proto.Field( + proto.STRING, + number=1, + ) + + completion_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=CompletionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + recent_search_results = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=RecentSearchResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py new file mode 100644 index 00000000..93e84d08 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'Control', + }, +) + + +class Control(proto.Message): + r"""Configures dynamic serving time metadata that is used to pre + and post process search/recommendation model results. + + 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: + facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec): + A facet specification to perform faceted + search. + + This field is a member of `oneof`_ ``control``. + rule (google.cloud.retail_v2alpha.types.Rule): + A rule control - a condition-action pair. + Enacts a set action when the condition is + triggered. For example: Boost "gShoe" when query + full matches "Running Shoes". + + This field is a member of `oneof`_ ``control``. + name (str): + Immutable. Fully qualified name + projects/\ */locations/global/catalogs/*/controls/\* + display_name (str): + Required. The human readable control display name. Used in + Retail UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is thrown. + associated_serving_config_ids (Sequence[str]): + Output only. List of serving configuration + ids that that are associated with this control. + Note the association is managed via the + ServingConfig, this is an output only + denormalizeed view. Assumed to be in the same + catalog. + solution_types (Sequence[google.cloud.retail_v2alpha.types.SolutionType]): + Required. Immutable. The solution types that the serving + config is used for. Currently we support setting only one + type of solution at creation time. + + Only ``SOLUTION_TYPE_SEARCH`` value is supported at the + moment. If no solution type is provided at creation time, + will default to SOLUTION_TYPE_SEARCH. + search_solution_use_case (Sequence[google.cloud.retail_v2alpha.types.SearchSolutionUseCase]): + Required. Specifies the use case for the control. Affects + what condition fields can be set. Only settable by search + controls. Will default to SEARCH_SOLUTION_USE_CASE_SEARCH if + not specified. Currently only allow one + search_solution_use_case per control. + """ + + facet_spec = proto.Field( + proto.MESSAGE, + number=3, + oneof='control', + message=search_service.SearchRequest.FacetSpec, + ) + rule = proto.Field( + proto.MESSAGE, + number=4, + oneof='control', + message=common.Rule, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + associated_serving_config_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + solution_types = proto.RepeatedField( + proto.ENUM, + number=6, + enum=common.SolutionType, + ) + search_solution_use_case = proto.RepeatedField( + proto.ENUM, + number=7, + enum=common.SearchSolutionUseCase, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py new file mode 100644 index 00000000..da0c4915 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'CreateControlRequest', + 'UpdateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + }, +) + + +class CreateControlRequest(proto.Message): + r"""Request for CreateControl method. + + Attributes: + parent (str): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + control (google.cloud.retail_v2alpha.types.Control): + Required. The Control to create. + control_id (str): + Required. The ID to use for the Control, which will become + the final component of the Control's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-_/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + control = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_control.Control, + ) + control_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateControlRequest(proto.Message): + r"""Request for UpdateControl method. + + Attributes: + control (google.cloud.retail_v2alpha.types.Control): + Required. The Control to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Control][google.cloud.retail.v2alpha.Control] to update. + The following are NOT supported: + + - [Control.name][google.cloud.retail.v2alpha.Control.name] + + If not set or empty, all supported fields are updated. + """ + + control = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_control.Control, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteControlRequest(proto.Message): + r"""Request for DeleteControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetControlRequest(proto.Message): + r"""Request for GetControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListControlsRequest(proto.Message): + r"""Request for ListControls method. + + Attributes: + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 50. Max + allowed value is 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListControls`` call. Provide this to retrieve the + subsequent page. + filter (str): + Optional. A filter to apply on the list results. Supported + features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2alpha.ListControlsRequest.filter] + is unset. + - List controls that are used in a single ServingConfig: + 'serving_config = "boosted_home_page_cvr"' + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListControlsResponse(proto.Message): + r"""Response for ListControls method. + + Attributes: + controls (Sequence[google.cloud.retail_v2alpha.types.Control]): + All the Controls for a given catalog. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + controls = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_control.Control, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py new file mode 100644 index 00000000..ffb42fde --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + }, +) + + +class ExportErrorsConfig(proto.Message): + r"""Configuration of destination for Export related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage path for import errors. This must be an + empty, existing Cloud Storage bucket. Export errors will be + written to a file in this bucket, one per line, as a + JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ExportMetadata(proto.Message): + r"""Metadata related to the progress of the Export operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ExportProductsResponse(proto.Message): + r"""Response of the ExportProductsRequest. If the long running + operation is done, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2alpha.types.ExportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExportErrorsConfig', + ) + + +class ExportUserEventsResponse(proto.Message): + r"""Response of the ExportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2alpha.types.ExportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExportErrorsConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py new file mode 100644 index 00000000..b6260358 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py @@ -0,0 +1,691 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import user_event +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'GcsSource', + 'BigQuerySource', + 'ProductInlineSource', + 'UserEventInlineSource', + 'ImportErrorsConfig', + 'ImportProductsRequest', + 'ImportUserEventsRequest', + 'ImportCompletionDataRequest', + 'ProductInputConfig', + 'UserEventInputConfig', + 'CompletionDataInputConfig', + 'ImportMetadata', + 'ImportProductsResponse', + 'ImportUserEventsResponse', + 'UserEventImportSummary', + 'ImportCompletionDataResponse', + }, +) + + +class GcsSource(proto.Message): + r"""Google Cloud Storage location for input content. + format. + + Attributes: + input_uris (Sequence[str]): + Required. Google Cloud Storage URIs to input files. URI can + be up to 2000 characters long. URIs can match the full + object path (for example, + ``gs://bucket/directory/object.json``) or a pattern matching + one or more files, such as ``gs://bucket/directory/*.json``. + A request can contain at most 100 files, and each file can + be up to 2 GB. See `Importing product + information `__ + for the expected file format and setup instructions. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2alpha.Product] per line. + Each product must have a valid + [Product.id][google.cloud.retail.v2alpha.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2alpha.UserEvent] per + line. + - ``user_event_ga360``: Using + https://support.google.com/analytics/answer/3437719. + + Supported values for control imports: + + - 'control' (default): One JSON + [Control][google.cloud.retail.v2alpha.Control] per line. + + Supported values for catalog attribute imports: + + - 'catalog_attribute' (default): One CSV + [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] + per line. + """ + + input_uris = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID (can be project # or ID) that + the BigQuery source is in with a length limit of + 128 characters. If not specified, inherits the + project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2alpha.Product] per line. + Each product must have a valid + [Product.id][google.cloud.retail.v2alpha.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2alpha.UserEvent] per + line. + - ``user_event_ga360``: The schema is available here: + https://support.google.com/analytics/answer/3437719. + - ``user_event_ga4``: This feature is in private preview. + Please contact the support team for importing Google + Analytics 4 events. The schema is available here: + https://support.google.com/analytics/answer/7029846. + + Supported values for auto-completion imports: + + - ``suggestions`` (default): One JSON completion suggestion + per line. + - ``denylist``: One JSON deny suggestion per line. + - ``allowlist``: One JSON allow suggestion per line. + """ + + partition_date = proto.Field( + proto.MESSAGE, + number=6, + oneof='partition', + message=date_pb2.Date, + ) + project_id = proto.Field( + proto.STRING, + number=5, + ) + dataset_id = proto.Field( + proto.STRING, + number=1, + ) + table_id = proto.Field( + proto.STRING, + number=2, + ) + gcs_staging_dir = proto.Field( + proto.STRING, + number=3, + ) + data_schema = proto.Field( + proto.STRING, + number=4, + ) + + +class ProductInlineSource(proto.Message): + r"""The inline source for the input config for ImportProducts + method. + + Attributes: + products (Sequence[google.cloud.retail_v2alpha.types.Product]): + Required. A list of products to update/create. Each product + must have a valid + [Product.id][google.cloud.retail.v2alpha.Product.id]. + Recommended max of 100 items. + """ + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=product.Product, + ) + + +class UserEventInlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (Sequence[google.cloud.retail_v2alpha.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + +class ImportErrorsConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage prefix for import errors. This must be + an empty, existing Cloud Storage directory. Import errors + will be written to sharded files in this directory, one per + line, as a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportProductsRequest(proto.Message): + r"""Request message for Import methods. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` + + If no updateMask is specified, requires products.create + permission. If updateMask is specified, requires + products.update permission. + request_id (str): + Deprecated. This field has no effect. + input_config (google.cloud.retail_v2alpha.types.ProductInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported 'products' to update. If not set, will + by default update all fields. + reconciliation_mode (google.cloud.retail_v2alpha.types.ImportProductsRequest.ReconciliationMode): + The mode of reconciliation between existing products and the + products to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + """ + class ReconciliationMode(proto.Enum): + r"""Indicates how imported products are reconciled with the + existing products created or imported before. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + request_id = proto.Field( + proto.STRING, + number=6, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='ProductInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + reconciliation_mode = proto.Field( + proto.ENUM, + number=5, + enum=ReconciliationMode, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=7, + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + input_config (google.cloud.retail_v2alpha.types.UserEventInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='UserEventInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + + +class ImportCompletionDataRequest(proto.Message): + r"""Request message for ImportCompletionData methods. + + Attributes: + parent (str): + Required. The catalog which the suggestions dataset belongs + to. + + Format: + ``projects/1234/locations/global/catalogs/default_catalog``. + input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): + Required. The desired input location of the + data. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='CompletionDataInputConfig', + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=3, + ) + + +class ProductInputConfig(proto.Message): + r"""The input config source for products. + + 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: + product_inline_source (google.cloud.retail_v2alpha.types.ProductInlineSource): + The Inline source for the input content for + products. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2alpha.types.GcsSource): + Google Cloud Storage location for the input + content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + product_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='ProductInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class UserEventInputConfig(proto.Message): + r"""The input config source for user events. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user_event_inline_source (google.cloud.retail_v2alpha.types.UserEventInlineSource): + Required. The Inline source for the input + content for UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2alpha.types.GcsSource): + Required. Google Cloud Storage location for + the input content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): + Required. BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + user_event_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='UserEventInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class CompletionDataInputConfig(proto.Message): + r"""The input config source for completion data. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): + Required. BigQuery input source. + Add the IAM permission "BigQuery Data Viewer" + for + cloud-retail-customer-data-access@system.gserviceaccount.com + before using this feature otherwise an error is + thrown. + + This field is a member of `oneof`_ ``source``. + """ + + big_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='BigQuerySource', + ) + + +class ImportMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + request_id (str): + Deprecated. This field is never set. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=3, + ) + failure_count = proto.Field( + proto.INT64, + number=4, + ) + request_id = proto.Field( + proto.STRING, + number=5, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=6, + ) + + +class ImportProductsResponse(proto.Message): + r"""Response of the + [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + import_summary (google.cloud.retail_v2alpha.types.UserEventImportSummary): + Aggregated statistics of user event import + status. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + import_summary = proto.Field( + proto.MESSAGE, + number=3, + message='UserEventImportSummary', + ) + + +class UserEventImportSummary(proto.Message): + r"""A summary of import result. The UserEventImportSummary + summarizes the import status for user events. + + Attributes: + joined_events_count (int): + Count of user events imported with complete + existing catalog information. + unjoined_events_count (int): + Count of user events imported, but with + catalog information not found in the imported + catalog. + """ + + joined_events_count = proto.Field( + proto.INT64, + number=1, + ) + unjoined_events_count = proto.Field( + proto.INT64, + number=2, + ) + + +class ImportCompletionDataResponse(proto.Message): + r"""Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. + 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 (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py new file mode 100644 index 00000000..51233cae --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import user_event as gcr_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'PredictRequest', + 'PredictResponse', + }, +) + + +class PredictRequest(proto.Message): + r"""Request message for Predict method. + + Attributes: + placement (str): + Required. Full resource name of the format: + {name=projects/*/locations/global/catalogs/default_catalog/placements/*} + The ID of the Recommendations AI placement. Before you can + request predictions from your model, you must create at + least one placement for it. For more information, see + `Managing + placements `__. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements + user_event (google.cloud.retail_v2alpha.types.UserEvent): + Required. Context about the user, what they + are looking at and what action they took to + trigger the predict request. Note that this user + event detail won't be ingested to userEvent + logs. Thus, a separate userEvent write request + is required for event logging. + page_size (int): + Maximum number of results to return per page. + Set this property to the number of prediction + results needed. If zero, the service will choose + a reasonable default. The maximum allowed value + is 100. Values above 100 will be coerced to 100. + page_token (str): + The previous PredictResponse.next_page_token. + filter (str): + Filter for restricting prediction results with a length + limit of 5,000 characters. Accepts values for tags and the + ``filterOutOfStockItems`` flag. + + - Tag expressions. Restricts predictions to products that + match all of the specified tags. Boolean operators ``OR`` + and ``NOT`` are supported if the expression is enclosed + in parentheses, and must be separated from the tag values + by a space. ``-"tagA"`` is also supported and is + equivalent to ``NOT "tagA"``. Tag values must be double + quoted UTF-8 encoded strings with a size limit of 1,000 + characters. + + Note: "Recently viewed" models don't support tag + filtering at the moment. + + - filterOutOfStockItems. Restricts predictions to products + that do not have a stockState value of OUT_OF_STOCK. + + Examples: + + - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT + "promotional") + - filterOutOfStockItems tag=(-"promotional") + - filterOutOfStockItems + + If your filter blocks all prediction results, the API will + return generic (unfiltered) popular products. If you only + want results strictly matching the filters, set + ``strictFiltering`` to True in ``PredictRequest.params`` to + receive empty results instead. Note that the API will never + return items with storageStatus of "EXPIRED" or "DELETED" + regardless of filter choices. + validate_only (bool): + Use validate only mode for this prediction + query. If set to true, a dummy model will be + used that returns arbitrary products. Note that + the validate only mode should only be used for + testing the API, or if the model is not ready. + params (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific parameters for the predictions. + + Allowed values: + + - ``returnProduct``: Boolean. If set to true, the + associated product object will be returned in the + ``results.metadata`` field in the prediction response. + - ``returnScore``: Boolean. If set to true, the prediction + 'score' corresponding to each returned product will be + set in the ``results.metadata`` field in the prediction + response. The given 'score' indicates the probability of + an product being clicked/purchased given the user's + context and history. + - ``strictFiltering``: Boolean. True by default. If set to + false, the service will return generic (unfiltered) + popular products instead of empty if your filter blocks + all prediction results. + - ``priceRerankLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of + {'no-price-reranking', 'low-price-reranking', + 'medium-price-reranking', 'high-price-reranking'}. This + gives request-level control and adjusts prediction + results based on product price. + - ``diversityLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of {'no-diversity', + 'low-diversity', 'medium-diversity', 'high-diversity', + 'auto-diversity'}. This gives request-level control and + adjusts prediction results based on product category. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters, and cannot be empty. Values can + be empty, and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + placement = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + filter = proto.Field( + proto.STRING, + number=5, + ) + validate_only = proto.Field( + proto.BOOL, + number=6, + ) + params = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class PredictResponse(proto.Message): + r"""Response message for predict method. + + Attributes: + results (Sequence[google.cloud.retail_v2alpha.types.PredictResponse.PredictionResult]): + A list of recommended products. The order + represents the ranking (from the most relevant + product to the least). + attribution_token (str): + A unique attribution token. This should be included in the + [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs + resulting from this recommendation, which enables accurate + attribution of recommendation model performance. + missing_ids (Sequence[str]): + IDs of products in the request that were + missing from the inventory. + validate_only (bool): + True if the validateOnly property was set in + the request. + """ + + class PredictionResult(proto.Message): + r"""PredictionResult represents the recommendation prediction + results. + + Attributes: + id (str): + ID of the recommended product + metadata (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional product metadata / annotations. + + Possible values: + + - ``product``: JSON representation of the product. Will be + set if ``returnProduct`` is set to true in + ``PredictRequest.params``. + - ``score``: Prediction score in double value. Will be set + if ``returnScore`` is set to true in + ``PredictRequest.params``. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + metadata = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=PredictionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + missing_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py new file mode 100644 index 00000000..492a51ff --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py @@ -0,0 +1,705 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'Product', + }, +) + + +class Product(proto.Message): + r"""Product captures all metadata information of items to be + recommended or searched. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this product becomes unavailable for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + If it is set, the + [Product][google.cloud.retail.v2alpha.Product] is not + available for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + after + [expire_time][google.cloud.retail.v2alpha.Product.expire_time]. + However, the product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + [expire_time][google.cloud.retail.v2alpha.Product.expire_time] + must be later than + [available_time][google.cloud.retail.v2alpha.Product.available_time] + and + [publish_time][google.cloud.retail.v2alpha.Product.publish_time], + otherwise an INVALID_ARGUMENT error is thrown. + + Corresponding properties: Google Merchant Center property + `expiration_date `__. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Input only. The TTL (time to live) of the product. + + If it is set, it must be a non-negative value, and + [expire_time][google.cloud.retail.v2alpha.Product.expire_time] + is set as current timestamp plus + [ttl][google.cloud.retail.v2alpha.Product.ttl]. The derived + [expire_time][google.cloud.retail.v2alpha.Product.expire_time] + is returned in the output and + [ttl][google.cloud.retail.v2alpha.Product.ttl] is left blank + when retrieving the + [Product][google.cloud.retail.v2alpha.Product]. + + If it is set, the product is not available for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + after current timestamp plus + [ttl][google.cloud.retail.v2alpha.Product.ttl]. However, the + product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. + + This field is a member of `oneof`_ ``expiration``. + name (str): + Immutable. Full resource name of the product, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. + id (str): + Immutable. [Product][google.cloud.retail.v2alpha.Product] + identifier, which is the final component of + [name][google.cloud.retail.v2alpha.Product.name]. For + example, this field is "id_1", if + [name][google.cloud.retail.v2alpha.Product.name] is + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `id `__. + Schema.org property + `Product.sku `__. + type_ (google.cloud.retail_v2alpha.types.Product.Type): + Immutable. The type of the product. Default to + [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2alpha.ProductLevelConfig.ingestion_product_type] + if unset. + primary_product_id (str): + Variant group identifier. Must be an + [id][google.cloud.retail.v2alpha.Product.id], with the same + parent branch with this product. Otherwise, an error is + thrown. + + For + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]s, this field + can only be empty or set to the same value as + [id][google.cloud.retail.v2alpha.Product.id]. + + For VARIANT [Product][google.cloud.retail.v2alpha.Product]s, + this field cannot be empty. A maximum of 2,000 products are + allowed to share the same + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]. Otherwise, + an INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `item_group_id `__. + Schema.org property + `Product.inProductGroupWithID `__. + collection_member_ids (Sequence[str]): + The [id][google.cloud.retail.v2alpha.Product.id] of the + collection members when + [type][google.cloud.retail.v2alpha.Product.type] is + [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION]. + + Non-existent product ids are allowed. The + [type][google.cloud.retail.v2alpha.Product.type] of the + members must be either + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + or + [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + otherwise and INVALID_ARGUMENT error is thrown. Should not + set it for other types. A maximum of 1000 values are + allowed. Otherwise, an INVALID_ARGUMENT error is return. + gtin (str): + The Global Trade Item Number (GTIN) of the product. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This field must be a Unigram. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `gtin `__. + Schema.org property + `Product.isbn `__, + `Product.gtin8 `__, + `Product.gtin12 `__, + `Product.gtin13 `__, or + `Product.gtin14 `__. + + If the value is not a valid GTIN, an INVALID_ARGUMENT error + is returned. + categories (Sequence[str]): + Product categories. This field is repeated for supporting + one product belonging to several parallel categories. + Strongly recommended using the full path for better search / + recommendation quality. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + For example, if a shoes product belongs to both ["Shoes & + Accessories" -> "Shoes"] and ["Sports & Fitness" -> + "Athletic Clothing" -> "Shoes"], it could be represented as: + + :: + + "categories": [ + "Shoes & Accessories > Shoes", + "Sports & Fitness > Athletic Clothing > Shoes" + ] + + Must be set for + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] otherwise an + INVALID_ARGUMENT error is returned. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. Empty values + are not allowed. Each value must be a UTF-8 encoded string + with a length limit of 5,000 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `google_product_category `__. + Schema.org property [Product.category] + (https://schema.org/category). + title (str): + Required. Product title. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `title `__. + Schema.org property + `Product.name `__. + brands (Sequence[str]): + The brands of the product. + + A maximum of 30 brands are allowed. Each brand must be a + UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `brand `__. + Schema.org property + `Product.brand `__. + description (str): + Product description. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `description `__. + Schema.org property + `Product.description `__. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. + + For product prediction, this field is ignored and the model + automatically detects the text language. The + [Product][google.cloud.retail.v2alpha.Product] can include + text in different languages, but duplicating + [Product][google.cloud.retail.v2alpha.Product]s to provide + text in multiple languages can result in degraded model + performance. + + For product search this field is in use. It defaults to + "en-US" if unset. + attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): + Highly encouraged. Extra product attributes to be included. + For example, for products, this could include the store + name, vendor, style, color, etc. These are very strong + signals for recommendation model, thus we highly recommend + providing the attributes here. + + Features that can take on one of a limited number of + possible values. Two types of features can be set are: + + Textual features. some examples would be the brand/maker of + a product, or country of a customer. Numerical features. + Some examples would be the height/weight of a product, or + age of a customer. + + For example: + ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - Max entries count: 200. + - The key must be a UTF-8 encoded string with a length + limit of 128 characters. + - For indexable attribute, the key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, + ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a + non-empty UTF-8 encoded string with a length limit of 256 + characters. + - For number attributes, at most 400 values are allowed. + tags (Sequence[str]): + Custom tags associated with the product. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. This value + must be a UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This tag can be used for filtering recommendation results by + passing the tag as part of the + [PredictRequest.filter][google.cloud.retail.v2alpha.PredictRequest.filter]. + + Corresponding properties: Google Merchant Center property + `custom_label_0–4 `__. + price_info (google.cloud.retail_v2alpha.types.PriceInfo): + Product price and cost information. + + Corresponding properties: Google Merchant Center property + `price `__. + rating (google.cloud.retail_v2alpha.types.Rating): + The rating of this product. + available_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this + [Product][google.cloud.retail.v2alpha.Product] becomes + available for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + availability (google.cloud.retail_v2alpha.types.Product.Availability): + The online availability of the + [Product][google.cloud.retail.v2alpha.Product]. Default to + [Availability.IN_STOCK][google.cloud.retail.v2alpha.Product.Availability.IN_STOCK]. + + Corresponding properties: Google Merchant Center property + `availability `__. + Schema.org property + `Offer.availability `__. + available_quantity (google.protobuf.wrappers_pb2.Int32Value): + The available quantity of the item. + fulfillment_info (Sequence[google.cloud.retail_v2alpha.types.FulfillmentInfo]): + Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + All the elements must have distinct + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type]. + Otherwise, an INVALID_ARGUMENT error is returned. + uri (str): + Canonical URL directly linking to the product detail page. + + It is strongly recommended to provide a valid uri for the + product, otherwise the service performance could be + significantly degraded. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `link `__. + Schema.org property `Offer.url `__. + images (Sequence[google.cloud.retail_v2alpha.types.Image]): + Product images for the product. We highly recommend putting + the main image first. + + A maximum of 300 images are allowed. + + Corresponding properties: Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + audience (google.cloud.retail_v2alpha.types.Audience): + The target group associated with a given + audience (e.g. male, veterans, car owners, + musicians, etc.) of the product. + color_info (google.cloud.retail_v2alpha.types.ColorInfo): + The color of the product. + + Corresponding properties: Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + sizes (Sequence[str]): + The size of the product. To represent different size systems + or size types, consider using this format: + [[[size_system:]size_type:]size_value]. + + For example, in "US:MENS:M", "US" represents size system; + "MENS" represents size type; "M" represents size value. In + "GIRLS:27", size system is empty; "GIRLS" represents size + type; "27" represents size value. In "32 inches", both size + system and size type are empty, while size value is "32 + inches". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `size `__, + `size_type `__, + and + `size_system `__. + Schema.org property + `Product.size `__. + materials (Sequence[str]): + The material of the product. For example, "leather", + "wooden". + + A maximum of 20 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 200 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `material `__. + Schema.org property + `Product.material `__. + patterns (Sequence[str]): + The pattern or graphic print of the product. For example, + "striped", "polka dot", "paisley". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `pattern `__. + Schema.org property + `Product.pattern `__. + conditions (Sequence[str]): + The condition of the product. Strongly encouraged to use the + standard values: "new", "refurbished", "used". + + A maximum of 1 value is allowed per + [Product][google.cloud.retail.v2alpha.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `condition `__. + Schema.org property + `Offer.itemCondition `__. + promotions (Sequence[google.cloud.retail_v2alpha.types.Promotion]): + The promotions applied to the product. A maximum of 10 + values are allowed per + [Product][google.cloud.retail.v2alpha.Product]. Only + [Promotion.promotion_id][google.cloud.retail.v2alpha.Promotion.promotion_id] + will be used, other fields will be ignored if set. + publish_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the product is published by the retailer + for the first time, which indicates the freshness of the + products. Note that this field is different from + [available_time][google.cloud.retail.v2alpha.Product.available_time], + given it purely describes product freshness regardless of + when it is available on search and recommendation. + retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the + [Product][google.cloud.retail.v2alpha.Product]s are returned + in + [SearchResponse][google.cloud.retail.v2alpha.SearchResponse]. + + Supported fields for all + [type][google.cloud.retail.v2alpha.Product.type]s: + + - [audience][google.cloud.retail.v2alpha.Product.audience] + - [availability][google.cloud.retail.v2alpha.Product.availability] + - [brands][google.cloud.retail.v2alpha.Product.brands] + - [color_info][google.cloud.retail.v2alpha.Product.color_info] + - [conditions][google.cloud.retail.v2alpha.Product.conditions] + - [gtin][google.cloud.retail.v2alpha.Product.gtin] + - [materials][google.cloud.retail.v2alpha.Product.materials] + - [name][google.cloud.retail.v2alpha.Product.name] + - [patterns][google.cloud.retail.v2alpha.Product.patterns] + - [price_info][google.cloud.retail.v2alpha.Product.price_info] + - [rating][google.cloud.retail.v2alpha.Product.rating] + - [sizes][google.cloud.retail.v2alpha.Product.sizes] + - [title][google.cloud.retail.v2alpha.Product.title] + - [uri][google.cloud.retail.v2alpha.Product.uri] + + Supported fields only for + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION]: + + - [categories][google.cloud.retail.v2alpha.Product.categories] + - [description][google.cloud.retail.v2alpha.Product.description] + - [images][google.cloud.retail.v2alpha.Product.images] + + Supported fields only for + [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT]: + + - Only the first image in + [images][google.cloud.retail.v2alpha.Product.images] + + To mark + [attributes][google.cloud.retail.v2alpha.Product.attributes] + as retrievable, include paths of the form "attributes.key" + where "key" is the key of a custom attribute, as specified + in + [attributes][google.cloud.retail.v2alpha.Product.attributes]. + + For + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION], + the following fields are always returned in + [SearchResponse][google.cloud.retail.v2alpha.SearchResponse] + by default: + + - [name][google.cloud.retail.v2alpha.Product.name] + + For + [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT], + the following fields are always returned in by default: + + - [name][google.cloud.retail.v2alpha.Product.name] + - [color_info][google.cloud.retail.v2alpha.Product.color_info] + + Maximum number of paths is 30. Otherwise, an + INVALID_ARGUMENT error is returned. + + Note: Returning more fields in + [SearchResponse][google.cloud.retail.v2alpha.SearchResponse] + may increase response payload size and serving latency. + variants (Sequence[google.cloud.retail_v2alpha.types.Product]): + Output only. Product variants grouped together on primary + product which share similar product attributes. It's + automatically grouped by + [primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] + for all the product variants. Only populated for + [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct]. + Do not set this field in API requests. + """ + class Type(proto.Enum): + r"""The type of this product.""" + TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + VARIANT = 2 + COLLECTION = 3 + + class Availability(proto.Enum): + r"""Product availability. If this field is unspecified, the + product is assumed to be in stock. + """ + AVAILABILITY_UNSPECIFIED = 0 + IN_STOCK = 1 + OUT_OF_STOCK = 2 + PREORDER = 3 + BACKORDER = 4 + + expire_time = proto.Field( + proto.MESSAGE, + number=16, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl = proto.Field( + proto.MESSAGE, + number=17, + oneof='expiration', + message=duration_pb2.Duration, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + type_ = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + primary_product_id = proto.Field( + proto.STRING, + number=4, + ) + collection_member_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + gtin = proto.Field( + proto.STRING, + number=6, + ) + categories = proto.RepeatedField( + proto.STRING, + number=7, + ) + title = proto.Field( + proto.STRING, + number=8, + ) + brands = proto.RepeatedField( + proto.STRING, + number=9, + ) + description = proto.Field( + proto.STRING, + number=10, + ) + language_code = proto.Field( + proto.STRING, + number=11, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message=common.CustomAttribute, + ) + tags = proto.RepeatedField( + proto.STRING, + number=13, + ) + price_info = proto.Field( + proto.MESSAGE, + number=14, + message=common.PriceInfo, + ) + rating = proto.Field( + proto.MESSAGE, + number=15, + message=common.Rating, + ) + available_time = proto.Field( + proto.MESSAGE, + number=18, + message=timestamp_pb2.Timestamp, + ) + availability = proto.Field( + proto.ENUM, + number=19, + enum=Availability, + ) + available_quantity = proto.Field( + proto.MESSAGE, + number=20, + message=wrappers_pb2.Int32Value, + ) + fulfillment_info = proto.RepeatedField( + proto.MESSAGE, + number=21, + message=common.FulfillmentInfo, + ) + uri = proto.Field( + proto.STRING, + number=22, + ) + images = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=common.Image, + ) + audience = proto.Field( + proto.MESSAGE, + number=24, + message=common.Audience, + ) + color_info = proto.Field( + proto.MESSAGE, + number=25, + message=common.ColorInfo, + ) + sizes = proto.RepeatedField( + proto.STRING, + number=26, + ) + materials = proto.RepeatedField( + proto.STRING, + number=27, + ) + patterns = proto.RepeatedField( + proto.STRING, + number=28, + ) + conditions = proto.RepeatedField( + proto.STRING, + number=29, + ) + promotions = proto.RepeatedField( + proto.MESSAGE, + number=34, + message=promotion.Promotion, + ) + publish_time = proto.Field( + proto.MESSAGE, + number=33, + message=timestamp_pb2.Timestamp, + ) + retrievable_fields = proto.Field( + proto.MESSAGE, + number=30, + message=field_mask_pb2.FieldMask, + ) + variants = proto.RepeatedField( + proto.MESSAGE, + number=31, + message='Product', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py new file mode 100644 index 00000000..ddfc08ed --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py @@ -0,0 +1,877 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'CreateProductRequest', + 'GetProductRequest', + 'UpdateProductRequest', + 'DeleteProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'SetInventoryRequest', + 'SetInventoryMetadata', + 'SetInventoryResponse', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesResponse', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesResponse', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesResponse', + }, +) + + +class CreateProductRequest(proto.Message): + r"""Request message for [CreateProduct][] method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + product (google.cloud.retail_v2alpha.types.Product): + Required. The [Product][google.cloud.retail.v2alpha.Product] + to create. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2alpha.Product], which will + become the final component of the + [Product.name][google.cloud.retail.v2alpha.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2alpha.Product]s with the + same + [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + product_id = proto.Field( + proto.STRING, + number=3, + ) + + +class GetProductRequest(proto.Message): + r"""Request message for [GetProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested + [Product][google.cloud.retail.v2alpha.Product] does not + exist, a NOT_FOUND error is returned. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateProductRequest(proto.Message): + r"""Request message for [UpdateProduct][] method. + + Attributes: + product (google.cloud.retail_v2alpha.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Product][google.cloud.retail.v2alpha.Product] to update. + The immutable and output only fields are NOT supported. If + not set, all supported fields (the fields that are neither + immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + a new [Product][google.cloud.retail.v2alpha.Product] will be + created. In this situation, ``update_mask`` is ignored. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteProductRequest(proto.Message): + r"""Request message for [DeleteProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2alpha.Product] to delete + can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] with more + than one + [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2alpha.Product] will be + deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProductsRequest(proto.Message): + r"""Request message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list products + under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2alpha.Product]s under this + branch, regardless of whether or not this branch exists, a + PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [Product][google.cloud.retail.v2alpha.Product]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 + [ListProductsResponse.next_page_token][google.cloud.retail.v2alpha.ListProductsResponse.next_page_token], + received from a previous + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + filter (str): + A filter to apply on the list results. Supported features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2alpha.ListProductsRequest.filter] + is unset. + - List + [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s sharing + the same + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product]. For + example: ``primary_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2alpha.Product]s + bundled in a + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product]. For + example: ``collection_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2alpha.Product]s with + a partibular type. For example: ``type = "PRIMARY"`` + ``type = "VARIANT"`` ``type = "COLLECTION"`` + + If the field is unrecognizable, an INVALID_ARGUMENT error is + returned. + + If the specified + [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2alpha.Product] or + [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2alpha.Product] does not + exist, a NOT_FOUND error is returned. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields of [Product][google.cloud.retail.v2alpha.Product] + to return in the responses. If not set or empty, the + following fields are returned: + + - [Product.name][google.cloud.retail.v2alpha.Product.name] + - [Product.id][google.cloud.retail.v2alpha.Product.id] + - [Product.title][google.cloud.retail.v2alpha.Product.title] + - [Product.uri][google.cloud.retail.v2alpha.Product.uri] + - [Product.images][google.cloud.retail.v2alpha.Product.images] + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.brands][google.cloud.retail.v2alpha.Product.brands] + + If "*" is provided, all fields are returned. + [Product.name][google.cloud.retail.v2alpha.Product.name] is + always returned no matter what mask is set. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + require_total_size (bool): + If true and + [page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] + is empty, + [ListProductsResponse.total_size][google.cloud.retail.v2alpha.ListProductsResponse.total_size] + is set to the total count of matched items irrespective of + pagination. + + Notice that setting this field to true affects the + performance. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + require_total_size = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListProductsResponse(proto.Message): + r"""Response message for + [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] + method. + + Attributes: + products (Sequence[google.cloud.retail_v2alpha.types.Product]): + The [Product][google.cloud.retail.v2alpha.Product]s. + next_page_token (str): + A token that can be sent as + [ListProductsRequest.page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + total_size (int): + The total count of matched + [Product][google.cloud.retail.v2alpha.Product]s irrespective + of pagination. The total number of + [Product][google.cloud.retail.v2alpha.Product]s returned by + pagination may be less than the + [total_size][google.cloud.retail.v2alpha.ListProductsResponse.total_size] + that matches. + + This field is ignored if + [ListProductsRequest.require_total_size][google.cloud.retail.v2alpha.ListProductsRequest.require_total_size] + is not set or + [ListProductsRequest.page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] + is not empty. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + + +class SetInventoryRequest(proto.Message): + r"""Request message for [SetInventory][] method. + + Attributes: + inventory (google.cloud.retail_v2alpha.types.Product): + Required. The inventory information to update. The allowable + fields to update are: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2alpha.Product] named in + [Product.name][google.cloud.retail.v2alpha.Product.name], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2alpha.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting the + last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of fulfillment + types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear in + [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types have + empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following inventory + fields: + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + - [Product.availability][google.cloud.retail.v2alpha.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] + + If a full overwrite of inventory information while ignoring + timestamps is needed, [UpdateProduct][] should be invoked + instead. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2alpha.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the request is issued, used to + prevent out-of-order updates on inventory fields + with the last update time recorded. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] with name + [Product.name][google.cloud.retail.v2alpha.Product.name] is + not found, the inventory update will still be processed and + retained for at most 1 day until the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + inventory = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + set_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + set_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=4, + ) + + +class SetInventoryMetadata(proto.Message): + r"""Metadata related to the progress of the SetInventory operation. + Currently empty because there is no meaningful metadata populated + from the [SetInventory][] method. + + """ + + +class SetInventoryResponse(proto.Message): + r"""Response of the SetInventoryRequest. Currently empty because there + is no meaningful response populated from the [SetInventory][] + method. + + """ + + +class AddFulfillmentPlacesRequest(proto.Message): + r"""Request message for [AddFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery" to be added for this + [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type]. + Duplicate IDs will be automatically ignored. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If the total number of place IDs exceeds 2000 for this + [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type] + after adding, then the update will be rejected. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + the fulfillment information will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + add_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class AddFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the AddFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [AddFulfillmentPlaces][] method. + + """ + + +class AddFulfillmentPlacesResponse(proto.Message): + r"""Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + + +class AddLocalInventoriesRequest(proto.Message): + r"""Request message for [AddLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + local_inventories (Sequence[google.cloud.retail_v2alpha.types.LocalInventory]): + Required. A list of inventory information at + difference places. Each place is identified by + its place ID. At most 3000 inventories are + allowed per request. + add_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided list of + [LocalInventory][google.cloud.retail.v2alpha.LocalInventory] + to update. The field is updated to the provided value. + + If a field is set while the place does not have a previous + local inventory, the local inventory at that store is + created. + + If a field is set while the value of that field is not + provided, the original field value, if it exists, is + deleted. + + If the mask is not set or set with empty paths, all + inventory fields will be updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory updates are + issued. Used to prevent out-of-order updates on + local inventory fields. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + the local inventory will still be processed and retained for + at most 1 day and processed once the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + local_inventories = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.LocalInventory, + ) + add_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + add_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=6, + ) + + +class AddLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the AddLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [AddLocalInventories][] method. + + """ + + +class AddLocalInventoriesResponse(proto.Message): + r"""Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesRequest(proto.Message): + r"""Request message for [RemoveLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + place_ids (Sequence[str]): + Required. A list of place IDs to have their + inventory deleted. At most 3000 place IDs are + allowed per request. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory deletions are + issued. Used to prevent out-of-order updates and + deletions on local inventory fields. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + the local inventory removal request will still be processed + and retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class RemoveLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesResponse(proto.Message): + r"""Response of the [RemoveLocalInventories][] API. Currently empty + because there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + + +class RemoveFulfillmentPlacesRequest(proto.Message): + r"""Request message for [RemoveFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2alpha.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2alpha.Product], regardless + of whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery", to be removed for this + [type][google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type]. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2alpha.Product] is not found, + the fulfillment information will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2alpha.Product] is created. + If set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2alpha.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class RemoveFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveFulfillmentPlaces][] method. + + """ + + +class RemoveFulfillmentPlacesResponse(proto.Message): + r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty + because there is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py new file mode 100644 index 00000000..bd5b8a58 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'Promotion', + }, +) + + +class Promotion(proto.Message): + r"""Promotion information. + + Attributes: + promotion_id (str): + ID of the promotion. For example, "free gift". + + The value must be a UTF-8 encoded string with a length limit + of 128 characters, and match the pattern: + ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or + ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is + returned. + + Google Merchant Center property + `promotion `__. + """ + + promotion_id = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py new file mode 100644 index 00000000..ad7ff6f6 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py @@ -0,0 +1,251 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'PurgeMetadata', + 'PurgeProductsMetadata', + 'PurgeProductsRequest', + 'PurgeProductsResponse', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + }, +) + + +class PurgeMetadata(proto.Message): + r"""Metadata related to the progress of the Purge operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + """ + + +class PurgeProductsMetadata(proto.Message): + r"""Metadata related to the progress of the PurgeProducts + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were deleted + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=3, + ) + failure_count = proto.Field( + proto.INT64, + number=4, + ) + + +class PurgeProductsRequest(proto.Message): + r"""Request message for PurgeProducts method. + + Attributes: + parent (str): + Required. The resource name of the branch under which the + products are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}/branches/${branchId}`` + filter (str): + Required. The filter string to specify the products to be + deleted with a length limit of 5,000 characters. + + Empty string filter is not allowed. "*" implies delete all + items in a branch. + + The eligible fields for filtering are: + + - ``availability``: Double quoted + [Product.availability][google.cloud.retail.v2alpha.Product.availability] + string. + - ``create_time`` : in ISO 8601 "zulu" format. + + Supported syntax: + + - Comparators (">", "<", ">=", "<=", "="). Examples: + + - create_time <= "2015-02-13T17:05:46Z" + - availability = "IN_STOCK" + + - Conjunctions ("AND") Examples: + + - create_time <= "2015-02-13T17:05:46Z" AND availability + = "PREORDER" + + - Disjunctions ("OR") Examples: + + - create_time <= "2015-02-13T17:05:46Z" OR availability + = "IN_STOCK" + + - Can support nested queries. Examples: + + - (create_time <= "2015-02-13T17:05:46Z" AND + availability = "PREORDER") OR (create_time >= + "2015-02-14T13:03:32Z" AND availability = "IN_STOCK") + + - Filter Limits: + + - Filter should not contain more than 6 conditions. + - Max nesting depth should not exceed 2 levels. + + Examples queries: + + - Delete back order products created before a timestamp. + create_time <= "2015-02-13T17:05:46Z" OR availability = + "BACKORDER". + force (bool): + Actually perform the purge. If ``force`` is set to false, + the method will return the expected purge count without + deleting any products. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeProductsResponse(proto.Message): + r"""Response of the PurgeProductsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purge_count (int): + The total count of products purged as a + result of the operation. + purge_sample (Sequence[str]): + A sample of the product names that will be deleted. Only + populated if ``force`` is set to false. A max of 100 names + will be returned and the names are chosen at random. + """ + + purge_count = proto.Field( + proto.INT64, + number=1, + ) + purge_sample = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + + Attributes: + parent (str): + Required. The resource name of the catalog under which the + events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}`` + filter (str): + Required. The filter string to specify the events to be + deleted with a length limit of 5,000 characters. Empty + string filter is not allowed. The eligible fields for + filtering are: + + - ``eventType``: Double quoted + [UserEvent.event_type][google.cloud.retail.v2alpha.UserEvent.event_type] + string. + - ``eventTime``: in ISO 8601 "zulu" format. + - ``visitorId``: Double quoted string. Specifying this will + delete all events associated with a visitor. + - ``userId``: Double quoted string. Specifying this will + delete all events associated with a user. + + Examples: + + - Deleting all events in a time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + - Deleting specific eventType in time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + - Deleting all events for a specific visitor: + ``visitorId = "visitor1024"`` + + The filtering fields are assumed to have an implicit AND. + force (bool): + Actually perform the purge. If ``force`` is set to false, + the method will return the expected purge count without + deleting any user events. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsResponse(proto.Message): + r"""Response of the PurgeUserEventsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purged_events_count (int): + The total count of events purged as a result + of the operation. + """ + + purged_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py new file mode 100644 index 00000000..e4dc0ba2 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py @@ -0,0 +1,1099 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'SearchRequest', + 'SearchResponse', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + + Attributes: + placement (str): + Required. The resource name of the search engine placement, + such as + ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` + This field is used to identify the serving configuration + name and the set of models that will be used to make the + search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + + Use "default_branch" as the branch ID or leave this field + empty, to search products under the default branch. + query (str): + Raw search query. + visitor_id (str): + Required. A unique identifier for tracking visitors. For + example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + This should be the same identifier as + [UserEvent.visitor_id][google.cloud.retail.v2alpha.UserEvent.visitor_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2alpha.types.UserInfo): + User information. + page_size (int): + Maximum number of + [Product][google.cloud.retail.v2alpha.Product]s to return. + If unspecified, defaults to a reasonable value. The maximum + allowed value is 120. Values above 120 will be coerced to + 120. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [SearchResponse.next_page_token][google.cloud.retail.v2alpha.SearchResponse.next_page_token], + received from a previous + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Product][google.cloud.retail.v2alpha.Product]s deemed by + the API as relevant) in search results. This field is only + considered if + [page_token][google.cloud.retail.v2alpha.SearchRequest.page_token] + is unset. + + If this field is negative, an INVALID_ARGUMENT is returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. Filter expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + canonical_filter (str): + The default filter that is applied when a user performs a + search without checking any filters on the search page. + + The filter applied to every search request when quality + improvement such as query expansion is needed. For example, + if a query does not have enough results, an expanded query + with + [SearchRequest.canonical_filter][google.cloud.retail.v2alpha.SearchRequest.canonical_filter] + will be returned as a supplement of the original query. This + field is strongly recommended to achieve high search + quality. + + See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for more details about filter syntax. + order_by (str): + The order in which products are returned. Products can be + ordered by a field in an + [Product][google.cloud.retail.v2alpha.Product] object. Leave + it unset if ordered by relevance. OrderBy expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + facet_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + dynamic_facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec): + Deprecated. Refer to + https://cloud.google.com/retail/docs/configs#dynamic + to enable dynamic facets. Do not set this field. + The specification for dynamically generated + facets. Notice that only textual facets can be + dynamically generated. + boost_spec (google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec): + Boost specification to boost certain products. See more + details at this `user + guide `__. + + Notice that if both + [ServingConfig.boost_control_ids][google.cloud.retail.v2alpha.ServingConfig.boost_control_ids] + and [SearchRequest.boost_spec] are set, the boost conditions + from both places are evaluated. If a search request matches + multiple boost conditions, the final boost score is equal to + the sum of the boost scores from all matched boost + conditions. + query_expansion_spec (google.cloud.retail_v2alpha.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that specifies the + conditions under which query expansion will occur. See more + details at this `user + guide `__. + relevance_threshold (google.cloud.retail_v2alpha.types.SearchRequest.RelevanceThreshold): + The relevance threshold of the search results. + + Defaults to + [RelevanceThreshold.HIGH][google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH], + which means only the most relevant results are shown, and + the least number of results are returned. See more details + at this `user + guide `__. + variant_rollup_keys (Sequence[str]): + The keys to fetch and rollup the matching + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s attributes, + [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo] + or + [LocalInventory][google.cloud.retail.v2alpha.LocalInventory]s + attributes. The attributes from all the matching + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s or + [LocalInventory][google.cloud.retail.v2alpha.LocalInventory]s + are merged and de-duplicated. Notice that rollup attributes + will lead to extra query latency. Maximum number of keys is + 30. + + For + [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], + a fulfillment type and a fulfillment ID must be provided in + the format of "fulfillmentType.fulfillmentId". E.g., in + "pickupInStore.store123", "pickupInStore" is fulfillment + type and "store123" is the store ID. + + Supported keys are: + + - colorFamilies + - price + - originalPrice + - discount + - variantId + - inventory(place_id,price) + - inventory(place_id,original_price) + - inventory(place_id,attributes.key), where key is any key + in the [Product.inventories.attributes][] map. + - attributes.key, where key is any key in the + [Product.attributes][google.cloud.retail.v2alpha.Product.attributes] + map. + - pickupInStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "pickup-in-store". + - shipToStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "ship-to-store". + - sameDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "same-day-delivery". + - nextDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "next-day-delivery". + - customFulfillment1.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-1". + - customFulfillment2.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-2". + - customFulfillment3.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-3". + - customFulfillment4.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-4". + - customFulfillment5.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] + "custom-type-5". + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. Required for + category navigation queries to achieve good search quality. + The format should be the same as + [UserEvent.page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories]; + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + search_mode (google.cloud.retail_v2alpha.types.SearchRequest.SearchMode): + The search mode of the search request. If not + specified, a single search request triggers both + product search and faceted search. + personalization_spec (google.cloud.retail_v2alpha.types.SearchRequest.PersonalizationSpec): + The specification for personalization. + """ + class RelevanceThreshold(proto.Enum): + r"""The relevance threshold of the search results. The higher + relevance threshold is, the higher relevant results are shown + and the less number of results are returned. + """ + RELEVANCE_THRESHOLD_UNSPECIFIED = 0 + HIGH = 1 + MEDIUM = 2 + LOW = 3 + LOWEST = 4 + + class SearchMode(proto.Enum): + r"""The search mode of each search request.""" + SEARCH_MODE_UNSPECIFIED = 0 + PRODUCT_SEARCH_ONLY = 1 + FACETED_SEARCH_ONLY = 2 + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum of facet values that should be returned for this + facet. If unspecified, defaults to 20. The maximum allowed + value is 300. Values above 300 will be coerced to 300. + + If this field is negative, an INVALID_ARGUMENT is returned. + excluded_filter_keys (Sequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + For example, suppose there are 100 products with color facet + "Red" and 200 products with color facet "Blue". A query + containing the filter "colorFamilies:ANY("Red")" and have + "colorFamilies" as + [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] + will by default return the "Red" with count 100. + + If this field contains "colorFamilies", then the query + returns both the "Red" with count 100 and "Blue" with count + 200, because the "colorFamilies" key is now excluded from + the filter. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined by Google Retail Search. It will be ordered + together with dynamic facets if dynamic facets is enabled. + If set to false, the position of this facet in the response + will be the same as in the request, and it will be ranked + before the facets with dynamic position enable and all + dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response will be determined by Google Retail + Search. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enable, which will + generate a facet 'gender'. Then the final order of the + facets in the response can be ("price", "brands", "rating", + "gender") or ("price", "brands", "gender", "rating") depends + on how Google Retail Search orders "gender" and "rating" + facets. However, notice that "price" and "brands" will + always be ranked at 1st and 2nd position since their + enable_dynamic_position are false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Product][google.cloud.retail.v2alpha.Product] object, over + which the facet values are computed. Facet key is + case-sensitive. + + Allowed facet keys when + [FacetKey.query][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.query] + is not specified: + + - textual_field = + + - "brands" + - "categories" + - "genders" + - "ageGroups" + - "availability" + - "colorFamilies" + - "colors" + - "sizes" + - "materials" + - "patterns" + - "conditions" + - "attributes.key" + - "pickupInStore" + - "shipToStore" + - "sameDayDelivery" + - "nextDayDelivery" + - "customFulfillment1" + - "customFulfillment2" + - "customFulfillment3" + - "customFulfillment4" + - "customFulfillment5" + - "inventory(place_id,attributes.key)" + + - numerical_field = + + - "price" + - "discount" + - "rating" + - "ratingCount" + - "attributes.key" + - "inventory(place_id,price)" + - "inventory(place_id,original_price)" + - "inventory(place_id,attributes.key)". + intervals (Sequence[google.cloud.retail_v2alpha.types.Interval]): + Set only if values should be bucketized into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (Sequence[str]): + Only get facet for the given restricted values. For example, + when using "pickupInStore" as key and set restricted values + to ["store123", "store456"], only facets for "store123" and + "store456" are returned. Only supported on textual fields + and fulfillments. Maximum is 20. + + Must be set for the fulfillment facet keys: + + - pickupInStore + + - shipToStore + + - sameDayDelivery + + - nextDayDelivery + + - customFulfillment1 + + - customFulfillment2 + + - customFulfillment3 + + - customFulfillment4 + + - customFulfillment5 + prefixes (Sequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "categories" has three values "Women > Shoe", + "Women > Dress" and "Men > Shoe". If set + "prefixes" to "Women", the "categories" facet + will give only "Women > Shoe" and "Women > + Dress". Only supported on textual fields. + Maximum is 10. + contains (Sequence[str]): + Only get facet values that contains the given + strings. For example, suppose "categories" has + three values "Women > Shoe", "Women > Dress" and + "Men > Shoe". If set "contains" to "Shoe", the + "categories" facet will give only "Women > Shoe" + and "Men > Shoe". Only supported on textual + fields. Maximum is 10. + order_by (str): + The order in which [Facet.values][] are returned. + + Allowed values are: + + - "count desc", which means order by + [Facet.FacetValue.count][] descending. + + - "value desc", which means order by + [Facet.FacetValue.value][] descending. Only applies to + textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.intervals]; + [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] + are sorted in the order given by + [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.restricted_values]. + query (str): + The query that is used to compute facet for the given facet + key. When provided, it will override the default behavior of + facet computation. The query syntax is the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for detail syntax and limitations. Notice that there is no + limitation on + [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] + when query is specified. + + In the response, [FacetValue.value][] will be always "1" and + [FacetValue.count][] will be the number of results that + matches the query. + + For example, you can set a customized facet for + "shipToStore", where + [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] + is "customizedShipToStore", and + [FacetKey.query][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.query] + is "availability: ANY("IN_STOCK") AND shipToStore: + ANY("123")". Then the facet will count the products that are + both in stock and ship to store "123". + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + intervals = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes = proto.RepeatedField( + proto.STRING, + number=8, + ) + contains = proto.RepeatedField( + proto.STRING, + number=9, + ) + order_by = proto.Field( + proto.STRING, + number=4, + ) + query = proto.Field( + proto.STRING, + number=5, + ) + + facet_key = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.FacetSpec.FacetKey', + ) + limit = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position = proto.Field( + proto.BOOL, + number=4, + ) + + class DynamicFacetSpec(proto.Message): + r"""The specifications of dynamically generated facets. + + Attributes: + mode (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec.Mode): + Mode of the DynamicFacet feature. Defaults to + [Mode.DISABLED][google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec.Mode.DISABLED] + if it's unset. + """ + class Mode(proto.Enum): + r"""Enum to control DynamicFacet mode""" + MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.DynamicFacetSpec.Mode', + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain items. + + Attributes: + condition_boost_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a product + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 10. + skip_boost_spec_validation (bool): + Whether to skip boostspec validation. If this field is set + to true, invalid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] + will be ignored and valid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] + will still be applied. + + This field is a member of `oneof`_ ``_skip_boost_spec_validation``. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to products which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": + + - (id: ANY("product_1", "product_2")) AND + (colorFamilies: ANY("Red","Blue")) + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition = proto.Field( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + skip_boost_spec_validation = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.retail_v2alpha.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 3 + + condition = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.QueryExpansionSpec.Condition', + ) + pin_unexpanded_results = proto.Field( + proto.BOOL, + number=2, + ) + + class PersonalizationSpec(proto.Message): + r"""The specification for personalization. + + Attributes: + mode (google.cloud.retail_v2alpha.types.SearchRequest.PersonalizationSpec.Mode): + Defaults to + [Mode.AUTO][google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""The personalization mode of each search request.""" + MODE_UNSPECIFIED = 0 + AUTO = 1 + DISABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.PersonalizationSpec.Mode', + ) + + placement = proto.Field( + proto.STRING, + number=1, + ) + branch = proto.Field( + proto.STRING, + number=2, + ) + query = proto.Field( + proto.STRING, + number=3, + ) + visitor_id = proto.Field( + proto.STRING, + number=4, + ) + user_info = proto.Field( + proto.MESSAGE, + number=5, + message=common.UserInfo, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + offset = proto.Field( + proto.INT32, + number=9, + ) + filter = proto.Field( + proto.STRING, + number=10, + ) + canonical_filter = proto.Field( + proto.STRING, + number=28, + ) + order_by = proto.Field( + proto.STRING, + number=11, + ) + facet_specs = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=FacetSpec, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=21, + message=DynamicFacetSpec, + ) + boost_spec = proto.Field( + proto.MESSAGE, + number=13, + message=BoostSpec, + ) + query_expansion_spec = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionSpec, + ) + relevance_threshold = proto.Field( + proto.ENUM, + number=15, + enum=RelevanceThreshold, + ) + variant_rollup_keys = proto.RepeatedField( + proto.STRING, + number=17, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=23, + ) + search_mode = proto.Field( + proto.ENUM, + number=31, + enum=SearchMode, + ) + personalization_spec = proto.Field( + proto.MESSAGE, + number=32, + message=PersonalizationSpec, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] + method. + + Attributes: + results (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.SearchResult]): + A list of matched items. The order represents + the ranking. + facets (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.Facet]): + Results of facets requested by user. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.retail.v2alpha.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.retail.v2alpha.SearchResponse.total_size] + that matches. + corrected_query (str): + If spell correction applies, the corrected + query. Otherwise, empty. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs + resulting from this search, which enables accurate + attribution of search model performance. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.retail.v2alpha.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + query_expansion_info (google.cloud.retail_v2alpha.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search will be performed, and only + [redirect_uri][google.cloud.retail.v2alpha.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.retail.v2alpha.SearchResponse.attribution_token] + will be set in the response. + applied_controls (Sequence[str]): + The fully qualified resource name of applied + `controls `__. + invalid_condition_boost_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + The invalid + [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] + that are not applied during serving. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Product.id][google.cloud.retail.v2alpha.Product.id] of the + searched [Product][google.cloud.retail.v2alpha.Product]. + product (google.cloud.retail_v2alpha.types.Product): + The product data snippet in the search response. Only + [Product.name][google.cloud.retail.v2alpha.Product.name] is + guaranteed to be populated. + + [Product.variants][google.cloud.retail.v2alpha.Product.variants] + contains the product variants that match the search query. + If there are multiple product variants matching the query, + top 5 most relevant product variants are returned and + ordered by relevancy. + + If relevancy can be deternmined, use + [matching_variant_fields][google.cloud.retail.v2alpha.SearchResponse.SearchResult.matching_variant_fields] + to look up matched product variants fields. If relevancy + cannot be determined, e.g. when searching "shoe" all + products in a shoe product can be a match, 5 product + variants are returned but order is meaningless. + matching_variant_count (int): + The count of matched + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product]s. + matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): + If a + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] matches the + search query, this map indicates which + [Product][google.cloud.retail.v2alpha.Product] fields are + matched. The key is the + [Product.name][google.cloud.retail.v2alpha.Product.name], + the value is a field mask of the matched + [Product][google.cloud.retail.v2alpha.Product] fields. If + matched attributes cannot be determined, this map will be + empty. + + For example, a key "sku1" with field mask + "products.color_info" indicates there is a match between + "sku1" [ColorInfo][google.cloud.retail.v2alpha.ColorInfo] + and the query. + variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): + The rollup matching + [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] + [Product][google.cloud.retail.v2alpha.Product] attributes. + The key is one of the + [SearchRequest.variant_rollup_keys][google.cloud.retail.v2alpha.SearchRequest.variant_rollup_keys]. + The values are the merged and de-duplicated + [Product][google.cloud.retail.v2alpha.Product] attributes. + Notice that the rollup values are respect filter. For + example, when filtering by "colorFamilies:ANY("red")" and + rollup "colorFamilies", only "red" is returned. + + For textual and numerical attributes, the rollup values is a + list of string or double values with type + [google.protobuf.ListValue][google.protobuf.ListValue]. For + example, if there are two variants with colors "red" and + "blue", the rollup values are + + :: + + { key: "colorFamilies" + value { + list_value { + values { string_value: "red" } + values { string_value: "blue" } + } + } + } + + For + [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], + the rollup values is a double value with type + [google.protobuf.Value][google.protobuf.Value]. For example, + ``{key: "pickupInStore.store1" value { number_value: 10 }}`` + means a there are 10 variants in this product are available + in the store "store1". + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + matching_variant_count = proto.Field( + proto.INT32, + number=3, + ) + matching_variant_fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + variant_rollup_values = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. E.g., "colorFamilies" + or "price" or "attributes.attr1". + values (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Text value of a facet, such as "Black" for + facet "colorFamilies". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.retail_v2alpha.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value = proto.Field( + proto.STRING, + number=1, + oneof='facet_value', + ) + interval = proto.Field( + proto.MESSAGE, + number=2, + oneof='facet_value', + message=common.Interval, + ) + count = proto.Field( + proto.INT64, + number=3, + ) + + key = proto.Field( + proto.STRING, + number=1, + ) + values = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SearchResponse.Facet.FacetValue', + ) + dynamic_facet = proto.Field( + proto.BOOL, + number=3, + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count = proto.Field( + proto.INT64, + number=2, + ) + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + corrected_query = proto.Field( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + next_page_token = proto.Field( + proto.STRING, + number=6, + ) + query_expansion_info = proto.Field( + proto.MESSAGE, + number=7, + message=QueryExpansionInfo, + ) + redirect_uri = proto.Field( + proto.STRING, + number=10, + ) + applied_controls = proto.RepeatedField( + proto.STRING, + number=12, + ) + invalid_condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py new file mode 100644 index 00000000..c8c3ccca --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py @@ -0,0 +1,309 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'ServingConfig', + }, +) + + +class ServingConfig(proto.Message): + r"""Configures metadata that is used to generate serving time results + (e.g. search results or recommendation predictions). The + ServingConfig is passed in the search and predict request and + together with the Catalog.default_branch, generates results. + + Attributes: + name (str): + Immutable. Fully qualified name + projects/\ */locations/global/catalogs/*/servingConfig/\* + display_name (str): + Required. The human readable serving config display name. + Used in Retail UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + model_id (str): + The id of the model to use at serving time. Currently only + RecommendationModels are supported: + https://cloud.google.com/retail/recommendations-ai/docs/create-models + Can be changed but only to a compatible model (e.g. + others-you-may-like CTR to others-you-may-like CVR). + + Required when + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + price_reranking_level (str): + How much price ranking we want in serving results. Price + reranking causes product items with a similar recommendation + probability to be ordered by price, with the highest-priced + items first. This setting could result in a decrease in + click-through and conversion rates. Allowed values are: + + - 'no-price-reranking' + - 'low-price-raranking' + - 'medium-price-reranking' + - 'high-price-reranking' + + If not specified, we choose default based on model type. + Default value: 'no-price-reranking'. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + facet_control_ids (Sequence[str]): + Facet specifications for faceted search. If empty, no facets + are returned. The ids refer to the ids of + [Control][google.cloud.retail.v2alpha.Control] resources + with only the Facet control set. These controls are assumed + to be in the same + [Catalog][google.cloud.retail.v2alpha.Catalog] as the + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]. + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + dynamic_facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec): + The specification for dynamically generated facets. Notice + that only textual facets can be dynamically generated. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + boost_control_ids (Sequence[str]): + Condition boost specifications. If a product matches + multiple conditions in the specifications, boost scores from + these specifications are all applied and combined in a + non-linear way. Maximum number of specifications is 100. + + Notice that if both + [ServingConfig.boost_control_ids][google.cloud.retail.v2alpha.ServingConfig.boost_control_ids] + and [SearchRequest.boost_spec] are set, the boost conditions + from both places are evaluated. If a search request matches + multiple boost conditions, the final boost score is equal to + the sum of the boost scores from all matched boost + conditions. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + filter_control_ids (Sequence[str]): + Condition filter specifications. If a product matches + multiple conditions in the specifications, filters from + these specifications are all applied and combined via the + AND operator. Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + redirect_control_ids (Sequence[str]): + Condition redirect specifications. Only the first triggered + redirect action is applied, even if multiple apply. Maximum + number of specifications is 1000. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + twoway_synonyms_control_ids (Sequence[str]): + Condition synonyms specifications. If multiple syonyms + conditions match, all matching synonyms control in the list + will execute. Order of controls in the list will not matter. + Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + oneway_synonyms_control_ids (Sequence[str]): + Condition oneway synonyms specifications. If multiple oneway + synonyms conditions match, all matching oneway synonyms + controls in the list will execute. Order of controls in the + list will not matter. Maximum number of specifications is + 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + do_not_associate_control_ids (Sequence[str]): + Condition do not associate specifications. If multiple do + not associate conditions match, all matching do not + associate controls in the list will execute. + + - Order does not matter. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + replacement_control_ids (Sequence[str]): + Condition replacement specifications. + + - Applied according to the order in the list. + - A previously replaced term can not be re-replaced. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + ignore_control_ids (Sequence[str]): + Condition ignore specifications. If multiple ignore + conditions match, all matching ignore controls in the list + will execute. + + - Order does not matter. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + diversity_level (str): + How much diversity to use in recommendation model results + e.g. 'medium-diversity' or 'high-diversity'. Currently + supported values: + + - 'no-diversity' + - 'low-diversity' + - 'medium-diversity' + - 'high-diversity' + - 'auto-diversity' + + If not specified, we choose default based on recommendation + model type. Default value: 'no-diversity'. + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + enable_category_filter_level (str): + Whether to add additional category filters on the + 'similar-items' model. If not specified, we enable it by + default. Allowed values are: + + - 'no-category-match': No additional filtering of original + results from the model and the customer's filters. + - 'relaxed-category-match': Only keep results with + categories that match at least one item categories in the + PredictRequests's context item. + + - If customer also sends filters in the PredictRequest, + then the results will satisfy both conditions (user + given and category match). + + Can only be set if + [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + solution_types (Sequence[google.cloud.retail_v2alpha.types.SolutionType]): + Required. Immutable. Specifies the solution + types that a serving config can be associated + with. Currently we support setting only one type + of solution. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + model_id = proto.Field( + proto.STRING, + number=3, + ) + price_reranking_level = proto.Field( + proto.STRING, + number=4, + ) + facet_control_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=6, + message=search_service.SearchRequest.DynamicFacetSpec, + ) + boost_control_ids = proto.RepeatedField( + proto.STRING, + number=7, + ) + filter_control_ids = proto.RepeatedField( + proto.STRING, + number=9, + ) + redirect_control_ids = proto.RepeatedField( + proto.STRING, + number=10, + ) + twoway_synonyms_control_ids = proto.RepeatedField( + proto.STRING, + number=18, + ) + oneway_synonyms_control_ids = proto.RepeatedField( + proto.STRING, + number=12, + ) + do_not_associate_control_ids = proto.RepeatedField( + proto.STRING, + number=13, + ) + replacement_control_ids = proto.RepeatedField( + proto.STRING, + number=14, + ) + ignore_control_ids = proto.RepeatedField( + proto.STRING, + number=15, + ) + diversity_level = proto.Field( + proto.STRING, + number=8, + ) + enable_category_filter_level = proto.Field( + proto.STRING, + number=16, + ) + solution_types = proto.RepeatedField( + proto.ENUM, + number=19, + enum=common.SolutionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py new file mode 100644 index 00000000..635f42bb --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py @@ -0,0 +1,234 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'CreateServingConfigRequest', + 'UpdateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'AddControlRequest', + 'RemoveControlRequest', + }, +) + + +class CreateServingConfigRequest(proto.Message): + r"""Request for CreateServingConfig method. + + Attributes: + parent (str): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + serving_config (google.cloud.retail_v2alpha.types.ServingConfig): + Required. The ServingConfig to create. + serving_config_id (str): + Required. The ID to use for the ServingConfig, which will + become the final component of the ServingConfig's resource + name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-_/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + serving_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_serving_config.ServingConfig, + ) + serving_config_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateServingConfigRequest(proto.Message): + r"""Request for UpdateServingConfig method. + + Attributes: + serving_config (google.cloud.retail_v2alpha.types.ServingConfig): + Required. The ServingConfig to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] + + If not set, all supported fields are updated. + """ + + serving_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_serving_config.ServingConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteServingConfigRequest(proto.Message): + r"""Request for DeleteServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetServingConfigRequest(proto.Message): + r"""Request for GetServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListServingConfigsRequest(proto.Message): + r"""Request for ListServingConfigs method. + + Attributes: + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 100. If a + value greater than 100 is provided, at most 100 + results are returned. + page_token (str): + Optional. A page token, received from a previous + ``ListServingConfigs`` call. Provide this to retrieve the + subsequent page. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServingConfigsResponse(proto.Message): + r"""Response for ListServingConfigs method. + + Attributes: + serving_configs (Sequence[google.cloud.retail_v2alpha.types.ServingConfig]): + All the ServingConfigs for a given catalog. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + serving_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_serving_config.ServingConfig, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class AddControlRequest(proto.Message): + r"""Request for AddControl method. + + Attributes: + serving_config (str): + Required. The source ServingConfig resource name . Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + control_id (str): + Required. The id of the control to apply. Assumed to be in + the same catalog as the serving config - if id is not found + a NOT_FOUND error is returned. + """ + + serving_config = proto.Field( + proto.STRING, + number=1, + ) + control_id = proto.Field( + proto.STRING, + number=2, + ) + + +class RemoveControlRequest(proto.Message): + r"""Request for RemoveControl method. + + Attributes: + serving_config (str): + Required. The source ServingConfig resource name . Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + control_id (str): + Required. The id of the control to apply. + Assumed to be in the same catalog as the serving + config. + """ + + serving_config = proto.Field( + proto.STRING, + number=1, + ) + control_id = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py new file mode 100644 index 00000000..f9d6a684 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py @@ -0,0 +1,507 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'UserEvent', + 'ProductDetail', + 'CompletionDetail', + 'PurchaseTransaction', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Retail API needs + to know about how end users interact with customers' website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + - ``add-to-cart``: Products being added to cart. + - ``category-page-view``: Special pages such as sale or + promotion pages viewed. + - ``detail-page-view``: Products detail page viewed. + - ``home-page-view``: Homepage viewed. + - ``promotion-offered``: Promotion is offered to a user. + - ``promotion-not-offered``: Promotion is not offered to a + user. + - ``purchase-complete``: User finishing a purchase. + - ``search``: Product search. + - ``shopping-cart-page-view``: User viewing a shopping + cart. + visitor_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + The field should not contain PII or user-data. We recommend + to use Google Analystics `Client + ID `__ + for this field. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the sesion_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add visitor_id as prefix. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.retail.v2alpha.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + experiment_ids (Sequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups + (e.g. using Retail API, using different + recommendation models). + attribution_token (str): + Highly recommended for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2alpha.PredictionService.Predict]. + This field enables accurate attribution of recommendation + model performance. + + The value must be a valid + [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] + for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2alpha.PredictionService.Predict]. + The value must be a valid + [SearchResponse.attribution_token][google.cloud.retail.v2alpha.SearchResponse.attribution_token] + for user events that are the result of + [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. + + This token enables us to accurately attribute page view or + purchase back to the event and the particular predict + response containing this clicked/purchased product. If user + clicks on product K in the recommendation results, pass + [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] + as a URL parameter to product K's page. When recording + events on product K's page, log the + [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] + to this field. + product_details (Sequence[google.cloud.retail_v2alpha.types.ProductDetail]): + The main product details related to the event. + + This field is required for the following event types: + + - ``add-to-cart`` + - ``detail-page-view`` + - ``purchase-complete`` + - ``search`` + + In a ``search`` event, this field represents the products + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [product_details][google.cloud.retail.v2alpha.UserEvent.product_details] + is desired. The end user may have not finished browsing the + whole page yet. + completion_detail (google.cloud.retail_v2alpha.types.CompletionDetail): + The main auto-completion details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Retail API use those + custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - The key must be a UTF-8 encoded string with a length + limit of 5,000 characters. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a UTF-8 + encoded string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is traffic_channel, which is how a user arrives + at the site. Users can arrive at the site by coming to the + site directly, coming through Google search, or in other + ways. + cart_id (str): + The ID or name of the associated shopping cart. This ID is + used to associate multiple items added or present in the + cart before purchase. + + This can only be set for ``add-to-cart``, + ``purchase-complete``, or ``shopping-cart-page-view`` + events. + purchase_transaction (google.cloud.retail_v2alpha.types.PurchaseTransaction): + A transaction represents the entire purchase transaction. + + Required for ``purchase-complete`` events. Other event types + should not set this field. Otherwise, an INVALID_ARGUMENT + error is returned. + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.retail.v2alpha.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + At least one of + [search_query][google.cloud.retail.v2alpha.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. + + See + [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + order_by (str): + The order in which products are returned. + + See + [SearchRequest.order_by][google.cloud.retail.v2alpha.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.retail.v2alpha.SearchRequest.offset] + for definition. + + If this field is negative, an INVALID_ARGUMENT is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + + Required for ``category-page-view`` events. At least one of + [search_query][google.cloud.retail.v2alpha.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2alpha.types.UserInfo): + User information. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. + page_view_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageViewId`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + """ + + event_type = proto.Field( + proto.STRING, + number=1, + ) + visitor_id = proto.Field( + proto.STRING, + number=2, + ) + session_id = proto.Field( + proto.STRING, + number=21, + ) + event_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + experiment_ids = proto.RepeatedField( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + product_details = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ProductDetail', + ) + completion_detail = proto.Field( + proto.MESSAGE, + number=22, + message='CompletionDetail', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=common.CustomAttribute, + ) + cart_id = proto.Field( + proto.STRING, + number=8, + ) + purchase_transaction = proto.Field( + proto.MESSAGE, + number=9, + message='PurchaseTransaction', + ) + search_query = proto.Field( + proto.STRING, + number=10, + ) + filter = proto.Field( + proto.STRING, + number=16, + ) + order_by = proto.Field( + proto.STRING, + number=17, + ) + offset = proto.Field( + proto.INT32, + number=18, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=11, + ) + user_info = proto.Field( + proto.MESSAGE, + number=12, + message=common.UserInfo, + ) + uri = proto.Field( + proto.STRING, + number=13, + ) + referrer_uri = proto.Field( + proto.STRING, + number=14, + ) + page_view_id = proto.Field( + proto.STRING, + number=15, + ) + + +class ProductDetail(proto.Message): + r"""Detailed product information associated with a user event. + + Attributes: + product (google.cloud.retail_v2alpha.types.Product): + Required. [Product][google.cloud.retail.v2alpha.Product] + information. + + Required field(s): + + - [Product.id][google.cloud.retail.v2alpha.Product.id] + + Optional override field(s): + + - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] + + If any supported optional fields are provided, we will treat + them as a full override when looking up product information + from the catalog. Thus, it is important to ensure that the + overriding fields are accurate and complete. + + All other product fields are ignored and instead populated + via catalog lookup after event ingestion. + quantity (google.protobuf.wrappers_pb2.Int32Value): + Quantity of the product associated with the user event. + + For example, this field will be 2 if two products are added + to the shopping cart for ``purchase-complete`` event. + Required for ``add-to-cart`` and ``purchase-complete`` event + types. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + quantity = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +class CompletionDetail(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + completion_attribution_token (str): + Completion attribution token in + [CompleteQueryResponse.attribution_token][google.cloud.retail.v2alpha.CompleteQueryResponse.attribution_token]. + selected_suggestion (str): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2alpha.CompleteQueryResponse.CompletionResult.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2alpha.CompleteQueryResponse.CompletionResult.suggestion] + position, starting from 0. + """ + + completion_attribution_token = proto.Field( + proto.STRING, + number=1, + ) + selected_suggestion = proto.Field( + proto.STRING, + number=2, + ) + selected_position = proto.Field( + proto.INT32, + number=3, + ) + + +class PurchaseTransaction(proto.Message): + r"""A transaction represents the entire purchase transaction. + + Attributes: + id (str): + The transaction ID with a length limit of 128 + characters. + revenue (float): + Required. Total non-zero revenue or grand + total associated with the transaction. This + value include shipping, tax, or other + adjustments to total revenue that you want to + include as part of your revenue calculations. + tax (float): + All the taxes associated with the + transaction. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [revenue][google.cloud.retail.v2alpha.PurchaseTransaction.revenue] + - + [tax][google.cloud.retail.v2alpha.PurchaseTransaction.tax] + - + [cost][google.cloud.retail.v2alpha.PurchaseTransaction.cost] + currency_code (str): + Required. Currency code. Use three-character + ISO-4217 code. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + revenue = proto.Field( + proto.FLOAT, + number=2, + ) + tax = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + currency_code = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py new file mode 100644 index 00000000..0e679b22 --- /dev/null +++ b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2alpha.types import user_event as gcr_user_event + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2alpha', + manifest={ + 'WriteUserEventRequest', + 'CollectUserEventRequest', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'RejoinUserEventsMetadata', + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (google.cloud.retail_v2alpha.types.UserEvent): + Required. User event to write. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for 3rd party requests. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.STRING, + number=2, + ) + uri = proto.Field( + proto.STRING, + number=3, + ) + ets = proto.Field( + proto.INT64, + number=4, + ) + + +class RejoinUserEventsRequest(proto.Message): + r"""Request message for RejoinUserEvents method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event_rejoin_scope (google.cloud.retail_v2alpha.types.RejoinUserEventsRequest.UserEventRejoinScope): + The type of the user event rejoin to define the scope and + range of the user events to be rejoined with the latest + product catalog. Defaults to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not + set, or set to an invalid integer value. + """ + class UserEventRejoinScope(proto.Enum): + r"""The scope of user events to be rejoined with the latest product + catalog. If the rejoining aims at reducing number of unjoined + events, set UserEventRejoinScope to UNJOINED_EVENTS. If the + rejoining aims at correcting product catalog information in joined + events, set UserEventRejoinScope to JOINED_EVENTS. If all events + needs to be rejoined, set UserEventRejoinScope to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. + """ + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 + JOINED_EVENTS = 1 + UNJOINED_EVENTS = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event_rejoin_scope = proto.Field( + proto.ENUM, + number=2, + enum=UserEventRejoinScope, + ) + + +class RejoinUserEventsResponse(proto.Message): + r"""Response message for RejoinUserEvents method. + + Attributes: + rejoined_user_events_count (int): + Number of user events that were joined with + latest product catalog. + """ + + rejoined_user_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +class RejoinUserEventsMetadata(proto.Message): + r"""Metadata for RejoinUserEvents method. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/mypy.ini b/owl-bot-staging/v2alpha/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v2alpha/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2alpha/noxfile.py b/owl-bot-staging/v2alpha/noxfile.py new file mode 100644 index 00000000..9f7eeaa1 --- /dev/null +++ b/owl-bot-staging/v2alpha/noxfile.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.6", + "3.7", + "3.8", + "3.9", + "3.10", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==19.10b0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.9" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/retail_v2alpha/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py new file mode 100644 index 00000000..9b5622c2 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async] +from google.cloud import retail_v2alpha + + +async def sample_add_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py new file mode 100644 index 00000000..ec76bc9f --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync] +from google.cloud import retail_v2alpha + + +def sample_add_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py new file mode 100644 index 00000000..d2f66638 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetAttributesConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_get_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetAttributesConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py new file mode 100644 index 00000000..91c914b3 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_get_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py new file mode 100644 index 00000000..9da8e840 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetCompletionConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_get_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetCompletionConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py new file mode 100644 index 00000000..5da5cd9f --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_get_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py new file mode 100644 index 00000000..2134a810 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetDefaultBranch_async] +from google.cloud import retail_v2alpha + + +async def sample_get_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py new file mode 100644 index 00000000..d233b424 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync] +from google.cloud import retail_v2alpha + + +def sample_get_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py new file mode 100644 index 00000000..7e7fbf33 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_ListCatalogs_async] +from google.cloud import retail_v2alpha + + +async def sample_list_catalogs(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py new file mode 100644 index 00000000..8165c25b --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_ListCatalogs_sync] +from google.cloud import retail_v2alpha + + +def sample_list_catalogs(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py new file mode 100644 index 00000000..f79bd768 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async] +from google.cloud import retail_v2alpha + + +async def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = await client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py new file mode 100644 index 00000000..35b6611c --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync] +from google.cloud import retail_v2alpha + + +def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py new file mode 100644 index 00000000..c42a8bb1 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReplaceCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async] +from google.cloud import retail_v2alpha + + +async def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py new file mode 100644 index 00000000..56e779ab --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReplaceCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync] +from google.cloud import retail_v2alpha + + +def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2alpha.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2alpha.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py new file mode 100644 index 00000000..9ddf2f8e --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_SetDefaultBranch_async] +from google.cloud import retail_v2alpha + + +async def sample_set_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + +# [END retail_v2alpha_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py new file mode 100644 index 00000000..6fa13ce6 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync] +from google.cloud import retail_v2alpha + + +def sample_set_default_branch(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + +# [END retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py new file mode 100644 index 00000000..c4654be4 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_update_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + attributes_config = retail_v2alpha.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2alpha.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = await client.update_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py new file mode 100644 index 00000000..1f4d3432 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_update_attributes_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + attributes_config = retail_v2alpha.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2alpha.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = client.update_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py new file mode 100644 index 00000000..6035f718 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateCatalog_async] +from google.cloud import retail_v2alpha + + +async def sample_update_catalog(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2alpha.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2alpha.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py new file mode 100644 index 00000000..35fff0d1 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateCatalog_sync] +from google.cloud import retail_v2alpha + + +def sample_update_catalog(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2alpha.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2alpha.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py new file mode 100644 index 00000000..26cac134 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_update_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceAsyncClient() + + # Initialize request argument(s) + completion_config = retail_v2alpha.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2alpha.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = await client.update_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py new file mode 100644 index 00000000..b9e11448 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_update_completion_config(): + # Create a client + client = retail_v2alpha.CatalogServiceClient() + + # Initialize request argument(s) + completion_config = retail_v2alpha.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2alpha.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = client.update_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py new file mode 100644 index 00000000..13dce99f --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CompletionService_CompleteQuery_async] +from google.cloud import retail_v2alpha + + +async def sample_complete_query(): + # Create a client + client = retail_v2alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py new file mode 100644 index 00000000..20687e33 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CompletionService_CompleteQuery_sync] +from google.cloud import retail_v2alpha + + +def sample_complete_query(): + # Create a client + client = retail_v2alpha.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py new file mode 100644 index 00000000..d1a515f2 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CompletionService_ImportCompletionData_async] +from google.cloud import retail_v2alpha + + +async def sample_import_completion_data(): + # Create a client + client = retail_v2alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2alpha.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py new file mode 100644 index 00000000..3c6ddc55 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_CompletionService_ImportCompletionData_sync] +from google.cloud import retail_v2alpha + + +def sample_import_completion_data(): + # Create a client + client = retail_v2alpha.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2alpha.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py new file mode 100644 index 00000000..131de87e --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_CreateControl_async] +from google.cloud import retail_v2alpha + + +async def sample_create_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = await client.create_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_CreateControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py new file mode 100644 index 00000000..8fee66d8 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_CreateControl_sync] +from google.cloud import retail_v2alpha + + +def sample_create_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = client.create_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_CreateControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py new file mode 100644 index 00000000..ae438a78 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_DeleteControl_async] +from google.cloud import retail_v2alpha + + +async def sample_delete_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteControlRequest( + name="name_value", + ) + + # Make the request + await client.delete_control(request=request) + + +# [END retail_v2alpha_generated_ControlService_DeleteControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py new file mode 100644 index 00000000..b83ddcd5 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_DeleteControl_sync] +from google.cloud import retail_v2alpha + + +def sample_delete_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteControlRequest( + name="name_value", + ) + + # Make the request + client.delete_control(request=request) + + +# [END retail_v2alpha_generated_ControlService_DeleteControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py new file mode 100644 index 00000000..588c8955 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_GetControl_async] +from google.cloud import retail_v2alpha + + +async def sample_get_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetControlRequest( + name="name_value", + ) + + # Make the request + response = await client.get_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_GetControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py new file mode 100644 index 00000000..f04eb36b --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_GetControl_sync] +from google.cloud import retail_v2alpha + + +def sample_get_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetControlRequest( + name="name_value", + ) + + # Make the request + response = client.get_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_GetControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py new file mode 100644 index 00000000..005329c1 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListControls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_ListControls_async] +from google.cloud import retail_v2alpha + + +async def sample_list_controls(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ControlService_ListControls_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py new file mode 100644 index 00000000..301c6036 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListControls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_ListControls_sync] +from google.cloud import retail_v2alpha + + +def sample_list_controls(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ControlService_ListControls_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py new file mode 100644 index 00000000..dc422066 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_UpdateControl_async] +from google.cloud import retail_v2alpha + + +async def sample_update_control(): + # Create a client + client = retail_v2alpha.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.UpdateControlRequest( + control=control, + ) + + # Make the request + response = await client.update_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_UpdateControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py new file mode 100644 index 00000000..cf7823fd --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ControlService_UpdateControl_sync] +from google.cloud import retail_v2alpha + + +def sample_update_control(): + # Create a client + client = retail_v2alpha.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2alpha.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" + + request = retail_v2alpha.UpdateControlRequest( + control=control, + ) + + # Make the request + response = client.update_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ControlService_UpdateControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py new file mode 100644 index 00000000..7d3c4540 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_PredictionService_Predict_async] +from google.cloud import retail_v2alpha + + +async def sample_predict(): + # Create a client + client = retail_v2alpha.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py new file mode 100644 index 00000000..c3dbd187 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_PredictionService_Predict_sync] +from google.cloud import retail_v2alpha + + +def sample_predict(): + # Create a client + client = retail_v2alpha.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py new file mode 100644 index 00000000..4ef15987 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async] +from google.cloud import retail_v2alpha + + +async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py new file mode 100644 index 00000000..03f0cd6d --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync] +from google.cloud import retail_v2alpha + + +def sample_add_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py new file mode 100644 index 00000000..c3b7dfdf --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_AddLocalInventories_async] +from google.cloud import retail_v2alpha + + +async def sample_add_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py new file mode 100644 index 00000000..b91b57f3 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_AddLocalInventories_sync] +from google.cloud import retail_v2alpha + + +def sample_add_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py new file mode 100644 index 00000000..8ca45663 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_CreateProduct_async] +from google.cloud import retail_v2alpha + + +async def sample_create_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py new file mode 100644 index 00000000..b2946508 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_CreateProduct_sync] +from google.cloud import retail_v2alpha + + +def sample_create_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py new file mode 100644 index 00000000..1ae74222 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_DeleteProduct_async] +from google.cloud import retail_v2alpha + + +async def sample_delete_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + +# [END retail_v2alpha_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py new file mode 100644 index 00000000..faebc2e4 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_DeleteProduct_sync] +from google.cloud import retail_v2alpha + + +def sample_delete_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + +# [END retail_v2alpha_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py new file mode 100644 index 00000000..70903b9e --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_GetProduct_async] +from google.cloud import retail_v2alpha + + +async def sample_get_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py new file mode 100644 index 00000000..25fccda2 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_GetProduct_sync] +from google.cloud import retail_v2alpha + + +def sample_get_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py new file mode 100644 index 00000000..5cfaf031 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_ImportProducts_async] +from google.cloud import retail_v2alpha + + +async def sample_import_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2alpha.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py new file mode 100644 index 00000000..ca54ea57 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_ImportProducts_sync] +from google.cloud import retail_v2alpha + + +def sample_import_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2alpha.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py new file mode 100644 index 00000000..8dcf7a71 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_ListProducts_async] +from google.cloud import retail_v2alpha + + +async def sample_list_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py new file mode 100644 index 00000000..aa96e9c2 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_ListProducts_sync] +from google.cloud import retail_v2alpha + + +def sample_list_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py new file mode 100644 index 00000000..8adf6af4 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_PurgeProducts_async] +from google.cloud import retail_v2alpha + + +async def sample_purge_products(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeProductsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_PurgeProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py new file mode 100644 index 00000000..72c32c88 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_PurgeProducts_sync] +from google.cloud import retail_v2alpha + + +def sample_purge_products(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeProductsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_PurgeProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py new file mode 100644 index 00000000..da379da0 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async] +from google.cloud import retail_v2alpha + + +async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py new file mode 100644 index 00000000..55bf6522 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync] +from google.cloud import retail_v2alpha + + +def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py new file mode 100644 index 00000000..bc0b9406 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_RemoveLocalInventories_async] +from google.cloud import retail_v2alpha + + +async def sample_remove_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py new file mode 100644 index 00000000..40e0b2bb --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync] +from google.cloud import retail_v2alpha + + +def sample_remove_local_inventories(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py new file mode 100644 index 00000000..64dc769c --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_SetInventory_async] +from google.cloud import retail_v2alpha + + +async def sample_set_inventory(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2alpha.Product() + inventory.title = "title_value" + + request = retail_v2alpha.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py new file mode 100644 index 00000000..9dbf88b6 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_SetInventory_sync] +from google.cloud import retail_v2alpha + + +def sample_set_inventory(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2alpha.Product() + inventory.title = "title_value" + + request = retail_v2alpha.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py new file mode 100644 index 00000000..35df5c2b --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_UpdateProduct_async] +from google.cloud import retail_v2alpha + + +async def sample_update_product(): + # Create a client + client = retail_v2alpha.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py new file mode 100644 index 00000000..6248e977 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ProductService_UpdateProduct_sync] +from google.cloud import retail_v2alpha + + +def sample_update_product(): + # Create a client + client = retail_v2alpha.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2alpha.Product() + product.title = "title_value" + + request = retail_v2alpha.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py new file mode 100644 index 00000000..75520b76 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_SearchService_Search_async] +from google.cloud import retail_v2alpha + + +async def sample_search(): + # Create a client + client = retail_v2alpha.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py new file mode 100644 index 00000000..2b2853a3 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_SearchService_Search_sync] +from google.cloud import retail_v2alpha + + +def sample_search(): + # Create a client + client = retail_v2alpha.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py new file mode 100644 index 00000000..0694590c --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_AddControl_async] +from google.cloud import retail_v2alpha + + +async def sample_add_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.add_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_AddControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py new file mode 100644 index 00000000..10d50ff7 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_AddControl_sync] +from google.cloud import retail_v2alpha + + +def sample_add_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.add_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_AddControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py new file mode 100644 index 00000000..33b080fc --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_create_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = await client.create_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py new file mode 100644 index 00000000..e7b0e80e --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_create_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = client.create_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py new file mode 100644 index 00000000..f8259bdf --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_delete_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_serving_config(request=request) + + +# [END retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py new file mode 100644 index 00000000..621916ef --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_delete_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_serving_config(request=request) + + +# [END retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py new file mode 100644 index 00000000..fdfd4d80 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_GetServingConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_get_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_GetServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py new file mode 100644 index 00000000..a1408016 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_get_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py new file mode 100644 index 00000000..c8244f95 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServingConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async] +from google.cloud import retail_v2alpha + + +async def sample_list_serving_configs(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py new file mode 100644 index 00000000..86e02687 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServingConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync] +from google.cloud import retail_v2alpha + + +def sample_list_serving_configs(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py new file mode 100644 index 00000000..66e07902 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_RemoveControl_async] +from google.cloud import retail_v2alpha + + +async def sample_remove_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.remove_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_RemoveControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py new file mode 100644 index 00000000..8b39362b --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_RemoveControl_sync] +from google.cloud import retail_v2alpha + + +def sample_remove_control(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.remove_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_RemoveControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py new file mode 100644 index 00000000..64e82dba --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async] +from google.cloud import retail_v2alpha + + +async def sample_update_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = await client.update_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py new file mode 100644 index 00000000..46d2d65c --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync] +from google.cloud import retail_v2alpha + + +def sample_update_serving_config(): + # Create a client + client = retail_v2alpha.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2alpha.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2alpha.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = client.update_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 00000000..f8aa3f78 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_CollectUserEvent_async] +from google.cloud import retail_v2alpha + + +async def sample_collect_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 00000000..026972b1 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_CollectUserEvent_sync] +from google.cloud import retail_v2alpha + + +def sample_collect_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py new file mode 100644 index 00000000..540ce130 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_ImportUserEvents_async] +from google.cloud import retail_v2alpha + + +async def sample_import_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2alpha.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 00000000..fe9310db --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_ImportUserEvents_sync] +from google.cloud import retail_v2alpha + + +def sample_import_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2alpha.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2alpha.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py new file mode 100644 index 00000000..17d5c66d --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_PurgeUserEvents_async] +from google.cloud import retail_v2alpha + + +async def sample_purge_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py new file mode 100644 index 00000000..d8b2ae83 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync] +from google.cloud import retail_v2alpha + + +def sample_purge_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py new file mode 100644 index 00000000..d38bb5f4 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_RejoinUserEvents_async] +from google.cloud import retail_v2alpha + + +async def sample_rejoin_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2alpha.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py new file mode 100644 index 00000000..f88f6437 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync] +from google.cloud import retail_v2alpha + + +def sample_rejoin_user_events(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2alpha.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py new file mode 100644 index 00000000..2dda0e65 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_WriteUserEvent_async] +from google.cloud import retail_v2alpha + + +async def sample_write_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 00000000..a121bdbd --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2alpha_generated_UserEventService_WriteUserEvent_sync] +from google.cloud import retail_v2alpha + + +def sample_write_user_event(): + # Create a client + client = retail_v2alpha.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2alpha.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2alpha_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json b/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json new file mode 100644 index 00000000..ea2cf419 --- /dev/null +++ b/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json @@ -0,0 +1,7066 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.retail.v2alpha", + "version": "v2alpha" + } + ], + "language": "PYTHON", + "name": "google-cloud-retail" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.add_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "AddCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "add_catalog_attribute" + }, + "description": "Sample for AddCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.add_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "AddCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "add_catalog_attribute" + }, + "description": "Sample for AddCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetAttributesConfigRequest" + }, + { + "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.retail_v2alpha.types.AttributesConfig", + "shortName": "get_attributes_config" + }, + "description": "Sample for GetAttributesConfig", + "file": "retail_v2alpha_generated_catalog_service_get_attributes_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetAttributesConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_attributes_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetAttributesConfigRequest" + }, + { + "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.retail_v2alpha.types.AttributesConfig", + "shortName": "get_attributes_config" + }, + "description": "Sample for GetAttributesConfig", + "file": "retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_completion_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetCompletionConfigRequest" + }, + { + "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.retail_v2alpha.types.CompletionConfig", + "shortName": "get_completion_config" + }, + "description": "Sample for GetCompletionConfig", + "file": "retail_v2alpha_generated_catalog_service_get_completion_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetCompletionConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_completion_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_completion_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetCompletionConfigRequest" + }, + { + "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.retail_v2alpha.types.CompletionConfig", + "shortName": "get_completion_config" + }, + "description": "Sample for GetCompletionConfig", + "file": "retail_v2alpha_generated_catalog_service_get_completion_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_completion_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2alpha_generated_catalog_service_get_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetDefaultBranch_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2alpha_generated_catalog_service_get_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_get_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListCatalogsRequest" + }, + { + "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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsAsyncPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2alpha_generated_catalog_service_list_catalogs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_ListCatalogs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_list_catalogs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListCatalogsRequest" + }, + { + "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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2alpha_generated_catalog_service_list_catalogs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_ListCatalogs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_list_catalogs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.remove_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "RemoveCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "remove_catalog_attribute" + }, + "description": "Sample for RemoveCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.remove_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "RemoveCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "remove_catalog_attribute" + }, + "description": "Sample for RemoveCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.replace_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ReplaceCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "replace_catalog_attribute" + }, + "description": "Sample for ReplaceCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.replace_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ReplaceCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", + "shortName": "replace_catalog_attribute" + }, + "description": "Sample for ReplaceCatalogAttribute", + "file": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2alpha_generated_catalog_service_set_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_SetDefaultBranch_async", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_set_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2alpha_generated_catalog_service_set_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_set_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest" + }, + { + "name": "attributes_config", + "type": "google.cloud.retail_v2alpha.types.AttributesConfig" + }, + { + "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.retail_v2alpha.types.AttributesConfig", + "shortName": "update_attributes_config" + }, + "description": "Sample for UpdateAttributesConfig", + "file": "retail_v2alpha_generated_catalog_service_update_attributes_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_attributes_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest" + }, + { + "name": "attributes_config", + "type": "google.cloud.retail_v2alpha.types.AttributesConfig" + }, + { + "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.retail_v2alpha.types.AttributesConfig", + "shortName": "update_attributes_config" + }, + "description": "Sample for UpdateAttributesConfig", + "file": "retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2alpha.types.Catalog" + }, + { + "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.retail_v2alpha.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2alpha_generated_catalog_service_update_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCatalog_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2alpha.types.Catalog" + }, + { + "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.retail_v2alpha.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2alpha_generated_catalog_service_update_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCatalog_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_completion_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest" + }, + { + "name": "completion_config", + "type": "google.cloud.retail_v2alpha.types.CompletionConfig" + }, + { + "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.retail_v2alpha.types.CompletionConfig", + "shortName": "update_completion_config" + }, + "description": "Sample for UpdateCompletionConfig", + "file": "retail_v2alpha_generated_catalog_service_update_completion_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_completion_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_completion_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest" + }, + { + "name": "completion_config", + "type": "google.cloud.retail_v2alpha.types.CompletionConfig" + }, + { + "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.retail_v2alpha.types.CompletionConfig", + "shortName": "update_completion_config" + }, + "description": "Sample for UpdateCompletionConfig", + "file": "retail_v2alpha_generated_catalog_service_update_completion_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_catalog_service_update_completion_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2alpha.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2alpha_generated_completion_service_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CompletionService_CompleteQuery_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_completion_service_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2alpha.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2alpha_generated_completion_service_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CompletionService_CompleteQuery_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_completion_service_complete_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2alpha.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2alpha_generated_completion_service_import_completion_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CompletionService_ImportCompletionData_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_completion_service_import_completion_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2alpha.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2alpha_generated_completion_service_import_completion_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_CompletionService_ImportCompletionData_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_completion_service_import_completion_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.create_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.CreateControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "CreateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateControlRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "control", + "type": "google.cloud.retail_v2alpha.types.Control" + }, + { + "name": "control_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.retail_v2alpha.types.Control", + "shortName": "create_control" + }, + "description": "Sample for CreateControl", + "file": "retail_v2alpha_generated_control_service_create_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_CreateControl_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_create_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.create_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.CreateControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "CreateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateControlRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "control", + "type": "google.cloud.retail_v2alpha.types.Control" + }, + { + "name": "control_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.retail_v2alpha.types.Control", + "shortName": "create_control" + }, + "description": "Sample for CreateControl", + "file": "retail_v2alpha_generated_control_service_create_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_CreateControl_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_create_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.delete_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.DeleteControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "DeleteControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteControlRequest" + }, + { + "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_control" + }, + "description": "Sample for DeleteControl", + "file": "retail_v2alpha_generated_control_service_delete_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_DeleteControl_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_delete_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.delete_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.DeleteControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "DeleteControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteControlRequest" + }, + { + "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_control" + }, + "description": "Sample for DeleteControl", + "file": "retail_v2alpha_generated_control_service_delete_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_DeleteControl_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_delete_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.get_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.GetControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "GetControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetControlRequest" + }, + { + "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.retail_v2alpha.types.Control", + "shortName": "get_control" + }, + "description": "Sample for GetControl", + "file": "retail_v2alpha_generated_control_service_get_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_GetControl_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_get_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.get_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.GetControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "GetControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetControlRequest" + }, + { + "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.retail_v2alpha.types.Control", + "shortName": "get_control" + }, + "description": "Sample for GetControl", + "file": "retail_v2alpha_generated_control_service_get_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_GetControl_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_get_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.list_controls", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.ListControls", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListControlsRequest" + }, + { + "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.retail_v2alpha.services.control_service.pagers.ListControlsAsyncPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "retail_v2alpha_generated_control_service_list_controls_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_ListControls_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_list_controls_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.list_controls", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.ListControls", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListControlsRequest" + }, + { + "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.retail_v2alpha.services.control_service.pagers.ListControlsPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "retail_v2alpha_generated_control_service_list_controls_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_ListControls_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_list_controls_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.update_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.UpdateControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "UpdateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateControlRequest" + }, + { + "name": "control", + "type": "google.cloud.retail_v2alpha.types.Control" + }, + { + "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.retail_v2alpha.types.Control", + "shortName": "update_control" + }, + "description": "Sample for UpdateControl", + "file": "retail_v2alpha_generated_control_service_update_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_UpdateControl_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_update_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.update_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ControlService.UpdateControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ControlService", + "shortName": "ControlService" + }, + "shortName": "UpdateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateControlRequest" + }, + { + "name": "control", + "type": "google.cloud.retail_v2alpha.types.Control" + }, + { + "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.retail_v2alpha.types.Control", + "shortName": "update_control" + }, + "description": "Sample for UpdateControl", + "file": "retail_v2alpha_generated_control_service_update_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ControlService_UpdateControl_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_control_service_update_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.PredictionServiceAsyncClient", + "shortName": "PredictionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.PredictionServiceAsyncClient.predict", + "method": { + "fullName": "google.cloud.retail.v2alpha.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2alpha.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2alpha_generated_prediction_service_predict_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_PredictionService_Predict_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_prediction_service_predict_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.PredictionServiceClient", + "shortName": "PredictionServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.PredictionServiceClient.predict", + "method": { + "fullName": "google.cloud.retail.v2alpha.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2alpha.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2alpha_generated_prediction_service_predict_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_PredictionService_Predict_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_prediction_service_predict_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2alpha_generated_product_service_add_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_add_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2alpha_generated_product_service_add_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_AddLocalInventories_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_add_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2alpha_generated_product_service_add_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_AddLocalInventories_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_add_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "name": "product_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.retail_v2alpha.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2alpha_generated_product_service_create_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_CreateProduct_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_create_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "name": "product_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.retail_v2alpha.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2alpha_generated_product_service_create_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_CreateProduct_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_create_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2alpha_generated_product_service_delete_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_DeleteProduct_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_delete_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2alpha_generated_product_service_delete_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_DeleteProduct_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_delete_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetProductRequest" + }, + { + "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.retail_v2alpha.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2alpha_generated_product_service_get_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_GetProduct_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_get_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetProductRequest" + }, + { + "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.retail_v2alpha.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2alpha_generated_product_service_get_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_GetProduct_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_get_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2alpha_generated_product_service_import_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_ImportProducts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_import_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2alpha_generated_product_service_import_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_ImportProducts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_import_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListProductsRequest" + }, + { + "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.retail_v2alpha.services.product_service.pagers.ListProductsAsyncPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2alpha_generated_product_service_list_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_ListProducts_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_list_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListProductsRequest" + }, + { + "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.retail_v2alpha.services.product_service.pagers.ListProductsPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2alpha_generated_product_service_list_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_ListProducts_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_list_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.purge_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.PurgeProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "PurgeProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PurgeProductsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_products" + }, + "description": "Sample for PurgeProducts", + "file": "retail_v2alpha_generated_product_service_purge_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_PurgeProducts_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_purge_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.purge_products", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.PurgeProducts", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "PurgeProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PurgeProductsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_products" + }, + "description": "Sample for PurgeProducts", + "file": "retail_v2alpha_generated_product_service_purge_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_PurgeProducts_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_purge_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2alpha_generated_product_service_remove_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_RemoveLocalInventories_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_remove_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2alpha_generated_product_service_remove_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_remove_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2alpha_generated_product_service_set_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_SetInventory_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_set_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2alpha_generated_product_service_set_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_SetInventory_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_set_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "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.retail_v2alpha.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2alpha_generated_product_service_update_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_UpdateProduct_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_update_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2alpha.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2alpha.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2alpha.types.Product" + }, + { + "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.retail_v2alpha.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2alpha_generated_product_service_update_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ProductService_UpdateProduct_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_product_service_update_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.SearchServiceAsyncClient.search", + "method": { + "fullName": "google.cloud.retail.v2alpha.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2alpha.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2alpha_generated_search_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_SearchService_Search_async", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_search_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.SearchServiceClient", + "shortName": "SearchServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.SearchServiceClient.search", + "method": { + "fullName": "google.cloud.retail.v2alpha.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2alpha.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.services.search_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2alpha_generated_search_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_SearchService_Search_sync", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_search_service_search_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.add_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.AddControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "AddControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "add_control" + }, + "description": "Sample for AddControl", + "file": "retail_v2alpha_generated_serving_config_service_add_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_AddControl_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_add_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.add_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.AddControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "AddControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.AddControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "add_control" + }, + "description": "Sample for AddControl", + "file": "retail_v2alpha_generated_serving_config_service_add_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_AddControl_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_add_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.create_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.CreateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "CreateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateServingConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2alpha.types.ServingConfig" + }, + { + "name": "serving_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "create_serving_config" + }, + "description": "Sample for CreateServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_create_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_create_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.create_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.CreateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "CreateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CreateServingConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2alpha.types.ServingConfig" + }, + { + "name": "serving_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "create_serving_config" + }, + "description": "Sample for CreateServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.delete_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.DeleteServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "DeleteServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteServingConfigRequest" + }, + { + "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_serving_config" + }, + "description": "Sample for DeleteServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.delete_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.DeleteServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "DeleteServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.DeleteServingConfigRequest" + }, + { + "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_serving_config" + }, + "description": "Sample for DeleteServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.get_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.GetServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "GetServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetServingConfigRequest" + }, + { + "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.retail_v2alpha.types.ServingConfig", + "shortName": "get_serving_config" + }, + "description": "Sample for GetServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_get_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_GetServingConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_get_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.get_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.GetServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "GetServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.GetServingConfigRequest" + }, + { + "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.retail_v2alpha.types.ServingConfig", + "shortName": "get_serving_config" + }, + "description": "Sample for GetServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.list_serving_configs", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.ListServingConfigs", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "ListServingConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListServingConfigsRequest" + }, + { + "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.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsAsyncPager", + "shortName": "list_serving_configs" + }, + "description": "Sample for ListServingConfigs", + "file": "retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.list_serving_configs", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.ListServingConfigs", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "ListServingConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ListServingConfigsRequest" + }, + { + "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.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsPager", + "shortName": "list_serving_configs" + }, + "description": "Sample for ListServingConfigs", + "file": "retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.remove_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.RemoveControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "RemoveControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "remove_control" + }, + "description": "Sample for RemoveControl", + "file": "retail_v2alpha_generated_serving_config_service_remove_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_RemoveControl_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_remove_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.remove_control", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.RemoveControl", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "RemoveControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RemoveControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", + "shortName": "remove_control" + }, + "description": "Sample for RemoveControl", + "file": "retail_v2alpha_generated_serving_config_service_remove_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_RemoveControl_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_remove_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.update_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.UpdateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "UpdateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateServingConfigRequest" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2alpha.types.ServingConfig" + }, + { + "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.retail_v2alpha.types.ServingConfig", + "shortName": "update_serving_config" + }, + "description": "Sample for UpdateServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_update_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_update_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.update_serving_config", + "method": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService.UpdateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2alpha.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "UpdateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.UpdateServingConfigRequest" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2alpha.types.ServingConfig" + }, + { + "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.retail_v2alpha.types.ServingConfig", + "shortName": "update_serving_config" + }, + "description": "Sample for UpdateServingConfig", + "file": "retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2alpha_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_CollectUserEvent_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2alpha_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_CollectUserEvent_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2alpha_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_ImportUserEvents_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2alpha_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_ImportUserEvents_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2alpha_generated_user_event_service_purge_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_PurgeUserEvents_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_purge_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2alpha_generated_user_event_service_purge_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_purge_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_RejoinUserEvents_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2alpha_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_WriteUserEvent_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2alpha.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2alpha.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2alpha.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2alpha_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2alpha_generated_UserEventService_WriteUserEvent_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2alpha_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py b/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py new file mode 100644 index 00000000..5fbe2d4d --- /dev/null +++ b/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py @@ -0,0 +1,219 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class retailCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_catalog_attribute': ('attributes_config', 'catalog_attribute', ), + 'add_control': ('serving_config', 'control_id', ), + 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), + 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), + 'create_control': ('parent', 'control', 'control_id', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'create_serving_config': ('parent', 'serving_config', 'serving_config_id', ), + 'delete_control': ('name', ), + 'delete_product': ('name', ), + 'delete_serving_config': ('name', ), + 'get_attributes_config': ('name', ), + 'get_completion_config': ('name', ), + 'get_control': ('name', ), + 'get_default_branch': ('catalog', ), + 'get_product': ('name', ), + 'get_serving_config': ('name', ), + 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), + 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), + 'import_user_events': ('parent', 'input_config', 'errors_config', ), + 'list_catalogs': ('parent', 'page_size', 'page_token', ), + 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', 'require_total_size', ), + 'list_serving_configs': ('parent', 'page_size', 'page_token', ), + 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), + 'purge_products': ('parent', 'filter', 'force', ), + 'purge_user_events': ('parent', 'filter', 'force', ), + 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), + 'remove_catalog_attribute': ('attributes_config', 'key', ), + 'remove_control': ('serving_config', 'control_id', ), + 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), + 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), + 'replace_catalog_attribute': ('attributes_config', 'catalog_attribute', 'update_mask', ), + 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'relevance_threshold', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), + 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), + 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), + 'update_attributes_config': ('attributes_config', 'update_mask', ), + 'update_catalog': ('catalog', 'update_mask', ), + 'update_completion_config': ('completion_config', 'update_mask', ), + 'update_control': ('control', 'update_mask', ), + 'update_product': ('product', 'update_mask', 'allow_missing', ), + 'update_serving_config': ('serving_config', 'update_mask', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=retailCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the retail client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2alpha/setup.py b/owl-bot-staging/v2alpha/setup.py new file mode 100644 index 00000000..1103510b --- /dev/null +++ b/owl-bot-staging/v2alpha/setup.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-retail', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-retail", + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 2.8.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'googleapis-common-protos >= 1.55.0, <2.0.0dev', + 'proto-plus >= 1.19.7', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2alpha/tests/__init__.py b/owl-bot-staging/v2alpha/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/tests/unit/__init__.py b/owl-bot-staging/v2alpha/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py new file mode 100644 index 00000000..44a7cde0 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py @@ -0,0 +1,3843 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.catalog_service import CatalogServiceAsyncClient +from google.cloud.retail_v2alpha.services.catalog_service import CatalogServiceClient +from google.cloud.retail_v2alpha.services.catalog_service import pagers +from google.cloud.retail_v2alpha.services.catalog_service import transports +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CatalogServiceClient._get_default_mtls_endpoint(None) is None + assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CatalogServiceGrpcTransport, "grpc"), + (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_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", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_catalog_service_client_get_transport_class(): + transport = CatalogServiceClient.get_transport_class() + available_transports = [ + transports.CatalogServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CatalogServiceClient.get_transport_class("grpc") + assert transport == transports.CatalogServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CatalogServiceClient, CatalogServiceAsyncClient +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_catalog_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ListCatalogsRequest, + dict, +]) +def test_list_catalogs(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_catalogs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalogs), + '__call__') as call: + client.list_catalogs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + +@pytest.mark.asyncio +async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_catalogs_async_from_dict(): + await test_list_catalogs_async(request_type=dict) + + +def test_list_catalogs_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = catalog_service.ListCatalogsResponse() + client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_catalogs( + 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_catalogs_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_catalogs_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_catalogs( + 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_catalogs_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + + +def test_list_catalogs_pager(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_catalogs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, catalog.Catalog) + for i in results) +def test_list_catalogs_pages(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = list(client.list_catalogs(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_catalogs_async_pager(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_catalogs(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, catalog.Catalog) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_catalogs_async_pages(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCatalogRequest, + dict, +]) +def test_update_catalog(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + ) + response = client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_catalog_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalog), + '__call__') as call: + client.update_catalog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + +@pytest.mark.asyncio +async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_catalog_async_from_dict(): + await test_update_catalog_async(request_type=dict) + + +def test_update_catalog_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = gcr_catalog.Catalog() + client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_catalog_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +def test_update_catalog_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_catalog_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.SetDefaultBranchRequest, + dict, +]) +def test_set_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_set_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + client.set_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_set_default_branch_async_from_dict(): + await test_set_default_branch_async(request_type=dict) + + +def test_set_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = None + client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_set_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_set_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetDefaultBranchRequest, + dict, +]) +def test_get_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + ) + response = client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +def test_get_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_default_branch), + '__call__') as call: + client.get_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + )) + response = await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +@pytest.mark.asyncio +async def test_get_default_branch_async_from_dict(): + await test_get_default_branch_async(request_type=dict) + + +def test_get_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = catalog_service.GetDefaultBranchResponse() + client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_get_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_get_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetCompletionConfigRequest, + dict, +]) +def test_get_completion_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + ) + response = client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +def test_get_completion_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_completion_config), + '__call__') as call: + client.get_completion_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + +@pytest.mark.asyncio +async def test_get_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCompletionConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + )) + response = await client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +@pytest.mark.asyncio +async def test_get_completion_config_async_from_dict(): + await test_get_completion_config_async(request_type=dict) + + +def test_get_completion_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCompletionConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + call.return_value = catalog.CompletionConfig() + client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_completion_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCompletionConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + await client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_completion_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_completion_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_completion_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_completion_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_completion_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_completion_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCompletionConfigRequest, + dict, +]) +def test_update_completion_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + ) + response = client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +def test_update_completion_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_completion_config), + '__call__') as call: + client.update_completion_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + +@pytest.mark.asyncio +async def test_update_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCompletionConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + )) + response = await client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +@pytest.mark.asyncio +async def test_update_completion_config_async_from_dict(): + await test_update_completion_config_async(request_type=dict) + + +def test_update_completion_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCompletionConfigRequest() + + request.completion_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + call.return_value = catalog.CompletionConfig() + client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'completion_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_completion_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCompletionConfigRequest() + + request.completion_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + await client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'completion_config.name=name_value', + ) in kw['metadata'] + + +def test_update_completion_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_completion_config( + completion_config=catalog.CompletionConfig(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].completion_config + mock_val = catalog.CompletionConfig(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_completion_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_completion_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_completion_config( + completion_config=catalog.CompletionConfig(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].completion_config + mock_val = catalog.CompletionConfig(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_completion_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetAttributesConfigRequest, + dict, +]) +def test_get_attributes_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_get_attributes_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_attributes_config), + '__call__') as call: + client.get_attributes_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + +@pytest.mark.asyncio +async def test_get_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetAttributesConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_get_attributes_config_async_from_dict(): + await test_get_attributes_config_async(request_type=dict) + + +def test_get_attributes_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetAttributesConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_attributes_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetAttributesConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_attributes_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_attributes_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_attributes_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_attributes_config( + catalog_service.GetAttributesConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_attributes_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_attributes_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_attributes_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_attributes_config( + catalog_service.GetAttributesConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateAttributesConfigRequest, + dict, +]) +def test_update_attributes_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_update_attributes_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_attributes_config), + '__call__') as call: + client.update_attributes_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + +@pytest.mark.asyncio +async def test_update_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateAttributesConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_update_attributes_config_async_from_dict(): + await test_update_attributes_config_async(request_type=dict) + + +def test_update_attributes_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateAttributesConfigRequest() + + request.attributes_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_attributes_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateAttributesConfigRequest() + + request.attributes_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config.name=name_value', + ) in kw['metadata'] + + +def test_update_attributes_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_attributes_config( + attributes_config=catalog.AttributesConfig(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].attributes_config + mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_attributes_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_attributes_config( + attributes_config=catalog.AttributesConfig(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].attributes_config + mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.AddCatalogAttributeRequest, + dict, +]) +def test_add_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_add_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + client.add_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_add_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.AddCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_add_catalog_attribute_async_from_dict(): + await test_add_catalog_attribute_async(request_type=dict) + + +def test_add_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.AddCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.AddCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + catalog_service.RemoveCatalogAttributeRequest, + dict, +]) +def test_remove_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_remove_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + client.remove_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.RemoveCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_async_from_dict(): + await test_remove_catalog_attribute_async(request_type=dict) + + +def test_remove_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.RemoveCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.RemoveCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ReplaceCatalogAttributeRequest, + dict, +]) +def test_replace_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_replace_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + client.replace_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ReplaceCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_async_from_dict(): + await test_replace_catalog_attribute_async(request_type=dict) + + +def test_replace_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ReplaceCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ReplaceCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CatalogServiceClient.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 = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CatalogServiceGrpcTransport, + ) + +def test_catalog_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_catalog_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_catalogs', + 'update_catalog', + 'set_default_branch', + 'get_default_branch', + 'get_completion_config', + 'update_completion_config', + 'get_attributes_config', + 'update_attributes_config', + 'add_catalog_attribute', + 'remove_catalog_attribute', + 'replace_catalog_attribute', + ) + 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_catalog_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.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport( + 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_catalog_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.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport() + adc.assert_called_once() + + +def test_catalog_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) + CatalogServiceClient() + 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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +def test_catalog_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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +def test_catalog_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.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_catalog_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_no_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_with_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_catalog_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcTransport( + 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_catalog_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcAsyncIOTransport( + 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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_attributes_config_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.attributes_config_path(project, location, catalog) + assert expected == actual + + +def test_parse_attributes_config_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CatalogServiceClient.attributes_config_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_attributes_config_path(path) + assert expected == actual + +def test_branch_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = CatalogServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "branch": "clam", + } + path = CatalogServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_branch_path(path) + assert expected == actual + +def test_catalog_path(): + project = "whelk" + location = "octopus" + catalog = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + } + path = CatalogServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_completion_config_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.completion_config_path(project, location, catalog) + assert expected == actual + + +def test_parse_completion_config_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + } + path = CatalogServiceClient.completion_config_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_completion_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CatalogServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = CatalogServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = CatalogServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CatalogServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CatalogServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CatalogServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = CatalogServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CatalogServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CatalogServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CatalogServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py new file mode 100644 index 00000000..9e035903 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py @@ -0,0 +1,1501 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.completion_service import CompletionServiceAsyncClient +from google.cloud.retail_v2alpha.services.completion_service import CompletionServiceClient +from google.cloud.retail_v2alpha.services.completion_service import transports +from google.cloud.retail_v2alpha.types import completion_service +from google.cloud.retail_v2alpha.types import import_config +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CompletionServiceClient._get_default_mtls_endpoint(None) is None + assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CompletionServiceGrpcTransport, "grpc"), + (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_completion_service_client_get_transport_class(): + transport = CompletionServiceClient.get_transport_class() + available_transports = [ + transports.CompletionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CompletionServiceClient.get_transport_class("grpc") + assert transport == transports.CompletionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CompletionServiceClient, CompletionServiceAsyncClient +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_completion_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CompletionServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + ) + response = client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +def test_complete_query_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + client.complete_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + +@pytest.mark.asyncio +async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + )) + response = await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +@pytest.mark.asyncio +async def test_complete_query_async_from_dict(): + await test_complete_query_async(request_type=dict) + + +def test_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) + await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportCompletionDataRequest, + dict, +]) +def test_import_completion_data(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_completion_data_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + client.import_completion_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + +@pytest.mark.asyncio +async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_completion_data_async_from_dict(): + await test_import_completion_data_async(request_type=dict) + + +def test_import_completion_data_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # 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_completion_data_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CompletionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CompletionServiceGrpcTransport, + ) + +def test_completion_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_completion_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'complete_query', + 'import_completion_data', + ) + 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_completion_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_completion_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport() + adc.assert_called_once() + + +def test_completion_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CompletionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionServiceGrpcTransport, grpc_helpers), + (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_completion_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_no_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_with_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_completion_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_completion_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_completion_service_grpc_lro_client(): + client = CompletionServiceClient( + 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_completion_service_grpc_lro_async_client(): + client = CompletionServiceAsyncClient( + 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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CompletionServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CompletionServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CompletionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CompletionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = CompletionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CompletionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CompletionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CompletionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = CompletionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CompletionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CompletionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CompletionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CompletionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py new file mode 100644 index 00000000..1f7f23e9 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py @@ -0,0 +1,2616 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.control_service import ControlServiceAsyncClient +from google.cloud.retail_v2alpha.services.control_service import ControlServiceClient +from google.cloud.retail_v2alpha.services.control_service import pagers +from google.cloud.retail_v2alpha.services.control_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service +from google.cloud.retail_v2alpha.types import search_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ControlServiceClient._get_default_mtls_endpoint(None) is None + assert ControlServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ControlServiceClient, "grpc"), + (ControlServiceAsyncClient, "grpc_asyncio"), +]) +def test_control_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ControlServiceGrpcTransport, "grpc"), + (transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_control_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", [ + (ControlServiceClient, "grpc"), + (ControlServiceAsyncClient, "grpc_asyncio"), +]) +def test_control_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_control_service_client_get_transport_class(): + transport = ControlServiceClient.get_transport_class() + available_transports = [ + transports.ControlServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ControlServiceClient.get_transport_class("grpc") + assert transport == transports.ControlServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +def test_control_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(ControlServiceClient, '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(ControlServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "true"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "false"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_control_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ControlServiceClient, ControlServiceAsyncClient +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +def test_control_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_control_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_control_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_control_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.control_service.transports.ControlServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ControlServiceClient( + 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", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_control_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.CreateControlRequest, + dict, +]) +def test_create_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +def test_create_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.create_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + +@pytest.mark.asyncio +async def test_create_control_async(transport: str = 'grpc_asyncio', request_type=control_service.CreateControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + )) + response = await client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +@pytest.mark.asyncio +async def test_create_control_async_from_dict(): + await test_create_control_async(request_type=dict) + + +def test_create_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.CreateControlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + call.return_value = gcr_control.Control() + client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.CreateControlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + await client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_control( + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) + assert arg == mock_val + arg = args[0].control_id + mock_val = 'control_id_value' + assert arg == mock_val + + +def test_create_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.CreateControlRequest(), + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_id_value', + ) + +@pytest.mark.asyncio +async def test_create_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_control( + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) + assert arg == mock_val + arg = args[0].control_id + mock_val = 'control_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.CreateControlRequest(), + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.DeleteControlRequest, + dict, +]) +def test_delete_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.delete_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + +@pytest.mark.asyncio +async def test_delete_control_async(transport: str = 'grpc_asyncio', request_type=control_service.DeleteControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_control_async_from_dict(): + await test_delete_control_async(request_type=dict) + + +def test_delete_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.DeleteControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__call__') as call: + call.return_value = None + client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.DeleteControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__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_control( + 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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.DeleteControlRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__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_control( + 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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.DeleteControlRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.UpdateControlRequest, + dict, +]) +def test_update_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +def test_update_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.update_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + +@pytest.mark.asyncio +async def test_update_control_async(transport: str = 'grpc_asyncio', request_type=control_service.UpdateControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + )) + response = await client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +@pytest.mark.asyncio +async def test_update_control_async_from_dict(): + await test_update_control_async(request_type=dict) + + +def test_update_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.UpdateControlRequest() + + request.control.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + call.return_value = gcr_control.Control() + client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'control.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.UpdateControlRequest() + + request.control.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + await client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'control.name=name_value', + ) in kw['metadata'] + + +def test_update_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_control( + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_control( + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.GetControlRequest, + dict, +]) +def test_get_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +def test_get_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.get_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + +@pytest.mark.asyncio +async def test_get_control_async(transport: str = 'grpc_asyncio', request_type=control_service.GetControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], + )) + response = await client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] + + +@pytest.mark.asyncio +async def test_get_control_async_from_dict(): + await test_get_control_async(request_type=dict) + + +def test_get_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.GetControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + call.return_value = control.Control() + client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.GetControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) + await client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_control( + 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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.GetControlRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_control( + 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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.GetControlRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.ListControlsRequest, + dict, +]) +def test_list_controls(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_controls_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_controls), + '__call__') as call: + client.list_controls() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + +@pytest.mark.asyncio +async def test_list_controls_async(transport: str = 'grpc_asyncio', request_type=control_service.ListControlsRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_controls_async_from_dict(): + await test_list_controls_async(request_type=dict) + + +def test_list_controls_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.ListControlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + call.return_value = control_service.ListControlsResponse() + client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_controls_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.ListControlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) + await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_controls_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_controls( + 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_controls_flattened_error(): + client = ControlServiceClient( + credentials=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_controls( + control_service.ListControlsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_controls_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_controls( + 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_controls_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_controls( + control_service.ListControlsRequest(), + parent='parent_value', + ) + + +def test_list_controls_pager(transport_name: str = "grpc"): + client = ControlServiceClient( + 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_controls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_controls(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, control.Control) + for i in results) +def test_list_controls_pages(transport_name: str = "grpc"): + client = ControlServiceClient( + 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_controls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + pages = list(client.list_controls(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_controls_async_pager(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_controls(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, control.Control) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_controls_async_pages(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_controls(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ControlServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ControlServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ControlServiceClient.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 = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ControlServiceGrpcTransport, + ) + +def test_control_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ControlServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_control_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.control_service.transports.ControlServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ControlServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_control', + 'delete_control', + 'update_control', + 'get_control', + 'list_controls', + ) + 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_control_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.retail_v2alpha.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ControlServiceTransport( + 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_control_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.retail_v2alpha.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ControlServiceTransport() + adc.assert_called_once() + + +def test_control_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) + ControlServiceClient() + 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.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + ], +) +def test_control_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.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + ], +) +def test_control_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.ControlServiceGrpcTransport, grpc_helpers), + (transports.ControlServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_control_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_control_service_host_no_port(transport_name): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_control_service_host_with_port(transport_name): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_control_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ControlServiceGrpcTransport( + 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_control_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ControlServiceGrpcAsyncIOTransport( + 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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = ControlServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = ControlServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_control_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + control = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) + actual = ControlServiceClient.control_path(project, location, catalog, control) + assert expected == actual + + +def test_parse_control_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "control": "clam", + } + path = ControlServiceClient.control_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_control_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ControlServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ControlServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ControlServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ControlServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ControlServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ControlServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ControlServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ControlServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.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 = ControlServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ControlServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.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.ControlServiceTransport, '_prep_wrapped_messages') as prep: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ControlServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ControlServiceClient.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 = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ControlServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ControlServiceClient( + 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", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py new file mode 100644 index 00000000..e1744b72 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py @@ -0,0 +1,1329 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.prediction_service import PredictionServiceAsyncClient +from google.cloud.retail_v2alpha.services.prediction_service import PredictionServiceClient +from google.cloud.retail_v2alpha.services.prediction_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import prediction_service +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import user_event +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PredictionServiceClient._get_default_mtls_endpoint(None) is None + assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionServiceGrpcTransport, "grpc"), + (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_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", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_prediction_service_client_get_transport_class(): + transport = PredictionServiceClient.get_transport_class() + available_transports = [ + transports.PredictionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = PredictionServiceClient.get_transport_class("grpc") + assert transport == transports.PredictionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + PredictionServiceClient, PredictionServiceAsyncClient +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_prediction_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_service.PredictRequest, + dict, +]) +def test_predict(request_type, transport: str = 'grpc'): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + response = client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_predict_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + client.predict() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + +@pytest.mark.asyncio +async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + )) + response = await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +@pytest.mark.asyncio +async def test_predict_async_from_dict(): + await test_predict_async(request_type=dict) + + +def test_predict_field_headers(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_predict_field_headers_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) + await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = PredictionServiceClient.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 = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'predict', + ) + 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport( + 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport() + adc.assert_called_once() + + +def test_prediction_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) + PredictionServiceClient() + 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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +def test_prediction_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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +def test_prediction_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.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_prediction_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_no_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_with_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_prediction_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcTransport( + 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_prediction_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcAsyncIOTransport( + 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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_product_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + product = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + "branch": "winkle", + "product": "nautilus", + } + path = PredictionServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PredictionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = PredictionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = PredictionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = PredictionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PredictionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = PredictionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = PredictionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = PredictionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = PredictionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PredictionServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py new file mode 100644 index 00000000..1bc17bbe --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py @@ -0,0 +1,4287 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.product_service import ProductServiceAsyncClient +from google.cloud.retail_v2alpha.services.product_service import ProductServiceClient +from google.cloud.retail_v2alpha.services.product_service import pagers +from google.cloud.retail_v2alpha.services.product_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import purge_config +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProductServiceClient._get_default_mtls_endpoint(None) is None + assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProductServiceGrpcTransport, "grpc"), + (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_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", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_product_service_client_get_transport_class(): + transport = ProductServiceClient.get_transport_class() + available_transports = [ + transports.ProductServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ProductServiceClient.get_transport_class("grpc") + assert transport == transports.ProductServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_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(ProductServiceClient, '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(ProductServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ProductServiceClient, ProductServiceAsyncClient +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_product_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.CreateProductRequest, + dict, +]) +def test_create_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_create_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.create_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + +@pytest.mark.asyncio +async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_create_product_async_from_dict(): + await test_create_product_async(request_type=dict) + + +def test_create_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + + +def test_create_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + +@pytest.mark.asyncio +async def test_create_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_get_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.get_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + +@pytest.mark.asyncio +async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_get_product_async_from_dict(): + await test_get_product_async(request_type=dict) + + +def test_get_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = product.Product() + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.GetProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.GetProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.list_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + +@pytest.mark.asyncio +async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_products_async_from_dict(): + await test_list_products_async(request_type=dict) + + +def test_list_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = product_service.ListProductsResponse() + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products( + 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_products_flattened_error(): + client = ProductServiceClient( + credentials=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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products( + 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_products_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + + +def test_list_products_pager(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_products(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, product.Product) + for i in results) +def test_list_products_pages(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(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_products_async_pager(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(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, product.Product) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_products(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + product_service.UpdateProductRequest, + dict, +]) +def test_update_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_update_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.update_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + +@pytest.mark.asyncio +async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_update_product_async_from_dict(): + await test_update_product_async(request_type=dict) + + +def test_update_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +def test_update_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.DeleteProductRequest, + dict, +]) +def test_delete_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.delete_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + +@pytest.mark.asyncio +async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_product_async_from_dict(): + await test_delete_product_async(request_type=dict) + + +def test_delete_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = None + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeProductsRequest, + dict, +]) +def test_purge_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + client.purge_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeProductsRequest() + +@pytest.mark.asyncio +async def test_purge_products_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_products_async_from_dict(): + await test_purge_products_async(request_type=dict) + + +def test_purge_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_purge_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportProductsRequest, + dict, +]) +def test_import_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.import_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + +@pytest.mark.asyncio +async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__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_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_products_async_from_dict(): + await test_import_products_async(request_type=dict) + + +def test_import_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + product_service.SetInventoryRequest, + dict, +]) +def test_set_inventory(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_inventory_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + client.set_inventory() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + +@pytest.mark.asyncio +async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_set_inventory_async_from_dict(): + await test_set_inventory_async(request_type=dict) + + +def test_set_inventory_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_inventory_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +def test_set_inventory_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_set_inventory_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_set_inventory_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_inventory_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddFulfillmentPlacesRequest, + dict, +]) +def test_add_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + client.add_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async_from_dict(): + await test_add_fulfillment_places_async(request_type=dict) + + +def test_add_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveFulfillmentPlacesRequest, + dict, +]) +def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + client.remove_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async_from_dict(): + await test_remove_fulfillment_places_async(request_type=dict) + + +def test_remove_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddLocalInventoriesRequest, + dict, +]) +def test_add_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + client.add_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_local_inventories_async_from_dict(): + await test_add_local_inventories_async(request_type=dict) + + +def test_add_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveLocalInventoriesRequest, + dict, +]) +def test_remove_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + client.remove_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_local_inventories_async_from_dict(): + await test_remove_local_inventories_async(request_type=dict) + + +def test_remove_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ProductServiceClient.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 = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProductServiceGrpcTransport, + ) + +def test_product_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_product_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.product_service.transports.ProductServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_product', + 'get_product', + 'list_products', + 'update_product', + 'delete_product', + 'purge_products', + 'import_products', + 'set_inventory', + 'add_fulfillment_places', + 'remove_fulfillment_places', + 'add_local_inventories', + 'remove_local_inventories', + ) + 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_product_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.retail_v2alpha.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport( + 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_product_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.retail_v2alpha.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport() + adc.assert_called_once() + + +def test_product_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) + ProductServiceClient() + 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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + ], +) +def test_product_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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + ], +) +def test_product_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.ProductServiceGrpcTransport, grpc_helpers), + (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_product_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_no_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_with_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_product_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcTransport( + 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_product_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcAsyncIOTransport( + 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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_product_service_grpc_lro_client(): + client = ProductServiceClient( + 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_product_service_grpc_lro_async_client(): + client = ProductServiceAsyncClient( + 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" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = ProductServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = ProductServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = ProductServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = ProductServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProductServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ProductServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProductServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ProductServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProductServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ProductServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ProductServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ProductServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ProductServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ProductServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ProductServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py new file mode 100644 index 00000000..05a00622 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py @@ -0,0 +1,1546 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.search_service import SearchServiceAsyncClient +from google.cloud.retail_v2alpha.services.search_service import SearchServiceClient +from google.cloud.retail_v2alpha.services.search_service import pagers +from google.cloud.retail_v2alpha.services.search_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SearchServiceClient._get_default_mtls_endpoint(None) is None + assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SearchServiceGrpcTransport, "grpc"), + (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_search_service_client_get_transport_class(): + transport = SearchServiceClient.get_transport_class() + available_transports = [ + transports.SearchServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SearchServiceClient.get_transport_class("grpc") + assert transport == transports.SearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SearchServiceClient, SearchServiceAsyncClient +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SearchServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + search_service.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + + +def test_search_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = search_service.SearchResponse() + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_search_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('placement', ''), + )), + ) + pager = client.search(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_async_pager(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = SearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_search_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_search_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport() + adc.assert_called_once() + + +def test_search_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SearchServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SearchServiceGrpcTransport, grpc_helpers), + (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_search_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_no_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_with_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_branch_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = SearchServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = SearchServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = SearchServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = SearchServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py new file mode 100644 index 00000000..12d27ac2 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py @@ -0,0 +1,3329 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.serving_config_service import ServingConfigServiceAsyncClient +from google.cloud.retail_v2alpha.services.serving_config_service import ServingConfigServiceClient +from google.cloud.retail_v2alpha.services.serving_config_service import pagers +from google.cloud.retail_v2alpha.services.serving_config_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import search_service +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ServingConfigServiceClient._get_default_mtls_endpoint(None) is None + assert ServingConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ServingConfigServiceClient, "grpc"), + (ServingConfigServiceAsyncClient, "grpc_asyncio"), +]) +def test_serving_config_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ServingConfigServiceGrpcTransport, "grpc"), + (transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_serving_config_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", [ + (ServingConfigServiceClient, "grpc"), + (ServingConfigServiceAsyncClient, "grpc_asyncio"), +]) +def test_serving_config_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_serving_config_service_client_get_transport_class(): + transport = ServingConfigServiceClient.get_transport_class() + available_transports = [ + transports.ServingConfigServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ServingConfigServiceClient.get_transport_class("grpc") + assert transport == transports.ServingConfigServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +def test_serving_config_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(ServingConfigServiceClient, '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(ServingConfigServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "true"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "false"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_serving_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ServingConfigServiceClient, ServingConfigServiceAsyncClient +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +def test_serving_config_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_serving_config_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_serving_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_serving_config_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ServingConfigServiceClient( + 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", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_serving_config_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.CreateServingConfigRequest, + dict, +]) +def test_create_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_create_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.create_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + +@pytest.mark.asyncio +async def test_create_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.CreateServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_create_serving_config_async_from_dict(): + await test_create_serving_config_async(request_type=dict) + + +def test_create_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.CreateServingConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.CreateServingConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_serving_config( + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].serving_config + mock_val = gcr_serving_config.ServingConfig(name='name_value') + assert arg == mock_val + arg = args[0].serving_config_id + mock_val = 'serving_config_id_value' + assert arg == mock_val + + +def test_create_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.CreateServingConfigRequest(), + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_serving_config( + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].serving_config + mock_val = gcr_serving_config.ServingConfig(name='name_value') + assert arg == mock_val + arg = args[0].serving_config_id + mock_val = 'serving_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.CreateServingConfigRequest(), + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.DeleteServingConfigRequest, + dict, +]) +def test_delete_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.delete_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + +@pytest.mark.asyncio +async def test_delete_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.DeleteServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_serving_config_async_from_dict(): + await test_delete_serving_config_async(request_type=dict) + + +def test_delete_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.DeleteServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__call__') as call: + call.return_value = None + client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.DeleteServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__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_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.DeleteServingConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__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_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.DeleteServingConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.UpdateServingConfigRequest, + dict, +]) +def test_update_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_update_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.update_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + +@pytest.mark.asyncio +async def test_update_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.UpdateServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_update_serving_config_async_from_dict(): + await test_update_serving_config_async(request_type=dict) + + +def test_update_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.UpdateServingConfigRequest() + + request.serving_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.UpdateServingConfigRequest() + + request.serving_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config.name=name_value', + ) in kw['metadata'] + + +def test_update_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_serving_config( + serving_config=gcr_serving_config.ServingConfig(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].serving_config + mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_serving_config( + serving_config=gcr_serving_config.ServingConfig(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].serving_config + mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.GetServingConfigRequest, + dict, +]) +def test_get_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_get_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.get_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + +@pytest.mark.asyncio +async def test_get_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.GetServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_get_serving_config_async_from_dict(): + await test_get_serving_config_async(request_type=dict) + + +def test_get_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.GetServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + call.return_value = serving_config.ServingConfig() + client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.GetServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) + await client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.GetServingConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.GetServingConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.ListServingConfigsRequest, + dict, +]) +def test_list_serving_configs(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_serving_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_configs), + '__call__') as call: + client.list_serving_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + +@pytest.mark.asyncio +async def test_list_serving_configs_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.ListServingConfigsRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_serving_configs_async_from_dict(): + await test_list_serving_configs_async(request_type=dict) + + +def test_list_serving_configs_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.ListServingConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + call.return_value = serving_config_service.ListServingConfigsResponse() + client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_serving_configs_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.ListServingConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) + await client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_serving_configs_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_serving_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_serving_configs_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_serving_configs_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_serving_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_serving_configs_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent='parent_value', + ) + + +def test_list_serving_configs_pager(transport_name: str = "grpc"): + client = ServingConfigServiceClient( + 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_serving_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_serving_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, serving_config.ServingConfig) + for i in results) +def test_list_serving_configs_pages(transport_name: str = "grpc"): + client = ServingConfigServiceClient( + 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_serving_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_serving_configs(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_serving_configs_async_pager(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_serving_configs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, serving_config.ServingConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_serving_configs_async_pages(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_serving_configs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + serving_config_service.AddControlRequest, + dict, +]) +def test_add_control(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_add_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + client.add_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + +@pytest.mark.asyncio +async def test_add_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.AddControlRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_add_control_async_from_dict(): + await test_add_control_async(request_type=dict) + + +def test_add_control_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.AddControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_control_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.AddControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_add_control_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + + +def test_add_control_flattened_error(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_control( + serving_config_service.AddControlRequest(), + serving_config='serving_config_value', + ) + +@pytest.mark.asyncio +async def test_add_control_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_control_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_control( + serving_config_service.AddControlRequest(), + serving_config='serving_config_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.RemoveControlRequest, + dict, +]) +def test_remove_control(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_remove_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + client.remove_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + +@pytest.mark.asyncio +async def test_remove_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.RemoveControlRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_remove_control_async_from_dict(): + await test_remove_control_async(request_type=dict) + + +def test_remove_control_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.RemoveControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_control_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.RemoveControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_remove_control_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + + +def test_remove_control_flattened_error(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config='serving_config_value', + ) + +@pytest.mark.asyncio +async def test_remove_control_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_control_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config='serving_config_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServingConfigServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ServingConfigServiceClient.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 = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ServingConfigServiceGrpcTransport, + ) + +def test_serving_config_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ServingConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_serving_config_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ServingConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_serving_config', + 'delete_serving_config', + 'update_serving_config', + 'get_serving_config', + 'list_serving_configs', + 'add_control', + 'remove_control', + ) + 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_serving_config_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.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServingConfigServiceTransport( + 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_serving_config_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.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServingConfigServiceTransport() + adc.assert_called_once() + + +def test_serving_config_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) + ServingConfigServiceClient() + 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.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + ], +) +def test_serving_config_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.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + ], +) +def test_serving_config_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.ServingConfigServiceGrpcTransport, grpc_helpers), + (transports.ServingConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_serving_config_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_serving_config_service_host_no_port(transport_name): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_serving_config_service_host_with_port(transport_name): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_serving_config_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServingConfigServiceGrpcTransport( + 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_serving_config_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + 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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = ServingConfigServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = ServingConfigServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + serving_config = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, serving_config=serving_config, ) + actual = ServingConfigServiceClient.serving_config_path(project, location, catalog, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "serving_config": "clam", + } + path = ServingConfigServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ServingConfigServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ServingConfigServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ServingConfigServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ServingConfigServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ServingConfigServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ServingConfigServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ServingConfigServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ServingConfigServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.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 = ServingConfigServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ServingConfigServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.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.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ServingConfigServiceClient.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 = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ServingConfigServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ServingConfigServiceClient( + 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", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py new file mode 100644 index 00000000..ef8d7602 --- /dev/null +++ b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py @@ -0,0 +1,2038 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2alpha.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.retail_v2alpha.services.user_event_service import UserEventServiceClient +from google.cloud.retail_v2alpha.services.user_event_service import transports +from google.cloud.retail_v2alpha.types import common +from google.cloud.retail_v2alpha.types import import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import promotion +from google.cloud.retail_v2alpha.types import purge_config +from google.cloud.retail_v2alpha.types import user_event +from google.cloud.retail_v2alpha.types import user_event_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + ) + response = client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +def test_write_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) + await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeUserEventsRequest, + dict, +]) +def test_purge_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + client.purge_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + +@pytest.mark.asyncio +async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_user_events_async_from_dict(): + await test_purge_user_events_async(request_type=dict) + + +def test_purge_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_purge_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.RejoinUserEventsRequest, + dict, +]) +def test_rejoin_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_rejoin_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + client.rejoin_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + +@pytest.mark.asyncio +async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_rejoin_user_events_async_from_dict(): + await test_rejoin_user_events_async(request_type=dict) + + +def test_rejoin_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_rejoin_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'purge_user_events', + 'import_user_events', + 'rejoin_user_events', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_user_event_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_user_event_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +def test_user_event_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + UserEventServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = UserEventServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = UserEventServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_product_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + product = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + "branch": "whelk", + "product": "octopus", + } + path = UserEventServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/.coveragerc b/owl-bot-staging/v2beta/.coveragerc new file mode 100644 index 00000000..a8b114f0 --- /dev/null +++ b/owl-bot-staging/v2beta/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/retail/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2beta/.flake8 b/owl-bot-staging/v2beta/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v2beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v2beta/MANIFEST.in b/owl-bot-staging/v2beta/MANIFEST.in new file mode 100644 index 00000000..43074617 --- /dev/null +++ b/owl-bot-staging/v2beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/retail *.py +recursive-include google/cloud/retail_v2beta *.py diff --git a/owl-bot-staging/v2beta/README.rst b/owl-bot-staging/v2beta/README.rst new file mode 100644 index 00000000..cb039760 --- /dev/null +++ b/owl-bot-staging/v2beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Retail API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Retail API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2beta/docs/conf.py b/owl-bot-staging/v2beta/docs/conf.py new file mode 100644 index 00000000..5be9eb4b --- /dev/null +++ b/owl-bot-staging/v2beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-retail documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-retail" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-retail-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-retail.tex", + u"google-cloud-retail Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-retail", + u"Google Cloud Retail Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-retail", + u"google-cloud-retail Documentation", + author, + "google-cloud-retail", + "GAPIC library for Google Cloud Retail API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v2beta/docs/index.rst b/owl-bot-staging/v2beta/docs/index.rst new file mode 100644 index 00000000..fd60fc85 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + retail_v2beta/services + retail_v2beta/types diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst new file mode 100644 index 00000000..3a7c19e6 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst @@ -0,0 +1,10 @@ +CatalogService +-------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.catalog_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.catalog_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst new file mode 100644 index 00000000..1f6782ed --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst @@ -0,0 +1,6 @@ +CompletionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.completion_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst new file mode 100644 index 00000000..86cfcba1 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst @@ -0,0 +1,10 @@ +ControlService +-------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.control_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.control_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst new file mode 100644 index 00000000..903c951d --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst @@ -0,0 +1,6 @@ +PredictionService +----------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.prediction_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst new file mode 100644 index 00000000..489daa22 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst @@ -0,0 +1,10 @@ +ProductService +-------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.product_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.product_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst new file mode 100644 index 00000000..591f5c86 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst @@ -0,0 +1,10 @@ +SearchService +------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst new file mode 100644 index 00000000..04251720 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst @@ -0,0 +1,13 @@ +Services for Google Cloud Retail v2beta API +=========================================== +.. toctree:: + :maxdepth: 2 + + catalog_service + completion_service + control_service + prediction_service + product_service + search_service + serving_config_service + user_event_service diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst new file mode 100644 index 00000000..c074749c --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst @@ -0,0 +1,10 @@ +ServingConfigService +-------------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.serving_config_service + :members: + :inherited-members: + +.. automodule:: google.cloud.retail_v2beta.services.serving_config_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst new file mode 100644 index 00000000..ae17ce43 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Retail v2beta API +======================================== + +.. automodule:: google.cloud.retail_v2beta.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst new file mode 100644 index 00000000..11ab3794 --- /dev/null +++ b/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst @@ -0,0 +1,6 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.retail_v2beta.services.user_event_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta/google/cloud/retail/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail/__init__.py new file mode 100644 index 00000000..07f795e3 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail/__init__.py @@ -0,0 +1,275 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.retail_v2beta.services.catalog_service.client import CatalogServiceClient +from google.cloud.retail_v2beta.services.catalog_service.async_client import CatalogServiceAsyncClient +from google.cloud.retail_v2beta.services.completion_service.client import CompletionServiceClient +from google.cloud.retail_v2beta.services.completion_service.async_client import CompletionServiceAsyncClient +from google.cloud.retail_v2beta.services.control_service.client import ControlServiceClient +from google.cloud.retail_v2beta.services.control_service.async_client import ControlServiceAsyncClient +from google.cloud.retail_v2beta.services.prediction_service.client import PredictionServiceClient +from google.cloud.retail_v2beta.services.prediction_service.async_client import PredictionServiceAsyncClient +from google.cloud.retail_v2beta.services.product_service.client import ProductServiceClient +from google.cloud.retail_v2beta.services.product_service.async_client import ProductServiceAsyncClient +from google.cloud.retail_v2beta.services.search_service.client import SearchServiceClient +from google.cloud.retail_v2beta.services.search_service.async_client import SearchServiceAsyncClient +from google.cloud.retail_v2beta.services.serving_config_service.client import ServingConfigServiceClient +from google.cloud.retail_v2beta.services.serving_config_service.async_client import ServingConfigServiceAsyncClient +from google.cloud.retail_v2beta.services.user_event_service.client import UserEventServiceClient +from google.cloud.retail_v2beta.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.retail_v2beta.types.catalog import AttributesConfig +from google.cloud.retail_v2beta.types.catalog import Catalog +from google.cloud.retail_v2beta.types.catalog import CatalogAttribute +from google.cloud.retail_v2beta.types.catalog import CompletionConfig +from google.cloud.retail_v2beta.types.catalog import MerchantCenterLink +from google.cloud.retail_v2beta.types.catalog import MerchantCenterLinkingConfig +from google.cloud.retail_v2beta.types.catalog import ProductLevelConfig +from google.cloud.retail_v2beta.types.catalog_service import AddCatalogAttributeRequest +from google.cloud.retail_v2beta.types.catalog_service import GetAttributesConfigRequest +from google.cloud.retail_v2beta.types.catalog_service import GetCompletionConfigRequest +from google.cloud.retail_v2beta.types.catalog_service import GetDefaultBranchRequest +from google.cloud.retail_v2beta.types.catalog_service import GetDefaultBranchResponse +from google.cloud.retail_v2beta.types.catalog_service import ListCatalogsRequest +from google.cloud.retail_v2beta.types.catalog_service import ListCatalogsResponse +from google.cloud.retail_v2beta.types.catalog_service import RemoveCatalogAttributeRequest +from google.cloud.retail_v2beta.types.catalog_service import ReplaceCatalogAttributeRequest +from google.cloud.retail_v2beta.types.catalog_service import SetDefaultBranchRequest +from google.cloud.retail_v2beta.types.catalog_service import UpdateAttributesConfigRequest +from google.cloud.retail_v2beta.types.catalog_service import UpdateCatalogRequest +from google.cloud.retail_v2beta.types.catalog_service import UpdateCompletionConfigRequest +from google.cloud.retail_v2beta.types.common import Audience +from google.cloud.retail_v2beta.types.common import ColorInfo +from google.cloud.retail_v2beta.types.common import Condition +from google.cloud.retail_v2beta.types.common import CustomAttribute +from google.cloud.retail_v2beta.types.common import FulfillmentInfo +from google.cloud.retail_v2beta.types.common import Image +from google.cloud.retail_v2beta.types.common import Interval +from google.cloud.retail_v2beta.types.common import LocalInventory +from google.cloud.retail_v2beta.types.common import PriceInfo +from google.cloud.retail_v2beta.types.common import Rating +from google.cloud.retail_v2beta.types.common import Rule +from google.cloud.retail_v2beta.types.common import UserInfo +from google.cloud.retail_v2beta.types.common import AttributeConfigLevel +from google.cloud.retail_v2beta.types.common import SearchSolutionUseCase +from google.cloud.retail_v2beta.types.common import SolutionType +from google.cloud.retail_v2beta.types.completion_service import CompleteQueryRequest +from google.cloud.retail_v2beta.types.completion_service import CompleteQueryResponse +from google.cloud.retail_v2beta.types.control import Control +from google.cloud.retail_v2beta.types.control_service import CreateControlRequest +from google.cloud.retail_v2beta.types.control_service import DeleteControlRequest +from google.cloud.retail_v2beta.types.control_service import GetControlRequest +from google.cloud.retail_v2beta.types.control_service import ListControlsRequest +from google.cloud.retail_v2beta.types.control_service import ListControlsResponse +from google.cloud.retail_v2beta.types.control_service import UpdateControlRequest +from google.cloud.retail_v2beta.types.export_config import ExportErrorsConfig +from google.cloud.retail_v2beta.types.export_config import ExportMetadata +from google.cloud.retail_v2beta.types.export_config import ExportProductsResponse +from google.cloud.retail_v2beta.types.export_config import ExportUserEventsResponse +from google.cloud.retail_v2beta.types.import_config import BigQuerySource +from google.cloud.retail_v2beta.types.import_config import CompletionDataInputConfig +from google.cloud.retail_v2beta.types.import_config import GcsSource +from google.cloud.retail_v2beta.types.import_config import ImportCompletionDataRequest +from google.cloud.retail_v2beta.types.import_config import ImportCompletionDataResponse +from google.cloud.retail_v2beta.types.import_config import ImportErrorsConfig +from google.cloud.retail_v2beta.types.import_config import ImportMetadata +from google.cloud.retail_v2beta.types.import_config import ImportProductsRequest +from google.cloud.retail_v2beta.types.import_config import ImportProductsResponse +from google.cloud.retail_v2beta.types.import_config import ImportUserEventsRequest +from google.cloud.retail_v2beta.types.import_config import ImportUserEventsResponse +from google.cloud.retail_v2beta.types.import_config import ProductInlineSource +from google.cloud.retail_v2beta.types.import_config import ProductInputConfig +from google.cloud.retail_v2beta.types.import_config import UserEventImportSummary +from google.cloud.retail_v2beta.types.import_config import UserEventInlineSource +from google.cloud.retail_v2beta.types.import_config import UserEventInputConfig +from google.cloud.retail_v2beta.types.prediction_service import PredictRequest +from google.cloud.retail_v2beta.types.prediction_service import PredictResponse +from google.cloud.retail_v2beta.types.product import Product +from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesMetadata +from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesRequest +from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesResponse +from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesMetadata +from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesRequest +from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesResponse +from google.cloud.retail_v2beta.types.product_service import CreateProductRequest +from google.cloud.retail_v2beta.types.product_service import DeleteProductRequest +from google.cloud.retail_v2beta.types.product_service import GetProductRequest +from google.cloud.retail_v2beta.types.product_service import ListProductsRequest +from google.cloud.retail_v2beta.types.product_service import ListProductsResponse +from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesMetadata +from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesRequest +from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesResponse +from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesMetadata +from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesRequest +from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesResponse +from google.cloud.retail_v2beta.types.product_service import SetInventoryMetadata +from google.cloud.retail_v2beta.types.product_service import SetInventoryRequest +from google.cloud.retail_v2beta.types.product_service import SetInventoryResponse +from google.cloud.retail_v2beta.types.product_service import UpdateProductRequest +from google.cloud.retail_v2beta.types.promotion import Promotion +from google.cloud.retail_v2beta.types.purge_config import PurgeMetadata +from google.cloud.retail_v2beta.types.purge_config import PurgeUserEventsRequest +from google.cloud.retail_v2beta.types.purge_config import PurgeUserEventsResponse +from google.cloud.retail_v2beta.types.search_service import SearchRequest +from google.cloud.retail_v2beta.types.search_service import SearchResponse +from google.cloud.retail_v2beta.types.serving_config import ServingConfig +from google.cloud.retail_v2beta.types.serving_config_service import AddControlRequest +from google.cloud.retail_v2beta.types.serving_config_service import CreateServingConfigRequest +from google.cloud.retail_v2beta.types.serving_config_service import DeleteServingConfigRequest +from google.cloud.retail_v2beta.types.serving_config_service import GetServingConfigRequest +from google.cloud.retail_v2beta.types.serving_config_service import ListServingConfigsRequest +from google.cloud.retail_v2beta.types.serving_config_service import ListServingConfigsResponse +from google.cloud.retail_v2beta.types.serving_config_service import RemoveControlRequest +from google.cloud.retail_v2beta.types.serving_config_service import UpdateServingConfigRequest +from google.cloud.retail_v2beta.types.user_event import CompletionDetail +from google.cloud.retail_v2beta.types.user_event import ProductDetail +from google.cloud.retail_v2beta.types.user_event import PurchaseTransaction +from google.cloud.retail_v2beta.types.user_event import UserEvent +from google.cloud.retail_v2beta.types.user_event_service import CollectUserEventRequest +from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsMetadata +from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsRequest +from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsResponse +from google.cloud.retail_v2beta.types.user_event_service import WriteUserEventRequest + +__all__ = ('CatalogServiceClient', + 'CatalogServiceAsyncClient', + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', + 'ControlServiceClient', + 'ControlServiceAsyncClient', + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', + 'ProductServiceClient', + 'ProductServiceAsyncClient', + 'SearchServiceClient', + 'SearchServiceAsyncClient', + 'ServingConfigServiceClient', + 'ServingConfigServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'AttributesConfig', + 'Catalog', + 'CatalogAttribute', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'ProductLevelConfig', + 'AddCatalogAttributeRequest', + 'GetAttributesConfigRequest', + 'GetCompletionConfigRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + 'SetDefaultBranchRequest', + 'UpdateAttributesConfigRequest', + 'UpdateCatalogRequest', + 'UpdateCompletionConfigRequest', + 'Audience', + 'ColorInfo', + 'Condition', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'Rule', + 'UserInfo', + 'AttributeConfigLevel', + 'SearchSolutionUseCase', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Control', + 'CreateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + 'UpdateControlRequest', + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'ServingConfig', + 'AddControlRequest', + 'CreateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'RemoveControlRequest', + 'UpdateServingConfigRequest', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail/py.typed b/owl-bot-staging/v2beta/google/cloud/retail/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py new file mode 100644 index 00000000..3ad83ab4 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.catalog_service import CatalogServiceClient +from .services.catalog_service import CatalogServiceAsyncClient +from .services.completion_service import CompletionServiceClient +from .services.completion_service import CompletionServiceAsyncClient +from .services.control_service import ControlServiceClient +from .services.control_service import ControlServiceAsyncClient +from .services.prediction_service import PredictionServiceClient +from .services.prediction_service import PredictionServiceAsyncClient +from .services.product_service import ProductServiceClient +from .services.product_service import ProductServiceAsyncClient +from .services.search_service import SearchServiceClient +from .services.search_service import SearchServiceAsyncClient +from .services.serving_config_service import ServingConfigServiceClient +from .services.serving_config_service import ServingConfigServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.catalog import AttributesConfig +from .types.catalog import Catalog +from .types.catalog import CatalogAttribute +from .types.catalog import CompletionConfig +from .types.catalog import MerchantCenterLink +from .types.catalog import MerchantCenterLinkingConfig +from .types.catalog import ProductLevelConfig +from .types.catalog_service import AddCatalogAttributeRequest +from .types.catalog_service import GetAttributesConfigRequest +from .types.catalog_service import GetCompletionConfigRequest +from .types.catalog_service import GetDefaultBranchRequest +from .types.catalog_service import GetDefaultBranchResponse +from .types.catalog_service import ListCatalogsRequest +from .types.catalog_service import ListCatalogsResponse +from .types.catalog_service import RemoveCatalogAttributeRequest +from .types.catalog_service import ReplaceCatalogAttributeRequest +from .types.catalog_service import SetDefaultBranchRequest +from .types.catalog_service import UpdateAttributesConfigRequest +from .types.catalog_service import UpdateCatalogRequest +from .types.catalog_service import UpdateCompletionConfigRequest +from .types.common import Audience +from .types.common import ColorInfo +from .types.common import Condition +from .types.common import CustomAttribute +from .types.common import FulfillmentInfo +from .types.common import Image +from .types.common import Interval +from .types.common import LocalInventory +from .types.common import PriceInfo +from .types.common import Rating +from .types.common import Rule +from .types.common import UserInfo +from .types.common import AttributeConfigLevel +from .types.common import SearchSolutionUseCase +from .types.common import SolutionType +from .types.completion_service import CompleteQueryRequest +from .types.completion_service import CompleteQueryResponse +from .types.control import Control +from .types.control_service import CreateControlRequest +from .types.control_service import DeleteControlRequest +from .types.control_service import GetControlRequest +from .types.control_service import ListControlsRequest +from .types.control_service import ListControlsResponse +from .types.control_service import UpdateControlRequest +from .types.export_config import ExportErrorsConfig +from .types.export_config import ExportMetadata +from .types.export_config import ExportProductsResponse +from .types.export_config import ExportUserEventsResponse +from .types.import_config import BigQuerySource +from .types.import_config import CompletionDataInputConfig +from .types.import_config import GcsSource +from .types.import_config import ImportCompletionDataRequest +from .types.import_config import ImportCompletionDataResponse +from .types.import_config import ImportErrorsConfig +from .types.import_config import ImportMetadata +from .types.import_config import ImportProductsRequest +from .types.import_config import ImportProductsResponse +from .types.import_config import ImportUserEventsRequest +from .types.import_config import ImportUserEventsResponse +from .types.import_config import ProductInlineSource +from .types.import_config import ProductInputConfig +from .types.import_config import UserEventImportSummary +from .types.import_config import UserEventInlineSource +from .types.import_config import UserEventInputConfig +from .types.prediction_service import PredictRequest +from .types.prediction_service import PredictResponse +from .types.product import Product +from .types.product_service import AddFulfillmentPlacesMetadata +from .types.product_service import AddFulfillmentPlacesRequest +from .types.product_service import AddFulfillmentPlacesResponse +from .types.product_service import AddLocalInventoriesMetadata +from .types.product_service import AddLocalInventoriesRequest +from .types.product_service import AddLocalInventoriesResponse +from .types.product_service import CreateProductRequest +from .types.product_service import DeleteProductRequest +from .types.product_service import GetProductRequest +from .types.product_service import ListProductsRequest +from .types.product_service import ListProductsResponse +from .types.product_service import RemoveFulfillmentPlacesMetadata +from .types.product_service import RemoveFulfillmentPlacesRequest +from .types.product_service import RemoveFulfillmentPlacesResponse +from .types.product_service import RemoveLocalInventoriesMetadata +from .types.product_service import RemoveLocalInventoriesRequest +from .types.product_service import RemoveLocalInventoriesResponse +from .types.product_service import SetInventoryMetadata +from .types.product_service import SetInventoryRequest +from .types.product_service import SetInventoryResponse +from .types.product_service import UpdateProductRequest +from .types.promotion import Promotion +from .types.purge_config import PurgeMetadata +from .types.purge_config import PurgeUserEventsRequest +from .types.purge_config import PurgeUserEventsResponse +from .types.search_service import SearchRequest +from .types.search_service import SearchResponse +from .types.serving_config import ServingConfig +from .types.serving_config_service import AddControlRequest +from .types.serving_config_service import CreateServingConfigRequest +from .types.serving_config_service import DeleteServingConfigRequest +from .types.serving_config_service import GetServingConfigRequest +from .types.serving_config_service import ListServingConfigsRequest +from .types.serving_config_service import ListServingConfigsResponse +from .types.serving_config_service import RemoveControlRequest +from .types.serving_config_service import UpdateServingConfigRequest +from .types.user_event import CompletionDetail +from .types.user_event import ProductDetail +from .types.user_event import PurchaseTransaction +from .types.user_event import UserEvent +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import RejoinUserEventsMetadata +from .types.user_event_service import RejoinUserEventsRequest +from .types.user_event_service import RejoinUserEventsResponse +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CatalogServiceAsyncClient', + 'CompletionServiceAsyncClient', + 'ControlServiceAsyncClient', + 'PredictionServiceAsyncClient', + 'ProductServiceAsyncClient', + 'SearchServiceAsyncClient', + 'ServingConfigServiceAsyncClient', + 'UserEventServiceAsyncClient', +'AddCatalogAttributeRequest', +'AddControlRequest', +'AddFulfillmentPlacesMetadata', +'AddFulfillmentPlacesRequest', +'AddFulfillmentPlacesResponse', +'AddLocalInventoriesMetadata', +'AddLocalInventoriesRequest', +'AddLocalInventoriesResponse', +'AttributeConfigLevel', +'AttributesConfig', +'Audience', +'BigQuerySource', +'Catalog', +'CatalogAttribute', +'CatalogServiceClient', +'CollectUserEventRequest', +'ColorInfo', +'CompleteQueryRequest', +'CompleteQueryResponse', +'CompletionConfig', +'CompletionDataInputConfig', +'CompletionDetail', +'CompletionServiceClient', +'Condition', +'Control', +'ControlServiceClient', +'CreateControlRequest', +'CreateProductRequest', +'CreateServingConfigRequest', +'CustomAttribute', +'DeleteControlRequest', +'DeleteProductRequest', +'DeleteServingConfigRequest', +'ExportErrorsConfig', +'ExportMetadata', +'ExportProductsResponse', +'ExportUserEventsResponse', +'FulfillmentInfo', +'GcsSource', +'GetAttributesConfigRequest', +'GetCompletionConfigRequest', +'GetControlRequest', +'GetDefaultBranchRequest', +'GetDefaultBranchResponse', +'GetProductRequest', +'GetServingConfigRequest', +'Image', +'ImportCompletionDataRequest', +'ImportCompletionDataResponse', +'ImportErrorsConfig', +'ImportMetadata', +'ImportProductsRequest', +'ImportProductsResponse', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'Interval', +'ListCatalogsRequest', +'ListCatalogsResponse', +'ListControlsRequest', +'ListControlsResponse', +'ListProductsRequest', +'ListProductsResponse', +'ListServingConfigsRequest', +'ListServingConfigsResponse', +'LocalInventory', +'MerchantCenterLink', +'MerchantCenterLinkingConfig', +'PredictRequest', +'PredictResponse', +'PredictionServiceClient', +'PriceInfo', +'Product', +'ProductDetail', +'ProductInlineSource', +'ProductInputConfig', +'ProductLevelConfig', +'ProductServiceClient', +'Promotion', +'PurchaseTransaction', +'PurgeMetadata', +'PurgeUserEventsRequest', +'PurgeUserEventsResponse', +'Rating', +'RejoinUserEventsMetadata', +'RejoinUserEventsRequest', +'RejoinUserEventsResponse', +'RemoveCatalogAttributeRequest', +'RemoveControlRequest', +'RemoveFulfillmentPlacesMetadata', +'RemoveFulfillmentPlacesRequest', +'RemoveFulfillmentPlacesResponse', +'RemoveLocalInventoriesMetadata', +'RemoveLocalInventoriesRequest', +'RemoveLocalInventoriesResponse', +'ReplaceCatalogAttributeRequest', +'Rule', +'SearchRequest', +'SearchResponse', +'SearchServiceClient', +'SearchSolutionUseCase', +'ServingConfig', +'ServingConfigServiceClient', +'SetDefaultBranchRequest', +'SetInventoryMetadata', +'SetInventoryRequest', +'SetInventoryResponse', +'SolutionType', +'UpdateAttributesConfigRequest', +'UpdateCatalogRequest', +'UpdateCompletionConfigRequest', +'UpdateControlRequest', +'UpdateProductRequest', +'UpdateServingConfigRequest', +'UserEvent', +'UserEventImportSummary', +'UserEventInlineSource', +'UserEventInputConfig', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json new file mode 100644 index 00000000..bf3205b9 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json @@ -0,0 +1,551 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.retail_v2beta", + "protoPackage": "google.cloud.retail.v2beta", + "schema": "1.0", + "services": { + "CatalogService": { + "clients": { + "grpc": { + "libraryClient": "CatalogServiceClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "add_catalog_attribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "get_attributes_config" + ] + }, + "GetCompletionConfig": { + "methods": [ + "get_completion_config" + ] + }, + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "remove_catalog_attribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "replace_catalog_attribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "update_attributes_config" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "update_completion_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CatalogServiceAsyncClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "add_catalog_attribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "get_attributes_config" + ] + }, + "GetCompletionConfig": { + "methods": [ + "get_completion_config" + ] + }, + "GetDefaultBranch": { + "methods": [ + "get_default_branch" + ] + }, + "ListCatalogs": { + "methods": [ + "list_catalogs" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "remove_catalog_attribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "replace_catalog_attribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "set_default_branch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "update_attributes_config" + ] + }, + "UpdateCatalog": { + "methods": [ + "update_catalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "update_completion_config" + ] + } + } + } + } + }, + "CompletionService": { + "clients": { + "grpc": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CompletionServiceAsyncClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + }, + "ImportCompletionData": { + "methods": [ + "import_completion_data" + ] + } + } + } + } + }, + "ControlService": { + "clients": { + "grpc": { + "libraryClient": "ControlServiceClient", + "rpcs": { + "CreateControl": { + "methods": [ + "create_control" + ] + }, + "DeleteControl": { + "methods": [ + "delete_control" + ] + }, + "GetControl": { + "methods": [ + "get_control" + ] + }, + "ListControls": { + "methods": [ + "list_controls" + ] + }, + "UpdateControl": { + "methods": [ + "update_control" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ControlServiceAsyncClient", + "rpcs": { + "CreateControl": { + "methods": [ + "create_control" + ] + }, + "DeleteControl": { + "methods": [ + "delete_control" + ] + }, + "GetControl": { + "methods": [ + "get_control" + ] + }, + "ListControls": { + "methods": [ + "list_controls" + ] + }, + "UpdateControl": { + "methods": [ + "update_control" + ] + } + } + } + } + }, + "PredictionService": { + "clients": { + "grpc": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionServiceAsyncClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + } + } + }, + "ProductService": { + "clients": { + "grpc": { + "libraryClient": "ProductServiceClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductServiceAsyncClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "add_fulfillment_places" + ] + }, + "AddLocalInventories": { + "methods": [ + "add_local_inventories" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ImportProducts": { + "methods": [ + "import_products" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "remove_fulfillment_places" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "remove_local_inventories" + ] + }, + "SetInventory": { + "methods": [ + "set_inventory" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + } + } + } + } + }, + "SearchService": { + "clients": { + "grpc": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SearchServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + }, + "ServingConfigService": { + "clients": { + "grpc": { + "libraryClient": "ServingConfigServiceClient", + "rpcs": { + "AddControl": { + "methods": [ + "add_control" + ] + }, + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, + "RemoveControl": { + "methods": [ + "remove_control" + ] + }, + "UpdateServingConfig": { + "methods": [ + "update_serving_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServingConfigServiceAsyncClient", + "rpcs": { + "AddControl": { + "methods": [ + "add_control" + ] + }, + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, + "RemoveControl": { + "methods": [ + "remove_control" + ] + }, + "UpdateServingConfig": { + "methods": [ + "update_serving_config" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "RejoinUserEvents": { + "methods": [ + "rejoin_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed new file mode 100644 index 00000000..fda82836 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py new file mode 100644 index 00000000..d276b897 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CatalogServiceClient +from .async_client import CatalogServiceAsyncClient + +__all__ = ( + 'CatalogServiceClient', + 'CatalogServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py new file mode 100644 index 00000000..dfff033b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py @@ -0,0 +1,1350 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.catalog_service import pagers +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport +from .client import CatalogServiceClient + + +class CatalogServiceAsyncClient: + """Service for managing catalog configuration.""" + + _client: CatalogServiceClient + + DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT + + attributes_config_path = staticmethod(CatalogServiceClient.attributes_config_path) + parse_attributes_config_path = staticmethod(CatalogServiceClient.parse_attributes_config_path) + branch_path = staticmethod(CatalogServiceClient.branch_path) + parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) + catalog_path = staticmethod(CatalogServiceClient.catalog_path) + parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) + completion_config_path = staticmethod(CatalogServiceClient.completion_config_path) + parse_completion_config_path = staticmethod(CatalogServiceClient.parse_completion_config_path) + common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CatalogServiceClient.common_project_path) + parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) + common_location_path = staticmethod(CatalogServiceClient.common_location_path) + parse_common_location_path = staticmethod(CatalogServiceClient.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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CatalogServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsAsyncPager: + r"""Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_list_catalogs(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + parent (:class:`str`): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2beta.Catalog]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.retail_v2beta.services.catalog_service.pagers.ListCatalogsAsyncPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.ListCatalogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_catalogs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCatalogsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_catalog(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2beta.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2beta.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] + method. + catalog (:class:`google.cloud.retail_v2beta.types.Catalog`): + Required. The + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2beta.Catalog], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Catalog][google.cloud.retail.v2beta.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_catalog, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_set_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (:class:`str`): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.SetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (:class:`str`): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetDefaultBranchRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # 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_default_branch, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_completion_config(self, + request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Gets a + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] + method. + name (:class:`str`): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + + 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.retail_v2beta.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetCompletionConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_completion_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_completion_config(self, + request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, + *, + completion_config: catalog.CompletionConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Updates the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + completion_config = retail_v2beta.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2beta.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = await client.update_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] + method. + completion_config (:class:`google.cloud.retail_v2beta.types.CompletionConfig`): + Required. The + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``completion_config`` 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 + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([completion_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCompletionConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if completion_config is not None: + request.completion_config = completion_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_completion_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("completion_config.name", request.completion_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_attributes_config(self, + request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Gets an + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] + method. + name (:class:`str`): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + + 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.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetAttributesConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_attributes_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_attributes_config(self, + request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, + *, + attributes_config: catalog.AttributesConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Updates the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + attributes_config = retail_v2beta.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2beta.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = await client.update_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] + method. + attributes_config (:class:`google.cloud.retail_v2beta.types.AttributesConfig`): + Required. The + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. + + This corresponds to the ``attributes_config`` 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 + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attributes_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateAttributesConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attributes_config is not None: + request.attributes_config = attributes_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_attributes_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config.name", request.attributes_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_catalog_attribute(self, + request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Adds the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_add_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.AddCatalogAttributeRequest(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.add_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_catalog_attribute(self, + request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Removes the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = await client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.RemoveCatalogAttributeRequest(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.remove_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def replace_catalog_attribute(self, + request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Replaces the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + request = catalog_service.ReplaceCatalogAttributeRequest(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.replace_catalog_attribute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py new file mode 100644 index 00000000..c95200de --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py @@ -0,0 +1,1580 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.catalog_service import pagers +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CatalogServiceGrpcTransport +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +class CatalogServiceClientMeta(type): + """Metaclass for the CatalogService 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[CatalogServiceTransport]] + _transport_registry["grpc"] = CatalogServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CatalogServiceTransport]: + """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): + """Service for managing catalog configuration.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CatalogServiceClient: 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: + CatalogServiceClient: 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) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def attributes_config_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified attributes_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_attributes_config_path(path: str) -> Dict[str,str]: + """Parses a attributes_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/attributesConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def completion_config_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified completion_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_completion_config_path(path: str) -> Dict[str,str]: + """Parses a completion_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/completionConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CatalogServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CatalogServiceTransport): + # transport is a CatalogServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_catalogs(self, + request: Union[catalog_service.ListCatalogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogsPager: + r"""Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s + associated with the project. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_list_catalogs(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListCatalogsRequest, dict]): + The request object. Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2beta.Catalog]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.retail_v2beta.services.catalog_service.pagers.ListCatalogsPager: + Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ListCatalogsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ListCatalogsRequest): + request = catalog_service.ListCatalogsRequest(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_catalogs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCatalogsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_catalog(self, + request: Union[catalog_service.UpdateCatalogRequest, dict] = None, + *, + catalog: gcr_catalog.Catalog = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_catalog.Catalog: + r"""Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_catalog(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2beta.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2beta.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateCatalogRequest, dict]): + The request object. Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] + method. + catalog (google.cloud.retail_v2beta.types.Catalog): + Required. The + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2beta.Catalog], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Catalog][google.cloud.retail.v2beta.Catalog] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``catalog`` 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 + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Catalog: + The catalog configuration. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCatalogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCatalogRequest): + request = catalog_service.UpdateCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + 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_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog.name", request.catalog.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_default_branch(self, + request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_set_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.SetDefaultBranchRequest, dict]): + The request object. Request message to set a specified + branch as new default_branch. + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.SetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.SetDefaultBranchRequest): + request = catalog_service.SetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_default_branch(self, + request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, + *, + catalog: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog_service.GetDefaultBranchResponse: + r"""Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetDefaultBranchRequest, dict]): + The request object. Request message to show which branch + is currently the default branch. + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.GetDefaultBranchResponse: + Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([catalog]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetDefaultBranchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetDefaultBranchRequest): + request = catalog_service.GetDefaultBranchRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if catalog is not None: + request.catalog = catalog + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_default_branch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_completion_config(self, + request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Gets a + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] + method. + name (str): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + + 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.retail_v2beta.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetCompletionConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetCompletionConfigRequest): + request = catalog_service.GetCompletionConfigRequest(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_completion_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_completion_config(self, + request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, + *, + completion_config: catalog.CompletionConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CompletionConfig: + r"""Updates the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + completion_config = retail_v2beta.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2beta.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = client.update_completion_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] + method. + completion_config (google.cloud.retail_v2beta.types.CompletionConfig): + Required. The + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``completion_config`` 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 + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.CompletionConfig: + Catalog level autocomplete config for + customers to customize autocomplete + feature's settings. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([completion_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCompletionConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCompletionConfigRequest): + request = catalog_service.UpdateCompletionConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if completion_config is not None: + request.completion_config = completion_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_completion_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("completion_config.name", request.completion_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_attributes_config(self, + request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Gets an + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] + method. + name (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + + 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.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetAttributesConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetAttributesConfigRequest): + request = catalog_service.GetAttributesConfigRequest(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_attributes_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_attributes_config(self, + request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, + *, + attributes_config: catalog.AttributesConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Updates the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + attributes_config = retail_v2beta.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2beta.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = client.update_attributes_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest, dict]): + The request object. Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] + method. + attributes_config (google.cloud.retail_v2beta.types.AttributesConfig): + Required. The + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. + + This corresponds to the ``attributes_config`` 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 + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attributes_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateAttributesConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateAttributesConfigRequest): + request = catalog_service.UpdateAttributesConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attributes_config is not None: + request.attributes_config = attributes_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_attributes_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config.name", request.attributes_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_catalog_attribute(self, + request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Adds the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_add_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.AddCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.AddCatalogAttributeRequest): + request = catalog_service.AddCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_catalog_attribute(self, + request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Removes the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.RemoveCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.RemoveCatalogAttributeRequest): + request = catalog_service.RemoveCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def replace_catalog_attribute(self, + request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.AttributesConfig: + r"""Replaces the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest, dict]): + The request object. Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.AttributesConfig: + Catalog level attribute config. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ReplaceCatalogAttributeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ReplaceCatalogAttributeRequest): + request = catalog_service.ReplaceCatalogAttributeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.replace_catalog_attribute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attributes_config", request.attributes_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py new file mode 100644 index 00000000..0ca25546 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog_service + + +class ListCatalogsPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` + 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[..., catalog_service.ListCatalogsResponse], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2beta.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + for page in self.pages: + yield from page.catalogs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCatalogsAsyncPager: + """A pager for iterating through ``list_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` + 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[catalog_service.ListCatalogsResponse]], + request: catalog_service.ListCatalogsRequest, + response: catalog_service.ListCatalogsResponse, + *, + 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.retail_v2beta.types.ListCatalogsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListCatalogsResponse): + 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 = catalog_service.ListCatalogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: + 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[catalog.Catalog]: + async def async_generator(): + async for page in self.pages: + for response in page.catalogs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py new file mode 100644 index 00000000..0cffa336 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 CatalogServiceTransport +from .grpc import CatalogServiceGrpcTransport +from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] +_transport_registry['grpc'] = CatalogServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport + +__all__ = ( + 'CatalogServiceTransport', + 'CatalogServiceGrpcTransport', + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py new file mode 100644 index 00000000..90964f49 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py @@ -0,0 +1,297 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CatalogServiceTransport(abc.ABC): + """Abstract transport class for CatalogService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_catalogs: gapic_v1.method.wrap_method( + self.list_catalogs, + default_timeout=None, + client_info=client_info, + ), + self.update_catalog: gapic_v1.method.wrap_method( + self.update_catalog, + default_timeout=None, + client_info=client_info, + ), + self.set_default_branch: gapic_v1.method.wrap_method( + self.set_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_default_branch: gapic_v1.method.wrap_method( + self.get_default_branch, + default_timeout=None, + client_info=client_info, + ), + self.get_completion_config: gapic_v1.method.wrap_method( + self.get_completion_config, + default_timeout=None, + client_info=client_info, + ), + self.update_completion_config: gapic_v1.method.wrap_method( + self.update_completion_config, + default_timeout=None, + client_info=client_info, + ), + self.get_attributes_config: gapic_v1.method.wrap_method( + self.get_attributes_config, + default_timeout=None, + client_info=client_info, + ), + self.update_attributes_config: gapic_v1.method.wrap_method( + self.update_attributes_config, + default_timeout=None, + client_info=client_info, + ), + self.add_catalog_attribute: gapic_v1.method.wrap_method( + self.add_catalog_attribute, + default_timeout=None, + client_info=client_info, + ), + self.remove_catalog_attribute: gapic_v1.method.wrap_method( + self.remove_catalog_attribute, + default_timeout=None, + client_info=client_info, + ), + self.replace_catalog_attribute: gapic_v1.method.wrap_method( + self.replace_catalog_attribute, + 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Union[ + catalog_service.ListCatalogsResponse, + Awaitable[catalog_service.ListCatalogsResponse] + ]]: + raise NotImplementedError() + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Union[ + gcr_catalog.Catalog, + Awaitable[gcr_catalog.Catalog] + ]]: + raise NotImplementedError() + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Union[ + catalog_service.GetDefaultBranchResponse, + Awaitable[catalog_service.GetDefaultBranchResponse] + ]]: + raise NotImplementedError() + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + Union[ + catalog.CompletionConfig, + Awaitable[catalog.CompletionConfig] + ]]: + raise NotImplementedError() + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + Union[ + catalog.CompletionConfig, + Awaitable[catalog.CompletionConfig] + ]]: + raise NotImplementedError() + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + Union[ + catalog.AttributesConfig, + Awaitable[catalog.AttributesConfig] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CatalogServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py new file mode 100644 index 00000000..9ae369d1 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py @@ -0,0 +1,600 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO + + +class CatalogServiceGrpcTransport(CatalogServiceTransport): + """gRPC backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + catalog_service.ListCatalogsResponse]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + ~.ListCatalogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + gcr_catalog.Catalog]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + ~.Catalog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + empty_pb2.Empty]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + ~.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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + catalog_service.GetDefaultBranchResponse]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + ~.GetDefaultBranchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + catalog.CompletionConfig]: + r"""Return a callable for the get completion config method over gRPC. + + Gets a + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. + + Returns: + Callable[[~.GetCompletionConfigRequest], + ~.CompletionConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetCompletionConfig', + request_serializer=catalog_service.GetCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['get_completion_config'] + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + catalog.CompletionConfig]: + r"""Return a callable for the update completion config method over gRPC. + + Updates the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. + + Returns: + Callable[[~.UpdateCompletionConfigRequest], + ~.CompletionConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateCompletionConfig', + request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['update_completion_config'] + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + catalog.AttributesConfig]: + r"""Return a callable for the get attributes config method over gRPC. + + Gets an + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + Returns: + Callable[[~.GetAttributesConfigRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetAttributesConfig', + request_serializer=catalog_service.GetAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['get_attributes_config'] + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + catalog.AttributesConfig]: + r"""Return a callable for the update attributes config method over gRPC. + + Updates the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + Returns: + Callable[[~.UpdateAttributesConfigRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateAttributesConfig', + request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['update_attributes_config'] + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the add catalog attribute method over gRPC. + + Adds the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.AddCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_catalog_attribute' not in self._stubs: + self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/AddCatalogAttribute', + request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['add_catalog_attribute'] + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the remove catalog attribute method over gRPC. + + Removes the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.RemoveCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_catalog_attribute' not in self._stubs: + self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/RemoveCatalogAttribute', + request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['remove_catalog_attribute'] + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + catalog.AttributesConfig]: + r"""Return a callable for the replace catalog attribute method over gRPC. + + Replaces the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.ReplaceCatalogAttributeRequest], + ~.AttributesConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_catalog_attribute' not in self._stubs: + self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/ReplaceCatalogAttribute', + request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['replace_catalog_attribute'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CatalogServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..37eaea4b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py @@ -0,0 +1,599 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CatalogServiceGrpcTransport + + +class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): + """gRPC AsyncIO backend transport for CatalogService. + + Service for managing catalog configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_catalogs(self) -> Callable[ + [catalog_service.ListCatalogsRequest], + Awaitable[catalog_service.ListCatalogsResponse]]: + r"""Return a callable for the list catalogs method over gRPC. + + Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s + associated with the project. + + Returns: + Callable[[~.ListCatalogsRequest], + Awaitable[~.ListCatalogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalogs' not in self._stubs: + self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/ListCatalogs', + request_serializer=catalog_service.ListCatalogsRequest.serialize, + response_deserializer=catalog_service.ListCatalogsResponse.deserialize, + ) + return self._stubs['list_catalogs'] + + @property + def update_catalog(self) -> Callable[ + [catalog_service.UpdateCatalogRequest], + Awaitable[gcr_catalog.Catalog]]: + r"""Return a callable for the update catalog method over gRPC. + + Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. + + Returns: + Callable[[~.UpdateCatalogRequest], + Awaitable[~.Catalog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog' not in self._stubs: + self._stubs['update_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateCatalog', + request_serializer=catalog_service.UpdateCatalogRequest.serialize, + response_deserializer=gcr_catalog.Catalog.deserialize, + ) + return self._stubs['update_catalog'] + + @property + def set_default_branch(self) -> Callable[ + [catalog_service.SetDefaultBranchRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the set default branch method over gRPC. + + Set a specified branch id as default branch. API methods such as + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + will treat requests using "default_branch" to the actual branch + id set as default. + + For example, if ``projects/*/locations/*/catalogs/*/branches/1`` + is set as default, setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/default_branch`` + is equivalent to setting + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to ``projects/*/locations/*/catalogs/*/branches/1``. + + Using multiple branches can be useful when developers would like + to have a staging branch to test and verify for future usage. + When it becomes ready, developers switch on the staging branch + using this API while keeping using + ``projects/*/locations/*/catalogs/*/branches/default_branch`` as + [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] + to route the traffic to this staging branch. + + CAUTION: If you have live predict/search traffic, switching the + default branch could potentially cause outages if the ID space + of the new branch is very different from the old one. + + More specifically: + + - PredictionService will only return product IDs from branch + {newBranch}. + - SearchService will only return product IDs from branch + {newBranch} (if branch is not explicitly set). + - UserEventService will only join events with products from + branch {newBranch}. + + Returns: + Callable[[~.SetDefaultBranchRequest], + 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 'set_default_branch' not in self._stubs: + self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/SetDefaultBranch', + request_serializer=catalog_service.SetDefaultBranchRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['set_default_branch'] + + @property + def get_default_branch(self) -> Callable[ + [catalog_service.GetDefaultBranchRequest], + Awaitable[catalog_service.GetDefaultBranchResponse]]: + r"""Return a callable for the get default branch method over gRPC. + + Get which branch is currently default branch set by + [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] + method under a specified parent catalog. + + Returns: + Callable[[~.GetDefaultBranchRequest], + Awaitable[~.GetDefaultBranchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_default_branch' not in self._stubs: + self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetDefaultBranch', + request_serializer=catalog_service.GetDefaultBranchRequest.serialize, + response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, + ) + return self._stubs['get_default_branch'] + + @property + def get_completion_config(self) -> Callable[ + [catalog_service.GetCompletionConfigRequest], + Awaitable[catalog.CompletionConfig]]: + r"""Return a callable for the get completion config method over gRPC. + + Gets a + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. + + Returns: + Callable[[~.GetCompletionConfigRequest], + Awaitable[~.CompletionConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetCompletionConfig', + request_serializer=catalog_service.GetCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['get_completion_config'] + + @property + def update_completion_config(self) -> Callable[ + [catalog_service.UpdateCompletionConfigRequest], + Awaitable[catalog.CompletionConfig]]: + r"""Return a callable for the update completion config method over gRPC. + + Updates the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. + + Returns: + Callable[[~.UpdateCompletionConfigRequest], + Awaitable[~.CompletionConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_config' not in self._stubs: + self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateCompletionConfig', + request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, + response_deserializer=catalog.CompletionConfig.deserialize, + ) + return self._stubs['update_completion_config'] + + @property + def get_attributes_config(self) -> Callable[ + [catalog_service.GetAttributesConfigRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the get attributes config method over gRPC. + + Gets an + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + Returns: + Callable[[~.GetAttributesConfigRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/GetAttributesConfig', + request_serializer=catalog_service.GetAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['get_attributes_config'] + + @property + def update_attributes_config(self) -> Callable[ + [catalog_service.UpdateAttributesConfigRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the update attributes config method over gRPC. + + Updates the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + The catalog attributes in the request will be updated in the + catalog, or inserted if they do not exist. Existing catalog + attributes not included in the request will remain unchanged. + Attributes that are assigned to products, but do not exist at + the catalog level, are always included in the response. The + product attribute is assigned default values for missing catalog + attribute fields, e.g., searchable and dynamic facetable + options. + + Returns: + Callable[[~.UpdateAttributesConfigRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: + self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/UpdateAttributesConfig', + request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['update_attributes_config'] + + @property + def add_catalog_attribute(self) -> Callable[ + [catalog_service.AddCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the add catalog attribute method over gRPC. + + Adds the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.AddCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_catalog_attribute' not in self._stubs: + self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/AddCatalogAttribute', + request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['add_catalog_attribute'] + + @property + def remove_catalog_attribute(self) -> Callable[ + [catalog_service.RemoveCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the remove catalog attribute method over gRPC. + + Removes the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + from the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.RemoveCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_catalog_attribute' not in self._stubs: + self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/RemoveCatalogAttribute', + request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['remove_catalog_attribute'] + + @property + def replace_catalog_attribute(self) -> Callable[ + [catalog_service.ReplaceCatalogAttributeRequest], + Awaitable[catalog.AttributesConfig]]: + r"""Return a callable for the replace catalog attribute method over gRPC. + + Replaces the specified + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + in the + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + by updating the catalog attribute with the same + [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. + + If the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to replace does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.ReplaceCatalogAttributeRequest], + Awaitable[~.AttributesConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_catalog_attribute' not in self._stubs: + self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CatalogService/ReplaceCatalogAttribute', + request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, + response_deserializer=catalog.AttributesConfig.deserialize, + ) + return self._stubs['replace_catalog_attribute'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py new file mode 100644 index 00000000..b8af95bd --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CompletionServiceClient +from .async_client import CompletionServiceAsyncClient + +__all__ = ( + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py new file mode 100644 index 00000000..66c91320 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .client import CompletionServiceClient + + +class CompletionServiceAsyncClient: + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: CompletionServiceClient + + DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(CompletionServiceClient.catalog_path) + parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) + common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CompletionServiceClient.common_project_path) + parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) + common_location_path = staticmethod(CompletionServiceClient.common_location_path) + parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CompletionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_complete_query(): + # Create a client + client = retail_v2beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_query, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_import_completion_data(): + # Create a client + client = retail_v2beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2beta.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. + 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. + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_completion_data, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py new file mode 100644 index 00000000..5766b6b2 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CompletionServiceGrpcTransport +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +class CompletionServiceClientMeta(type): + """Metaclass for the CompletionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] + _transport_registry["grpc"] = CompletionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CompletionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CompletionServiceClient(metaclass=CompletionServiceClientMeta): + """Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CompletionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CompletionServiceTransport): + # transport is a CompletionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def complete_query(self, + request: Union[completion_service.CompleteQueryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_complete_query(): + # Create a client + client = retail_v2beta.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]): + The request object. Auto-complete parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.CompleteQueryResponse: + Response of the auto-complete query. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a completion_service.CompleteQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, completion_service.CompleteQueryRequest): + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("catalog", request.catalog), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_completion_data(self, + request: Union[import_config.ImportCompletionDataRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_import_completion_data(): + # Create a client + client = retail_v2beta.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2beta.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]): + The request object. Request message for + ImportCompletionData methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. + 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. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportCompletionDataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportCompletionDataRequest): + request = import_config.ImportCompletionDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_completion_data] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportCompletionDataResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CompletionServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py new file mode 100644 index 00000000..a0c9542f --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CompletionServiceTransport +from .grpc import CompletionServiceGrpcTransport +from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] +_transport_registry['grpc'] = CompletionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport + +__all__ = ( + 'CompletionServiceTransport', + 'CompletionServiceGrpcTransport', + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py new file mode 100644 index 00000000..6a5d8425 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CompletionServiceTransport(abc.ABC): + """Abstract transport class for CompletionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.complete_query: gapic_v1.method.wrap_method( + self.complete_query, + default_timeout=None, + client_info=client_info, + ), + self.import_completion_data: gapic_v1.method.wrap_method( + self.import_completion_data, + 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Union[ + completion_service.CompleteQueryResponse, + Awaitable[completion_service.CompleteQueryResponse] + ]]: + raise NotImplementedError() + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CompletionServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py new file mode 100644 index 00000000..d3ee0929 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py @@ -0,0 +1,325 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO + + +class CompletionServiceGrpcTransport(CompletionServiceTransport): + """gRPC backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + ~.CompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + operations_pb2.Operation]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CompletionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..56463003 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py @@ -0,0 +1,324 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CompletionServiceGrpcTransport + + +class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): + """gRPC AsyncIO backend transport for CompletionService. + + Auto-completion service for retail. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Awaitable[completion_service.CompleteQueryResponse]]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified prefix with keyword + suggestions. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.CompleteQueryRequest], + Awaitable[~.CompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + @property + def import_completion_data(self) -> Callable[ + [import_config.ImportCompletionDataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import completion data method over gRPC. + + Bulk import of processed completion dataset. + Request processing is asynchronous. Partial updating is + not supported. + The operation is successfully finished only after the + imported suggestions are indexed successfully and ready + for serving. The process takes hours. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.ImportCompletionDataRequest], + 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_completion_data' not in self._stubs: + self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.CompletionService/ImportCompletionData', + request_serializer=import_config.ImportCompletionDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_completion_data'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py new file mode 100644 index 00000000..e9a7be2f --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ControlServiceClient +from .async_client import ControlServiceAsyncClient + +__all__ = ( + 'ControlServiceClient', + 'ControlServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py new file mode 100644 index 00000000..5d3cfeb7 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py @@ -0,0 +1,742 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.control_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.cloud.retail_v2beta.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport +from .client import ControlServiceClient + + +class ControlServiceAsyncClient: + """Service for modifying Control.""" + + _client: ControlServiceClient + + DEFAULT_ENDPOINT = ControlServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ControlServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(ControlServiceClient.catalog_path) + parse_catalog_path = staticmethod(ControlServiceClient.parse_catalog_path) + control_path = staticmethod(ControlServiceClient.control_path) + parse_control_path = staticmethod(ControlServiceClient.parse_control_path) + common_billing_account_path = staticmethod(ControlServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ControlServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ControlServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ControlServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ControlServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ControlServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ControlServiceClient.common_project_path) + parse_common_project_path = staticmethod(ControlServiceClient.parse_common_project_path) + common_location_path = staticmethod(ControlServiceClient.common_location_path) + parse_common_location_path = staticmethod(ControlServiceClient.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: + ControlServiceAsyncClient: The constructed client. + """ + return ControlServiceClient.from_service_account_info.__func__(ControlServiceAsyncClient, 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: + ControlServiceAsyncClient: The constructed client. + """ + return ControlServiceClient.from_service_account_file.__func__(ControlServiceAsyncClient, 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 variabel 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 ControlServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ControlServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ControlServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ControlServiceClient).get_transport_class, type(ControlServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ControlServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the control service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ControlServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ControlServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_control(self, + request: Union[control_service.CreateControlRequest, dict] = None, + *, + parent: str = None, + control: gcr_control.Control = None, + control_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Creates a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_create_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = await client.create_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateControlRequest, dict]): + The request object. Request for CreateControl method. + parent (:class:`str`): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control (:class:`google.cloud.retail_v2beta.types.Control`): + Required. The Control to create. + This corresponds to the ``control`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control_id (:class:`str`): + Required. The ID to use for the Control, which will + become the final component of the Control's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``control_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.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, control, control_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.CreateControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if control is not None: + request.control = control + if control_id is not None: + request.control_id = control_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_control(self, + request: Union[control_service.DeleteControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_delete_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteControlRequest( + name="name_value", + ) + + # Make the request + await client.delete_control(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteControlRequest, dict]): + The request object. Request for DeleteControl method. + name (:class:`str`): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.DeleteControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_control(self, + request: Union[control_service.UpdateControlRequest, dict] = None, + *, + control: gcr_control.Control = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Updates a Control. + + [Control][google.cloud.retail.v2beta.Control] cannot be set to a + different oneof field, if so an INVALID_ARGUMENT is returned. If + the [Control][google.cloud.retail.v2beta.Control] to delete does + not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateControlRequest( + control=control, + ) + + # Make the request + response = await client.update_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateControlRequest, dict]): + The request object. Request for UpdateControl method. + control (:class:`google.cloud.retail_v2beta.types.Control`): + Required. The Control to update. + This corresponds to the ``control`` 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 + [Control][google.cloud.retail.v2beta.Control] to update. + The following are NOT supported: + + - [Control.name][google.cloud.retail.v2beta.Control.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([control, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.UpdateControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if control is not None: + request.control = control + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("control.name", request.control.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_control(self, + request: Union[control_service.GetControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> control.Control: + r"""Gets a Control. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetControlRequest( + name="name_value", + ) + + # Make the request + response = await client.get_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetControlRequest, dict]): + The request object. Request for GetControl method. + name (:class:`str`): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.GetControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_controls(self, + request: Union[control_service.ListControlsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListControlsAsyncPager: + r"""Lists all Controls linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_list_controls(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListControlsRequest, dict]): + The request object. Request for ListControls method. + parent (:class:`str`): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.control_service.pagers.ListControlsAsyncPager: + Response for ListControls method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = control_service.ListControlsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_controls, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListControlsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ControlServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py new file mode 100644 index 00000000..fbad615b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py @@ -0,0 +1,951 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.control_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.cloud.retail_v2beta.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ControlServiceGrpcTransport +from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport + + +class ControlServiceClientMeta(type): + """Metaclass for the ControlService 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[ControlServiceTransport]] + _transport_registry["grpc"] = ControlServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ControlServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ControlServiceTransport]: + """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 ControlServiceClient(metaclass=ControlServiceClientMeta): + """Service for modifying Control.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ControlServiceClient: 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: + ControlServiceClient: 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) -> ControlServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ControlServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def control_path(project: str,location: str,catalog: str,control: str,) -> str: + """Returns a fully-qualified control string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) + + @staticmethod + def parse_control_path(path: str) -> Dict[str,str]: + """Parses a control path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/controls/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ControlServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the control service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ControlServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ControlServiceTransport): + # transport is a ControlServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_control(self, + request: Union[control_service.CreateControlRequest, dict] = None, + *, + parent: str = None, + control: gcr_control.Control = None, + control_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Creates a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_create_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = client.create_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateControlRequest, dict]): + The request object. Request for CreateControl method. + parent (str): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control (google.cloud.retail_v2beta.types.Control): + Required. The Control to create. + This corresponds to the ``control`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + control_id (str): + Required. The ID to use for the Control, which will + become the final component of the Control's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``control_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.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, control, control_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.CreateControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.CreateControlRequest): + request = control_service.CreateControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if control is not None: + request.control = control + if control_id is not None: + request.control_id = control_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_control(self, + request: Union[control_service.DeleteControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to delete + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_delete_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteControlRequest( + name="name_value", + ) + + # Make the request + client.delete_control(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteControlRequest, dict]): + The request object. Request for DeleteControl method. + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.DeleteControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.DeleteControlRequest): + request = control_service.DeleteControlRequest(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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_control(self, + request: Union[control_service.UpdateControlRequest, dict] = None, + *, + control: gcr_control.Control = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_control.Control: + r"""Updates a Control. + + [Control][google.cloud.retail.v2beta.Control] cannot be set to a + different oneof field, if so an INVALID_ARGUMENT is returned. If + the [Control][google.cloud.retail.v2beta.Control] to delete does + not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateControlRequest( + control=control, + ) + + # Make the request + response = client.update_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateControlRequest, dict]): + The request object. Request for UpdateControl method. + control (google.cloud.retail_v2beta.types.Control): + Required. The Control to update. + This corresponds to the ``control`` 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 + [Control][google.cloud.retail.v2beta.Control] to update. + The following are NOT supported: + + - [Control.name][google.cloud.retail.v2beta.Control.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([control, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.UpdateControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.UpdateControlRequest): + request = control_service.UpdateControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if control is not None: + request.control = control + 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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("control.name", request.control.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_control(self, + request: Union[control_service.GetControlRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> control.Control: + r"""Gets a Control. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetControlRequest( + name="name_value", + ) + + # Make the request + response = client.get_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetControlRequest, dict]): + The request object. Request for GetControl method. + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Control: + Configures dynamic serving time + metadata that is used to pre and post + process search/recommendation model + results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.GetControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.GetControlRequest): + request = control_service.GetControlRequest(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_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_controls(self, + request: Union[control_service.ListControlsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListControlsPager: + r"""Lists all Controls linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_list_controls(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListControlsRequest, dict]): + The request object. Request for ListControls method. + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.control_service.pagers.ListControlsPager: + Response for ListControls method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a control_service.ListControlsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, control_service.ListControlsRequest): + request = control_service.ListControlsRequest(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_controls] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListControlsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ControlServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py new file mode 100644 index 00000000..f51a3970 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control_service + + +class ListControlsPager: + """A pager for iterating through ``list_controls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListControlsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``controls`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListControls`` requests and continue to iterate + through the ``controls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListControlsResponse` + 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[..., control_service.ListControlsResponse], + request: control_service.ListControlsRequest, + response: control_service.ListControlsResponse, + *, + 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.retail_v2beta.types.ListControlsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListControlsResponse): + 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 = control_service.ListControlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[control_service.ListControlsResponse]: + 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[control.Control]: + for page in self.pages: + yield from page.controls + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListControlsAsyncPager: + """A pager for iterating through ``list_controls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListControlsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``controls`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListControls`` requests and continue to iterate + through the ``controls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListControlsResponse` + 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[control_service.ListControlsResponse]], + request: control_service.ListControlsRequest, + response: control_service.ListControlsResponse, + *, + 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.retail_v2beta.types.ListControlsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListControlsResponse): + 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 = control_service.ListControlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[control_service.ListControlsResponse]: + 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[control.Control]: + async def async_generator(): + async for page in self.pages: + for response in page.controls: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py new file mode 100644 index 00000000..3622876b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ControlServiceTransport +from .grpc import ControlServiceGrpcTransport +from .grpc_asyncio import ControlServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ControlServiceTransport]] +_transport_registry['grpc'] = ControlServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ControlServiceGrpcAsyncIOTransport + +__all__ = ( + 'ControlServiceTransport', + 'ControlServiceGrpcTransport', + 'ControlServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py new file mode 100644 index 00000000..2424eb4a --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ControlServiceTransport(abc.ABC): + """Abstract transport class for ControlService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_control: gapic_v1.method.wrap_method( + self.create_control, + default_timeout=None, + client_info=client_info, + ), + self.delete_control: gapic_v1.method.wrap_method( + self.delete_control, + default_timeout=None, + client_info=client_info, + ), + self.update_control: gapic_v1.method.wrap_method( + self.update_control, + default_timeout=None, + client_info=client_info, + ), + self.get_control: gapic_v1.method.wrap_method( + self.get_control, + default_timeout=None, + client_info=client_info, + ), + self.list_controls: gapic_v1.method.wrap_method( + self.list_controls, + 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 create_control(self) -> Callable[ + [control_service.CreateControlRequest], + Union[ + gcr_control.Control, + Awaitable[gcr_control.Control] + ]]: + raise NotImplementedError() + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + Union[ + gcr_control.Control, + Awaitable[gcr_control.Control] + ]]: + raise NotImplementedError() + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + Union[ + control.Control, + Awaitable[control.Control] + ]]: + raise NotImplementedError() + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + Union[ + control_service.ListControlsResponse, + Awaitable[control_service.ListControlsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ControlServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py new file mode 100644 index 00000000..64b13dfb --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py @@ -0,0 +1,382 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO + + +class ControlServiceGrpcTransport(ControlServiceTransport): + """gRPC backend transport for ControlService. + + Service for modifying Control. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_control(self) -> Callable[ + [control_service.CreateControlRequest], + gcr_control.Control]: + r"""Return a callable for the create control method over gRPC. + + Creates a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['create_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/CreateControl', + request_serializer=control_service.CreateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['create_control'] + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete control method over gRPC. + + Deletes a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteControlRequest], + ~.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_control' not in self._stubs: + self._stubs['delete_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/DeleteControl', + request_serializer=control_service.DeleteControlRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_control'] + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + gcr_control.Control]: + r"""Return a callable for the update control method over gRPC. + + Updates a Control. + + [Control][google.cloud.retail.v2beta.Control] cannot be set to a + different oneof field, if so an INVALID_ARGUMENT is returned. If + the [Control][google.cloud.retail.v2beta.Control] to delete does + not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['update_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/UpdateControl', + request_serializer=control_service.UpdateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['update_control'] + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + control.Control]: + r"""Return a callable for the get control method over gRPC. + + Gets a Control. + + Returns: + Callable[[~.GetControlRequest], + ~.Control]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['get_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/GetControl', + request_serializer=control_service.GetControlRequest.serialize, + response_deserializer=control.Control.deserialize, + ) + return self._stubs['get_control'] + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + control_service.ListControlsResponse]: + r"""Return a callable for the list controls method over gRPC. + + Lists all Controls linked to this catalog. + + Returns: + Callable[[~.ListControlsRequest], + ~.ListControlsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_controls' not in self._stubs: + self._stubs['list_controls'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/ListControls', + request_serializer=control_service.ListControlsRequest.serialize, + response_deserializer=control_service.ListControlsResponse.deserialize, + ) + return self._stubs['list_controls'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ControlServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..701a8de1 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ControlServiceGrpcTransport + + +class ControlServiceGrpcAsyncIOTransport(ControlServiceTransport): + """gRPC AsyncIO backend transport for ControlService. + + Service for modifying Control. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_control(self) -> Callable[ + [control_service.CreateControlRequest], + Awaitable[gcr_control.Control]]: + r"""Return a callable for the create control method over gRPC. + + Creates a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to create + already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['create_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/CreateControl', + request_serializer=control_service.CreateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['create_control'] + + @property + def delete_control(self) -> Callable[ + [control_service.DeleteControlRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete control method over gRPC. + + Deletes a Control. + + If the [Control][google.cloud.retail.v2beta.Control] to delete + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteControlRequest], + 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_control' not in self._stubs: + self._stubs['delete_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/DeleteControl', + request_serializer=control_service.DeleteControlRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_control'] + + @property + def update_control(self) -> Callable[ + [control_service.UpdateControlRequest], + Awaitable[gcr_control.Control]]: + r"""Return a callable for the update control method over gRPC. + + Updates a Control. + + [Control][google.cloud.retail.v2beta.Control] cannot be set to a + different oneof field, if so an INVALID_ARGUMENT is returned. If + the [Control][google.cloud.retail.v2beta.Control] to delete does + not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['update_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/UpdateControl', + request_serializer=control_service.UpdateControlRequest.serialize, + response_deserializer=gcr_control.Control.deserialize, + ) + return self._stubs['update_control'] + + @property + def get_control(self) -> Callable[ + [control_service.GetControlRequest], + Awaitable[control.Control]]: + r"""Return a callable for the get control method over gRPC. + + Gets a Control. + + Returns: + Callable[[~.GetControlRequest], + Awaitable[~.Control]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_control' not in self._stubs: + self._stubs['get_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/GetControl', + request_serializer=control_service.GetControlRequest.serialize, + response_deserializer=control.Control.deserialize, + ) + return self._stubs['get_control'] + + @property + def list_controls(self) -> Callable[ + [control_service.ListControlsRequest], + Awaitable[control_service.ListControlsResponse]]: + r"""Return a callable for the list controls method over gRPC. + + Lists all Controls linked to this catalog. + + Returns: + Callable[[~.ListControlsRequest], + Awaitable[~.ListControlsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_controls' not in self._stubs: + self._stubs['list_controls'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ControlService/ListControls', + request_serializer=control_service.ListControlsRequest.serialize, + response_deserializer=control_service.ListControlsResponse.deserialize, + ) + return self._stubs['list_controls'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ControlServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py new file mode 100644 index 00000000..7c079c80 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import PredictionServiceClient +from .async_client import PredictionServiceAsyncClient + +__all__ = ( + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py new file mode 100644 index 00000000..d8a1a148 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport +from .client import PredictionServiceClient + + +class PredictionServiceAsyncClient: + """Service for making recommendation prediction.""" + + _client: PredictionServiceClient + + DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT + + product_path = staticmethod(PredictionServiceClient.product_path) + parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) + common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(PredictionServiceClient.common_project_path) + parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) + common_location_path = staticmethod(PredictionServiceClient.common_location_path) + parse_common_location_path = staticmethod(PredictionServiceClient.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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PredictionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_predict(): + # Create a client + client = retail_v2beta.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + request = prediction_service.PredictRequest(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.predict, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py new file mode 100644 index 00000000..6eb343ca --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py @@ -0,0 +1,480 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionServiceGrpcTransport +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +class PredictionServiceClientMeta(type): + """Metaclass for the PredictionService 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[PredictionServiceTransport]] + _transport_registry["grpc"] = PredictionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PredictionServiceTransport]: + """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): + """Service for making recommendation prediction.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PredictionServiceClient: 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: + PredictionServiceClient: 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) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PredictionServiceTransport): + # transport is a PredictionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def predict(self, + request: Union[prediction_service.PredictRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_service.PredictResponse: + r"""Makes a recommendation prediction. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_predict(): + # Create a client + client = retail_v2beta.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.PredictRequest, dict]): + The request object. Request message for Predict method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.PredictResponse: + Response message for predict method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a prediction_service.PredictRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_service.PredictRequest): + request = prediction_service.PredictRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.predict] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py new file mode 100644 index 00000000..bb65c664 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PredictionServiceTransport +from .grpc import PredictionServiceGrpcTransport +from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] +_transport_registry['grpc'] = PredictionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport + +__all__ = ( + 'PredictionServiceTransport', + 'PredictionServiceGrpcTransport', + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py new file mode 100644 index 00000000..12f65a6c --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PredictionServiceTransport(abc.ABC): + """Abstract transport class for PredictionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.predict: gapic_v1.method.wrap_method( + self.predict, + 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + Union[ + prediction_service.PredictResponse, + Awaitable[prediction_service.PredictResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'PredictionServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py new file mode 100644 index 00000000..98c69839 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py @@ -0,0 +1,264 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO + + +class PredictionServiceGrpcTransport(PredictionServiceTransport): + """gRPC backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 predict(self) -> Callable[ + [prediction_service.PredictRequest], + prediction_service.PredictResponse]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + ~.PredictResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'PredictionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..11fce51c --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import PredictionServiceGrpcTransport + + +class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): + """gRPC AsyncIO backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + Awaitable[prediction_service.PredictResponse]]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. + + Returns: + Callable[[~.PredictRequest], + Awaitable[~.PredictResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py new file mode 100644 index 00000000..0fa6330a --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ProductServiceClient +from .async_client import ProductServiceAsyncClient + +__all__ = ( + 'ProductServiceClient', + 'ProductServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py new file mode 100644 index 00000000..493936e0 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py @@ -0,0 +1,1692 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.services.product_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.cloud.retail_v2beta.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport +from .client import ProductServiceClient + + +class ProductServiceAsyncClient: + """Service for ingesting [Product][google.cloud.retail.v2beta.Product] + information of the customer's website. + """ + + _client: ProductServiceClient + + DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(ProductServiceClient.branch_path) + parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) + product_path = staticmethod(ProductServiceClient.product_path) + parse_product_path = staticmethod(ProductServiceClient.parse_product_path) + common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProductServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProductServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProductServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProductServiceClient.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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: + ProductServiceAsyncClient: The constructed client. + """ + return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ProductServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ProductServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_create_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`google.cloud.retail_v2beta.types.Product`): + Required. The + [Product][google.cloud.retail.v2beta.Product] to create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + Required. The ID to use for the + [Product][google.cloud.retail.v2beta.Product], which + will become the final component of the + [Product.name][google.cloud.retail.v2beta.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This field must be unique among all + [Product][google.cloud.retail.v2beta.Product]s with the + same + [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Product][google.cloud.retail.v2beta.Product] 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.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Gets a list of [Product][google.cloud.retail.v2beta.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_list_products(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2beta.Product]s under + this branch, regardless of whether or not this branch + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.product_service.pagers.ListProductsAsyncPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (:class:`google.cloud.retail_v2beta.types.Product`): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2beta.Product] to update. + The immutable and output only fields are NOT supported. + If not set, all supported fields (the fields that are + neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_delete_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2beta.Product] to + delete can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product] member nor + a + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] with more + than one + [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2beta.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2beta.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2beta.Product]s to be + successfully updated. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_import_products(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2beta.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2beta.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_set_inventory(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2beta.Product() + inventory.title = "title_value" + + request = retail_v2beta.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (:class:`google.cloud.retail_v2beta.types.Product`): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product] named in + [Product.name][google.cloud.retail.v2beta.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2beta.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2beta.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.SetInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_inventory, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + async def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [AddFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveFulfillmentPlacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_fulfillment_places, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + async def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_add_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [AddLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.AddLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_remove_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (:class:`str`): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = product_service.RemoveLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_local_inventories, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py new file mode 100644 index 00000000..fa4ba1f6 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py @@ -0,0 +1,1895 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.services.product_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.cloud.retail_v2beta.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductServiceGrpcTransport +from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +class ProductServiceClientMeta(type): + """Metaclass for the ProductService 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[ProductServiceTransport]] + _transport_registry["grpc"] = ProductServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ProductServiceTransport]: + """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 ProductServiceClient(metaclass=ProductServiceClientMeta): + """Service for ingesting [Product][google.cloud.retail.v2beta.Product] + information of the customer's website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProductServiceClient: 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: + ProductServiceClient: 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) -> ProductServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ProductServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ProductServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProductServiceTransport): + # transport is a ProductServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_product(self, + request: Union[product_service.CreateProductRequest, dict] = None, + *, + parent: str = None, + product: gcr_product.Product = None, + product_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Creates a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_create_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateProductRequest, dict]): + The request object. Request message for + [CreateProduct][] method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (google.cloud.retail_v2beta.types.Product): + Required. The + [Product][google.cloud.retail.v2beta.Product] to create. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2beta.Product], which + will become the final component of the + [Product.name][google.cloud.retail.v2beta.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This field must be unique among all + [Product][google.cloud.retail.v2beta.Product]s with the + same + [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This corresponds to the ``product_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.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.CreateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.CreateProductRequest): + request = product_service.CreateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product(self, + request: Union[product_service.GetProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product.Product: + r"""Gets a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetProductRequest, dict]): + The request object. Request message for [GetProduct][] + method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Product][google.cloud.retail.v2beta.Product] 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.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.GetProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.GetProductRequest): + request = product_service.GetProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_products(self, + request: Union[product_service.ListProductsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Gets a list of [Product][google.cloud.retail.v2beta.Product]s. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_list_products(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListProductsRequest, dict]): + The request object. Request message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list + products under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2beta.Product]s under + this branch, regardless of whether or not this branch + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.product_service.pagers.ListProductsPager: + Response message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.ListProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.ListProductsRequest): + request = product_service.ListProductsRequest(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_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_product(self, + request: Union[product_service.UpdateProductRequest, dict] = None, + *, + product: gcr_product.Product = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_product.Product: + r"""Updates a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateProductRequest, dict]): + The request object. Request message for + [UpdateProduct][] method. + product (google.cloud.retail_v2beta.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + + This corresponds to the ``product`` 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 + [Product][google.cloud.retail.v2beta.Product] to update. + The immutable and output only fields are NOT supported. + If not set, all supported fields (the fields that are + neither immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.Product: + Product captures all metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.UpdateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.UpdateProductRequest): + request = product_service.UpdateProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + 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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_product(self, + request: Union[product_service.DeleteProductRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Product][google.cloud.retail.v2beta.Product]. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_delete_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteProductRequest, dict]): + The request object. Request message for + [DeleteProduct][] method. + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2beta.Product] to + delete can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product] member nor + a + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] with more + than one + [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2beta.Product] will be + deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.DeleteProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.DeleteProductRequest): + request = product_service.DeleteProductRequest(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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_products(self, + request: Union[import_config.ImportProductsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple + [Product][google.cloud.retail.v2beta.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2beta.Product]s to be + successfully updated. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_import_products(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2beta.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportProductsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportProductsResponse` Response of the + [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportProductsRequest): + request = import_config.ImportProductsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportProductsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def set_inventory(self, + request: Union[product_service.SetInventoryRequest, dict] = None, + *, + inventory: product.Product = None, + set_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates inventory information for a + [Product][google.cloud.retail.v2beta.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_set_inventory(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2beta.Product() + inventory.title = "title_value" + + request = retail_v2beta.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.SetInventoryRequest, dict]): + The request object. Request message for [SetInventory][] + method. + inventory (google.cloud.retail_v2beta.types.Product): + Required. The inventory information to update. The + allowable fields to update are: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product] named in + [Product.name][google.cloud.retail.v2beta.Product.name], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2beta.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting + the last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear + in [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types + have empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following + inventory fields: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + + If a full overwrite of inventory information while + ignoring timestamps is needed, [UpdateProduct][] should + be invoked instead. + + This corresponds to the ``inventory`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2beta.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + + This corresponds to the ``set_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because + there is no meaningful response populated from the + [SetInventory][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([inventory, set_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.SetInventoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.SetInventoryRequest): + request = product_service.SetInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if inventory is not None: + request.inventory = inventory + if set_mask is not None: + request.set_mask = set_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("inventory.name", request.inventory.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + product_service.SetInventoryResponse, + metadata_type=product_service.SetInventoryMetadata, + ) + + # Done; return the response. + return response + + def add_fulfillment_places(self, + request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_add_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest, dict]): + The request object. Request message for + [AddFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddFulfillmentPlacesRequest): + request = product_service.AddFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddFulfillmentPlacesResponse, + metadata_type=product_service.AddFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def remove_fulfillment_places(self, + request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest, dict]): + The request object. Request message for + [RemoveFulfillmentPlaces][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there + is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveFulfillmentPlacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): + request = product_service.RemoveFulfillmentPlacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveFulfillmentPlacesResponse, + metadata_type=product_service.RemoveFulfillmentPlacesMetadata, + ) + + # Done; return the response. + return response + + def add_local_inventories(self, + request: Union[product_service.AddLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_add_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddLocalInventoriesRequest, dict]): + The request object. Request message for + [AddLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.AddLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.AddLocalInventoriesRequest): + request = product_service.AddLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.AddLocalInventoriesResponse, + metadata_type=product_service.AddLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def remove_local_inventories(self, + request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, + *, + product: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_remove_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest, dict]): + The request object. Request message for + [RemoveLocalInventories][] method. + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a product_service.RemoveLocalInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_service.RemoveLocalInventoriesRequest): + request = product_service.RemoveLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("product", request.product), + )), + ) + + # 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, + product_service.RemoveLocalInventoriesResponse, + metadata_type=product_service.RemoveLocalInventoriesMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ProductServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py new file mode 100644 index 00000000..552c2bfa --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product_service + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListProductsResponse` + 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[..., product_service.ListProductsResponse], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2beta.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[product_service.ListProductsResponse]: + 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[product.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListProductsResponse` + 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[product_service.ListProductsResponse]], + request: product_service.ListProductsRequest, + response: product_service.ListProductsResponse, + *, + 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.retail_v2beta.types.ListProductsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListProductsResponse): + 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 = product_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: + 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[product.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py new file mode 100644 index 00000000..db824dec --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ProductServiceTransport +from .grpc import ProductServiceGrpcTransport +from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] +_transport_registry['grpc'] = ProductServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport + +__all__ = ( + 'ProductServiceTransport', + 'ProductServiceGrpcTransport', + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py new file mode 100644 index 00000000..325ba99e --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py @@ -0,0 +1,312 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ProductServiceTransport(abc.ABC): + """Abstract transport class for ProductService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_product: gapic_v1.method.wrap_method( + self.create_product, + default_timeout=None, + client_info=client_info, + ), + self.get_product: gapic_v1.method.wrap_method( + self.get_product, + default_timeout=None, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + default_timeout=None, + client_info=client_info, + ), + self.update_product: gapic_v1.method.wrap_method( + self.update_product, + default_timeout=None, + client_info=client_info, + ), + self.delete_product: gapic_v1.method.wrap_method( + self.delete_product, + default_timeout=None, + client_info=client_info, + ), + self.import_products: gapic_v1.method.wrap_method( + self.import_products, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.set_inventory: gapic_v1.method.wrap_method( + self.set_inventory, + default_timeout=None, + client_info=client_info, + ), + self.add_fulfillment_places: gapic_v1.method.wrap_method( + self.add_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.remove_fulfillment_places: gapic_v1.method.wrap_method( + self.remove_fulfillment_places, + default_timeout=None, + client_info=client_info, + ), + self.add_local_inventories: gapic_v1.method.wrap_method( + self.add_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.remove_local_inventories: gapic_v1.method.wrap_method( + self.remove_local_inventories, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Union[ + product.Product, + Awaitable[product.Product] + ]]: + raise NotImplementedError() + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Union[ + product_service.ListProductsResponse, + Awaitable[product_service.ListProductsResponse] + ]]: + raise NotImplementedError() + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Union[ + gcr_product.Product, + Awaitable[gcr_product.Product] + ]]: + raise NotImplementedError() + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProductServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py new file mode 100644 index 00000000..8df65e63 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py @@ -0,0 +1,680 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO + + +class ProductServiceGrpcTransport(ProductServiceTransport): + """gRPC backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2beta.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + gcr_product.Product]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.CreateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + product.Product]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + product_service.ListProductsResponse]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2beta.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + gcr_product.Product]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + ~.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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2beta.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2beta.Product]s to be + successfully updated. + + Returns: + Callable[[~.ImportProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + operations_pb2.Operation]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2beta.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProductServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..9ccfc3ee --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py @@ -0,0 +1,679 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductServiceGrpcTransport + + +class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): + """gRPC AsyncIO backend transport for ProductService. + + Service for ingesting [Product][google.cloud.retail.v2beta.Product] + information of the customer's website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_product(self) -> Callable[ + [product_service.CreateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the create product method over gRPC. + + Creates a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.CreateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['create_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/CreateProduct', + request_serializer=product_service.CreateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['create_product'] + + @property + def get_product(self) -> Callable[ + [product_service.GetProductRequest], + Awaitable[product.Product]]: + r"""Return a callable for the get product method over gRPC. + + Gets a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/GetProduct', + request_serializer=product_service.GetProductRequest.serialize, + response_deserializer=product.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [product_service.ListProductsRequest], + Awaitable[product_service.ListProductsResponse]]: + r"""Return a callable for the list products method over gRPC. + + Gets a list of [Product][google.cloud.retail.v2beta.Product]s. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/ListProducts', + request_serializer=product_service.ListProductsRequest.serialize, + response_deserializer=product_service.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + @property + def update_product(self) -> Callable[ + [product_service.UpdateProductRequest], + Awaitable[gcr_product.Product]]: + r"""Return a callable for the update product method over gRPC. + + Updates a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.UpdateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['update_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/UpdateProduct', + request_serializer=product_service.UpdateProductRequest.serialize, + response_deserializer=gcr_product.Product.deserialize, + ) + return self._stubs['update_product'] + + @property + def delete_product(self) -> Callable[ + [product_service.DeleteProductRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete product method over gRPC. + + Deletes a [Product][google.cloud.retail.v2beta.Product]. + + Returns: + Callable[[~.DeleteProductRequest], + 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_product' not in self._stubs: + self._stubs['delete_product'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/DeleteProduct', + request_serializer=product_service.DeleteProductRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product'] + + @property + def import_products(self) -> Callable[ + [import_config.ImportProductsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import products method over gRPC. + + Bulk import of multiple + [Product][google.cloud.retail.v2beta.Product]s. + + Request processing may be synchronous. No partial updating is + supported. Non-existing items are created. + + Note that it is possible for a subset of the + [Product][google.cloud.retail.v2beta.Product]s to be + successfully updated. + + Returns: + Callable[[~.ImportProductsRequest], + 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_products' not in self._stubs: + self._stubs['import_products'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/ImportProducts', + request_serializer=import_config.ImportProductsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_products'] + + @property + def set_inventory(self) -> Callable[ + [product_service.SetInventoryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the set inventory method over gRPC. + + Updates inventory information for a + [Product][google.cloud.retail.v2beta.Product] while respecting + the last update timestamps of each inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + When inventory is updated with + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], + the specified inventory field value(s) will overwrite any + existing value(s) while ignoring the last update time for this + field. Furthermore, the last update time for the specified + inventory fields will be overwritten to the time of the + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + or + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + request. + + If no inventory fields are set in + [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], + then any pre-existing inventory information for this product + will be used. + + If no inventory fields are set in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], + then any existing inventory information will be preserved. + + Pre-existing inventory information can only be updated with + [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], + [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], + and + [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.SetInventoryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_inventory' not in self._stubs: + self._stubs['set_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/SetInventory', + request_serializer=product_service.SetInventoryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['set_inventory'] + + @property + def add_fulfillment_places(self) -> Callable[ + [product_service.AddFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add fulfillment places method over gRPC. + + Incrementally adds place IDs to + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the added place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddFulfillmentPlacesRequest], + 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 'add_fulfillment_places' not in self._stubs: + self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/AddFulfillmentPlaces', + request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_fulfillment_places'] + + @property + def remove_fulfillment_places(self) -> Callable[ + [product_service.RemoveFulfillmentPlacesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove fulfillment places method over gRPC. + + Incrementally removes place IDs from a + [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating fulfillment information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, the removed place IDs + are not immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveFulfillmentPlacesRequest], + 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 'remove_fulfillment_places' not in self._stubs: + self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/RemoveFulfillmentPlaces', + request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_fulfillment_places'] + + @property + def add_local_inventories(self) -> Callable[ + [product_service.AddLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add local inventories method over gRPC. + + Updates local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places, while respecting the last update timestamps of each + inventory field. + + This process is asynchronous and does not require the + [Product][google.cloud.retail.v2beta.Product] to exist before + updating inventory information. If the request is valid, the + update will be enqueued and processed downstream. As a + consequence, when a response is returned, updates are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be modified using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.AddLocalInventoriesRequest], + 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 'add_local_inventories' not in self._stubs: + self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/AddLocalInventories', + request_serializer=product_service.AddLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_local_inventories'] + + @property + def remove_local_inventories(self) -> Callable[ + [product_service.RemoveLocalInventoriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove local inventories method over gRPC. + + Remove local inventory information for a + [Product][google.cloud.retail.v2beta.Product] at a list of + places at a removal timestamp. + + This process is asynchronous. If the request is valid, the + removal will be enqueued and processed downstream. As a + consequence, when a response is returned, removals are not + immediately manifested in the + [Product][google.cloud.retail.v2beta.Product] queried by + [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + or + [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + Local inventory information can only be removed using this + method. + [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] + and + [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] + has no effect on local inventories. + + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + Returns: + Callable[[~.RemoveLocalInventoriesRequest], + 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 'remove_local_inventories' not in self._stubs: + self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ProductService/RemoveLocalInventories', + request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_local_inventories'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ProductServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py new file mode 100644 index 00000000..2f63fc22 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SearchServiceClient +from .async_client import SearchServiceAsyncClient + +__all__ = ( + 'SearchServiceClient', + 'SearchServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py new file mode 100644 index 00000000..4943cff9 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.search_service import pagers +from google.cloud.retail_v2beta.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .client import SearchServiceClient + + +class SearchServiceAsyncClient: + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + _client: SearchServiceClient + + DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(SearchServiceClient.branch_path) + parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + product_path = staticmethod(SearchServiceClient.product_path) + parse_product_path = staticmethod(SearchServiceClient.parse_product_path) + common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(SearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SearchServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAsyncPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_search(): + # Create a client + client = retail_v2beta.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.search_service.pagers.SearchAsyncPager: + Response message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py new file mode 100644 index 00000000..7c944320 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py @@ -0,0 +1,513 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.search_service import pagers +from google.cloud.retail_v2beta.types import search_service +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SearchServiceGrpcTransport +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +class SearchServiceClientMeta(type): + """Metaclass for the SearchService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] + _transport_registry["grpc"] = SearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SearchServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SearchServiceClient(metaclass=SearchServiceClientMeta): + """Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SearchServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SearchServiceTransport): + # transport is a SearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def search(self, + request: Union[search_service.SearchRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchPager: + r"""Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_search(): + # Create a client + client = retail_v2beta.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.search_service.pagers.SearchPager: + Response message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a search_service.SearchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("placement", request.placement), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SearchServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py new file mode 100644 index 00000000..6ff03162 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import search_service + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2beta.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.retail_v2beta.types.SearchRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py new file mode 100644 index 00000000..7917cd1d --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SearchServiceTransport +from .grpc import SearchServiceGrpcTransport +from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] +_transport_registry['grpc'] = SearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport + +__all__ = ( + 'SearchServiceTransport', + 'SearchServiceGrpcTransport', + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py new file mode 100644 index 00000000..c084a7f1 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import search_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SearchServiceTransport(abc.ABC): + """Abstract transport class for SearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search: gapic_v1.method.wrap_method( + self.search, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Union[ + search_service.SearchResponse, + Awaitable[search_service.SearchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SearchServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py new file mode 100644 index 00000000..74a10421 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py @@ -0,0 +1,270 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO + + +class SearchServiceGrpcTransport(SearchServiceTransport): + """gRPC backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..3dfd4aa1 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import search_service +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SearchServiceGrpcTransport + + +class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): + """gRPC AsyncIO backend transport for SearchService. + + Service for search. + This feature is only available for users who have Retail Search + enabled. Please enable Retail Search on Cloud Console before + using this feature. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Awaitable[search_service.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + This feature is only available for users who have Retail + Search enabled. Please enable Retail Search on Cloud + Console before using this feature. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py new file mode 100644 index 00000000..d1a0a023 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ServingConfigServiceClient +from .async_client import ServingConfigServiceAsyncClient + +__all__ = ( + 'ServingConfigServiceClient', + 'ServingConfigServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py new file mode 100644 index 00000000..cfdace1d --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py @@ -0,0 +1,954 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.serving_config_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport +from .client import ServingConfigServiceClient + + +class ServingConfigServiceAsyncClient: + """Service for modifying ServingConfig.""" + + _client: ServingConfigServiceClient + + DEFAULT_ENDPOINT = ServingConfigServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ServingConfigServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(ServingConfigServiceClient.catalog_path) + parse_catalog_path = staticmethod(ServingConfigServiceClient.parse_catalog_path) + serving_config_path = staticmethod(ServingConfigServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(ServingConfigServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(ServingConfigServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ServingConfigServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ServingConfigServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ServingConfigServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ServingConfigServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ServingConfigServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ServingConfigServiceClient.common_project_path) + parse_common_project_path = staticmethod(ServingConfigServiceClient.parse_common_project_path) + common_location_path = staticmethod(ServingConfigServiceClient.common_location_path) + parse_common_location_path = staticmethod(ServingConfigServiceClient.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: + ServingConfigServiceAsyncClient: The constructed client. + """ + return ServingConfigServiceClient.from_service_account_info.__func__(ServingConfigServiceAsyncClient, 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: + ServingConfigServiceAsyncClient: The constructed client. + """ + return ServingConfigServiceClient.from_service_account_file.__func__(ServingConfigServiceAsyncClient, 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 variabel 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 ServingConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ServingConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ServingConfigServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ServingConfigServiceClient).get_transport_class, type(ServingConfigServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ServingConfigServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the serving config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ServingConfigServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ServingConfigServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_serving_config(self, + request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, + *, + parent: str = None, + serving_config: gcr_serving_config.ServingConfig = None, + serving_config_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_create_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = await client.create_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateServingConfigRequest, dict]): + The request object. Request for CreateServingConfig + method. + parent (:class:`str`): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config (:class:`google.cloud.retail_v2beta.types.ServingConfig`): + Required. The ServingConfig to + create. + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config_id (:class:`str`): + Required. The ID to use for the ServingConfig, which + will become the final component of the ServingConfig's + resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``serving_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, serving_config, serving_config_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.CreateServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if serving_config is not None: + request.serving_config = serving_config + if serving_config_id is not None: + request.serving_config_id = serving_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_serving_config(self, + request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_delete_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_serving_config(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteServingConfigRequest, dict]): + The request object. Request for DeleteServingConfig + method. + name (:class:`str`): + Required. The resource name of the ServingConfig to + delete. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.DeleteServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_serving_config(self, + request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, + *, + serving_config: gcr_serving_config.ServingConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Updates a ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_update_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = await client.update_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateServingConfigRequest, dict]): + The request object. Request for UpdateServingConfig + method. + serving_config (:class:`google.cloud.retail_v2beta.types.ServingConfig`): + Required. The ServingConfig to + update. + + This corresponds to the ``serving_config`` 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 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.UpdateServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config.name", request.serving_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_serving_config(self, + request: Union[serving_config_service.GetServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> serving_config.ServingConfig: + r"""Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_get_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetServingConfigRequest, dict]): + The request object. Request for GetServingConfig method. + name (:class:`str`): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.GetServingConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_serving_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_serving_configs(self, + request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServingConfigsAsyncPager: + r"""Lists all ServingConfigs linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_list_serving_configs(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListServingConfigsRequest, dict]): + The request object. Request for ListServingConfigs + method. + parent (:class:`str`): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager: + Response for ListServingConfigs + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.ListServingConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_serving_configs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServingConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_control(self, + request: Union[serving_config_service.AddControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_add_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.add_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddControlRequest, dict]): + The request object. Request for AddControl method. + serving_config (:class:`str`): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.AddControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_control(self, + request: Union[serving_config_service.RemoveControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_remove_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.remove_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveControlRequest, dict]): + The request object. Request for RemoveControl method. + serving_config (:class:`str`): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = serving_config_service.RemoveControlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_control, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServingConfigServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py new file mode 100644 index 00000000..bca31abe --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py @@ -0,0 +1,1163 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.retail_v2beta.services.serving_config_service import pagers +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ServingConfigServiceGrpcTransport +from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport + + +class ServingConfigServiceClientMeta(type): + """Metaclass for the ServingConfigService 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[ServingConfigServiceTransport]] + _transport_registry["grpc"] = ServingConfigServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ServingConfigServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ServingConfigServiceTransport]: + """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 ServingConfigServiceClient(metaclass=ServingConfigServiceClientMeta): + """Service for modifying ServingConfig.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServingConfigServiceClient: 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: + ServingConfigServiceClient: 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) -> ServingConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ServingConfigServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,catalog: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ServingConfigServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the serving config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ServingConfigServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ServingConfigServiceTransport): + # transport is a ServingConfigServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_serving_config(self, + request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, + *, + parent: str = None, + serving_config: gcr_serving_config.ServingConfig = None, + serving_config_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_create_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = client.create_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CreateServingConfigRequest, dict]): + The request object. Request for CreateServingConfig + method. + parent (str): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config (google.cloud.retail_v2beta.types.ServingConfig): + Required. The ServingConfig to + create. + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + serving_config_id (str): + Required. The ID to use for the ServingConfig, which + will become the final component of the ServingConfig's + resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-_/. + + This corresponds to the ``serving_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick 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, serving_config, serving_config_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.CreateServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.CreateServingConfigRequest): + request = serving_config_service.CreateServingConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if serving_config is not None: + request.serving_config = serving_config + if serving_config_id is not None: + request.serving_config_id = serving_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_serving_config(self, + request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_delete_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_serving_config(request=request) + + Args: + request (Union[google.cloud.retail_v2beta.types.DeleteServingConfigRequest, dict]): + The request object. Request for DeleteServingConfig + method. + name (str): + Required. The resource name of the ServingConfig to + delete. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.DeleteServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.DeleteServingConfigRequest): + request = serving_config_service.DeleteServingConfigRequest(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_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_serving_config(self, + request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, + *, + serving_config: gcr_serving_config.ServingConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Updates a ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_update_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = client.update_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.UpdateServingConfigRequest, dict]): + The request object. Request for UpdateServingConfig + method. + serving_config (google.cloud.retail_v2beta.types.ServingConfig): + Required. The ServingConfig to + update. + + This corresponds to the ``serving_config`` 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 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] + + If not set, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.UpdateServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.UpdateServingConfigRequest): + request = serving_config_service.UpdateServingConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config.name", request.serving_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_serving_config(self, + request: Union[serving_config_service.GetServingConfigRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> serving_config.ServingConfig: + r"""Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_get_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_serving_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.GetServingConfigRequest, dict]): + The request object. Request for GetServingConfig method. + name (str): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.GetServingConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.GetServingConfigRequest): + request = serving_config_service.GetServingConfigRequest(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_serving_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_serving_configs(self, + request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServingConfigsPager: + r"""Lists all ServingConfigs linked to this catalog. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_list_serving_configs(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ListServingConfigsRequest, dict]): + The request object. Request for ListServingConfigs + method. + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsPager: + Response for ListServingConfigs + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.ListServingConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.ListServingConfigsRequest): + request = serving_config_service.ListServingConfigsRequest(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_serving_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListServingConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_control(self, + request: Union[serving_config_service.AddControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_add_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.add_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.AddControlRequest, dict]): + The request object. Request for AddControl method. + serving_config (str): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.AddControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.AddControlRequest): + request = serving_config_service.AddControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_control(self, + request: Union[serving_config_service.RemoveControlRequest, dict] = None, + *, + serving_config: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_serving_config.ServingConfig: + r"""Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_remove_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.remove_control(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RemoveControlRequest, dict]): + The request object. Request for RemoveControl method. + serving_config (str): + Required. The source ServingConfig resource name . + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + + This corresponds to the ``serving_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.ServingConfig: + Configures metadata that is used to generate serving time results (e.g. + search results or recommendation predictions). The + ServingConfig is passed in the search and predict + request and together with the Catalog.default_branch, + generates results. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([serving_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a serving_config_service.RemoveControlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, serving_config_service.RemoveControlRequest): + request = serving_config_service.RemoveControlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if serving_config is not None: + request.serving_config = serving_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_control] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServingConfigServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py new file mode 100644 index 00000000..a45bf88c --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config_service + + +class ListServingConfigsPager: + """A pager for iterating through ``list_serving_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``serving_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServingConfigs`` requests and continue to iterate + through the ``serving_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` + 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[..., serving_config_service.ListServingConfigsResponse], + request: serving_config_service.ListServingConfigsRequest, + response: serving_config_service.ListServingConfigsResponse, + *, + 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.retail_v2beta.types.ListServingConfigsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListServingConfigsResponse): + 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 = serving_config_service.ListServingConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[serving_config_service.ListServingConfigsResponse]: + 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[serving_config.ServingConfig]: + for page in self.pages: + yield from page.serving_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServingConfigsAsyncPager: + """A pager for iterating through ``list_serving_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``serving_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServingConfigs`` requests and continue to iterate + through the ``serving_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` + 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[serving_config_service.ListServingConfigsResponse]], + request: serving_config_service.ListServingConfigsRequest, + response: serving_config_service.ListServingConfigsResponse, + *, + 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.retail_v2beta.types.ListServingConfigsRequest): + The initial request object. + response (google.cloud.retail_v2beta.types.ListServingConfigsResponse): + 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 = serving_config_service.ListServingConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[serving_config_service.ListServingConfigsResponse]: + 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[serving_config.ServingConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.serving_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py new file mode 100644 index 00000000..3726ac83 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ServingConfigServiceTransport +from .grpc import ServingConfigServiceGrpcTransport +from .grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ServingConfigServiceTransport]] +_transport_registry['grpc'] = ServingConfigServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ServingConfigServiceGrpcAsyncIOTransport + +__all__ = ( + 'ServingConfigServiceTransport', + 'ServingConfigServiceGrpcTransport', + 'ServingConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py new file mode 100644 index 00000000..b8fc6e2b --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ServingConfigServiceTransport(abc.ABC): + """Abstract transport class for ServingConfigService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_serving_config: gapic_v1.method.wrap_method( + self.create_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_serving_config: gapic_v1.method.wrap_method( + self.delete_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.update_serving_config: gapic_v1.method.wrap_method( + self.update_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.get_serving_config: gapic_v1.method.wrap_method( + self.get_serving_config, + default_timeout=None, + client_info=client_info, + ), + self.list_serving_configs: gapic_v1.method.wrap_method( + self.list_serving_configs, + default_timeout=None, + client_info=client_info, + ), + self.add_control: gapic_v1.method.wrap_method( + self.add_control, + default_timeout=None, + client_info=client_info, + ), + self.remove_control: gapic_v1.method.wrap_method( + self.remove_control, + 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 create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + Union[ + serving_config.ServingConfig, + Awaitable[serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + Union[ + serving_config_service.ListServingConfigsResponse, + Awaitable[serving_config_service.ListServingConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + Union[ + gcr_serving_config.ServingConfig, + Awaitable[gcr_serving_config.ServingConfig] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ServingConfigServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py new file mode 100644 index 00000000..309a486a --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py @@ -0,0 +1,440 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO + + +class ServingConfigServiceGrpcTransport(ServingConfigServiceTransport): + """gRPC backend transport for ServingConfigService. + + Service for modifying ServingConfig. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the create serving config method over gRPC. + + Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + Returns: + Callable[[~.CreateServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/CreateServingConfig', + request_serializer=serving_config_service.CreateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['create_serving_config'] + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete serving config method over gRPC. + + Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.DeleteServingConfigRequest], + ~.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_serving_config' not in self._stubs: + self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/DeleteServingConfig', + request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_serving_config'] + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the update serving config method over gRPC. + + Updates a ServingConfig. + + Returns: + Callable[[~.UpdateServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/UpdateServingConfig', + request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['update_serving_config'] + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + serving_config.ServingConfig]: + r"""Return a callable for the get serving config method over gRPC. + + Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.GetServingConfigRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/GetServingConfig', + request_serializer=serving_config_service.GetServingConfigRequest.serialize, + response_deserializer=serving_config.ServingConfig.deserialize, + ) + return self._stubs['get_serving_config'] + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + serving_config_service.ListServingConfigsResponse]: + r"""Return a callable for the list serving configs method over gRPC. + + Lists all ServingConfigs linked to this catalog. + + Returns: + Callable[[~.ListServingConfigsRequest], + ~.ListServingConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: + self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/ListServingConfigs', + request_serializer=serving_config_service.ListServingConfigsRequest.serialize, + response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, + ) + return self._stubs['list_serving_configs'] + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the add control method over gRPC. + + Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + Returns: + Callable[[~.AddControlRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_control' not in self._stubs: + self._stubs['add_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/AddControl', + request_serializer=serving_config_service.AddControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['add_control'] + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + gcr_serving_config.ServingConfig]: + r"""Return a callable for the remove control method over gRPC. + + Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + Returns: + Callable[[~.RemoveControlRequest], + ~.ServingConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_control' not in self._stubs: + self._stubs['remove_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/RemoveControl', + request_serializer=serving_config_service.RemoveControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['remove_control'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ServingConfigServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..3cd75655 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py @@ -0,0 +1,439 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.protobuf import empty_pb2 # type: ignore +from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ServingConfigServiceGrpcTransport + + +class ServingConfigServiceGrpcAsyncIOTransport(ServingConfigServiceTransport): + """gRPC AsyncIO backend transport for ServingConfigService. + + Service for modifying ServingConfig. + + 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 = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_serving_config(self) -> Callable[ + [serving_config_service.CreateServingConfigRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the create serving config method over gRPC. + + Creates a ServingConfig. + + A maximum of 100 + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are + allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], + otherwise a FAILED_PRECONDITION error is returned. + + Returns: + Callable[[~.CreateServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/CreateServingConfig', + request_serializer=serving_config_service.CreateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['create_serving_config'] + + @property + def delete_serving_config(self) -> Callable[ + [serving_config_service.DeleteServingConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete serving config method over gRPC. + + Deletes a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.DeleteServingConfigRequest], + 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_serving_config' not in self._stubs: + self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/DeleteServingConfig', + request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_serving_config'] + + @property + def update_serving_config(self) -> Callable[ + [serving_config_service.UpdateServingConfigRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the update serving config method over gRPC. + + Updates a ServingConfig. + + Returns: + Callable[[~.UpdateServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/UpdateServingConfig', + request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['update_serving_config'] + + @property + def get_serving_config(self) -> Callable[ + [serving_config_service.GetServingConfigRequest], + Awaitable[serving_config.ServingConfig]]: + r"""Return a callable for the get serving config method over gRPC. + + Gets a ServingConfig. + Returns a NotFound error if the ServingConfig does not + exist. + + Returns: + Callable[[~.GetServingConfigRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_config' not in self._stubs: + self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/GetServingConfig', + request_serializer=serving_config_service.GetServingConfigRequest.serialize, + response_deserializer=serving_config.ServingConfig.deserialize, + ) + return self._stubs['get_serving_config'] + + @property + def list_serving_configs(self) -> Callable[ + [serving_config_service.ListServingConfigsRequest], + Awaitable[serving_config_service.ListServingConfigsResponse]]: + r"""Return a callable for the list serving configs method over gRPC. + + Lists all ServingConfigs linked to this catalog. + + Returns: + Callable[[~.ListServingConfigsRequest], + Awaitable[~.ListServingConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: + self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/ListServingConfigs', + request_serializer=serving_config_service.ListServingConfigsRequest.serialize, + response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, + ) + return self._stubs['list_serving_configs'] + + @property + def add_control(self) -> Callable[ + [serving_config_service.AddControlRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the add control method over gRPC. + + Enables a Control on the specified ServingConfig. The control is + added in the last position of the list of controls it belongs to + (e.g. if it's a facet spec control it will be applied in the + last position of servingConfig.facetSpecIds) Returns a + ALREADY_EXISTS error if the control has already been applied. + Returns a FAILED_PRECONDITION error if the addition could exceed + maximum number of control allowed for that type of control. + + Returns: + Callable[[~.AddControlRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_control' not in self._stubs: + self._stubs['add_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/AddControl', + request_serializer=serving_config_service.AddControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['add_control'] + + @property + def remove_control(self) -> Callable[ + [serving_config_service.RemoveControlRequest], + Awaitable[gcr_serving_config.ServingConfig]]: + r"""Return a callable for the remove control method over gRPC. + + Disables a Control on the specified ServingConfig. The control + is removed from the ServingConfig. Returns a NOT_FOUND error if + the Control is not enabled for the ServingConfig. + + Returns: + Callable[[~.RemoveControlRequest], + Awaitable[~.ServingConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_control' not in self._stubs: + self._stubs['remove_control'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.ServingConfigService/RemoveControl', + request_serializer=serving_config_service.RemoveControlRequest.serialize, + response_deserializer=gcr_serving_config.ServingConfig.deserialize, + ) + return self._stubs['remove_control'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ServingConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py new file mode 100644 index 00000000..5f5171c1 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py new file mode 100644 index 00000000..24cdc934 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py @@ -0,0 +1,730 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on the customer + website. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(UserEventServiceClient.catalog_path) + parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) + product_path = staticmethod(UserEventServiceClient.product_path) + parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_write_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_collect_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_purge_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_import_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2beta.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + async def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2beta + + async def sample_rejoin_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py new file mode 100644 index 00000000..a57e4e27 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py @@ -0,0 +1,930 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[UserEventServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on the customer + website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "retail.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def write_user_event(self, + request: Union[user_event_service.WriteUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_write_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.retail_v2beta.types.UserEvent: + UserEvent captures all metadata + information Retail API needs to know + about how end users interact with + customers' website. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Union[user_event_service.CollectUserEventRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_collect_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events(self, + request: Union[purge_config.PurgeUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_purge_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeUserEventsRequest): + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeMetadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Union[import_config.ImportUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_import_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2beta.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportMetadata, + ) + + # Done; return the response. + return response + + def rejoin_user_events(self, + request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + .. code-block:: python + + from google.cloud import retail_v2beta + + def sample_rejoin_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.retail_v2beta.types.RejoinUserEventsRequest, dict]): + The request object. Request message for RejoinUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.retail_v2beta.types.RejoinUserEventsResponse` + Response message for RejoinUserEvents method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.RejoinUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.RejoinUserEventsRequest): + request = user_event_service.RejoinUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + user_event_service.RejoinUserEventsResponse, + metadata_type=user_event_service.RejoinUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-retail", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py new file mode 100644 index 00000000..f53ee5d7 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py new file mode 100644 index 00000000..bf9e4cfe --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py @@ -0,0 +1,235 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-retail', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'retail.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.rejoin_user_events: gapic_v1.method.wrap_method( + self.rejoin_user_events, + 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 write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + user_event.UserEvent, + Awaitable[user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py new file mode 100644 index 00000000..098839e0 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..7fbcb123 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'retail.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Retail API JavaScript + pixel and Google Tag Manager. Users should not call this + method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + @property + def rejoin_user_events(self) -> Callable[ + [user_event_service.RejoinUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the rejoin user events method over gRPC. + + Starts a user event rejoin operation with latest + product catalog. Events will not be annotated with + detailed product information if product is missing from + the catalog at the time the user event is ingested, and + these events are stored as unjoined events with a + limited usage on training and serving. This method can + be used to start a join operation on specified events + with latest version of product catalog. It can also be + used to correct events joined with the wrong product + catalog. A rejoin operation can take hours or days to + complete. + + Returns: + Callable[[~.RejoinUserEventsRequest], + 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 'rejoin_user_events' not in self._stubs: + self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.retail.v2beta.UserEventService/RejoinUserEvents', + request_serializer=user_event_service.RejoinUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rejoin_user_events'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py new file mode 100644 index 00000000..62477503 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .catalog import ( + AttributesConfig, + Catalog, + CatalogAttribute, + CompletionConfig, + MerchantCenterLink, + MerchantCenterLinkingConfig, + ProductLevelConfig, +) +from .catalog_service import ( + AddCatalogAttributeRequest, + GetAttributesConfigRequest, + GetCompletionConfigRequest, + GetDefaultBranchRequest, + GetDefaultBranchResponse, + ListCatalogsRequest, + ListCatalogsResponse, + RemoveCatalogAttributeRequest, + ReplaceCatalogAttributeRequest, + SetDefaultBranchRequest, + UpdateAttributesConfigRequest, + UpdateCatalogRequest, + UpdateCompletionConfigRequest, +) +from .common import ( + Audience, + ColorInfo, + Condition, + CustomAttribute, + FulfillmentInfo, + Image, + Interval, + LocalInventory, + PriceInfo, + Rating, + Rule, + UserInfo, + AttributeConfigLevel, + SearchSolutionUseCase, + SolutionType, +) +from .completion_service import ( + CompleteQueryRequest, + CompleteQueryResponse, +) +from .control import ( + Control, +) +from .control_service import ( + CreateControlRequest, + DeleteControlRequest, + GetControlRequest, + ListControlsRequest, + ListControlsResponse, + UpdateControlRequest, +) +from .export_config import ( + ExportErrorsConfig, + ExportMetadata, + ExportProductsResponse, + ExportUserEventsResponse, +) +from .import_config import ( + BigQuerySource, + CompletionDataInputConfig, + GcsSource, + ImportCompletionDataRequest, + ImportCompletionDataResponse, + ImportErrorsConfig, + ImportMetadata, + ImportProductsRequest, + ImportProductsResponse, + ImportUserEventsRequest, + ImportUserEventsResponse, + ProductInlineSource, + ProductInputConfig, + UserEventImportSummary, + UserEventInlineSource, + UserEventInputConfig, +) +from .prediction_service import ( + PredictRequest, + PredictResponse, +) +from .product import ( + Product, +) +from .product_service import ( + AddFulfillmentPlacesMetadata, + AddFulfillmentPlacesRequest, + AddFulfillmentPlacesResponse, + AddLocalInventoriesMetadata, + AddLocalInventoriesRequest, + AddLocalInventoriesResponse, + CreateProductRequest, + DeleteProductRequest, + GetProductRequest, + ListProductsRequest, + ListProductsResponse, + RemoveFulfillmentPlacesMetadata, + RemoveFulfillmentPlacesRequest, + RemoveFulfillmentPlacesResponse, + RemoveLocalInventoriesMetadata, + RemoveLocalInventoriesRequest, + RemoveLocalInventoriesResponse, + SetInventoryMetadata, + SetInventoryRequest, + SetInventoryResponse, + UpdateProductRequest, +) +from .promotion import ( + Promotion, +) +from .purge_config import ( + PurgeMetadata, + PurgeUserEventsRequest, + PurgeUserEventsResponse, +) +from .search_service import ( + SearchRequest, + SearchResponse, +) +from .serving_config import ( + ServingConfig, +) +from .serving_config_service import ( + AddControlRequest, + CreateServingConfigRequest, + DeleteServingConfigRequest, + GetServingConfigRequest, + ListServingConfigsRequest, + ListServingConfigsResponse, + RemoveControlRequest, + UpdateServingConfigRequest, +) +from .user_event import ( + CompletionDetail, + ProductDetail, + PurchaseTransaction, + UserEvent, +) +from .user_event_service import ( + CollectUserEventRequest, + RejoinUserEventsMetadata, + RejoinUserEventsRequest, + RejoinUserEventsResponse, + WriteUserEventRequest, +) + +__all__ = ( + 'AttributesConfig', + 'Catalog', + 'CatalogAttribute', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'ProductLevelConfig', + 'AddCatalogAttributeRequest', + 'GetAttributesConfigRequest', + 'GetCompletionConfigRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + 'SetDefaultBranchRequest', + 'UpdateAttributesConfigRequest', + 'UpdateCatalogRequest', + 'UpdateCompletionConfigRequest', + 'Audience', + 'ColorInfo', + 'Condition', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'LocalInventory', + 'PriceInfo', + 'Rating', + 'Rule', + 'UserInfo', + 'AttributeConfigLevel', + 'SearchSolutionUseCase', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Control', + 'CreateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + 'UpdateControlRequest', + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + 'BigQuerySource', + 'CompletionDataInputConfig', + 'GcsSource', + 'ImportCompletionDataRequest', + 'ImportCompletionDataResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportProductsRequest', + 'ImportProductsResponse', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ProductInlineSource', + 'ProductInputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'UserEventInputConfig', + 'PredictRequest', + 'PredictResponse', + 'Product', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesResponse', + 'CreateProductRequest', + 'DeleteProductRequest', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesResponse', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesResponse', + 'SetInventoryMetadata', + 'SetInventoryRequest', + 'SetInventoryResponse', + 'UpdateProductRequest', + 'Promotion', + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'SearchRequest', + 'SearchResponse', + 'ServingConfig', + 'AddControlRequest', + 'CreateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'RemoveControlRequest', + 'UpdateServingConfigRequest', + 'CompletionDetail', + 'ProductDetail', + 'PurchaseTransaction', + 'UserEvent', + 'CollectUserEventRequest', + 'RejoinUserEventsMetadata', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py new file mode 100644 index 00000000..8398213f --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py @@ -0,0 +1,528 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'ProductLevelConfig', + 'CatalogAttribute', + 'AttributesConfig', + 'CompletionConfig', + 'MerchantCenterLink', + 'MerchantCenterLinkingConfig', + 'Catalog', + }, +) + + +class ProductLevelConfig(proto.Message): + r"""Configures what level the product should be uploaded with + regards to how users will be send events and how predictions + will be made. + + Attributes: + ingestion_product_type (str): + The type of [Product][google.cloud.retail.v2beta.Product]s + allowed to be ingested into the catalog. Acceptable values + are: + + - ``primary`` (default): You can ingest + [Product][google.cloud.retail.v2beta.Product]s of all + types. When ingesting a + [Product][google.cloud.retail.v2beta.Product], its type + will default to + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + if unset. + - ``variant``: You can only ingest + [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s. This + means + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] + cannot be empty. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``variant`` and + [merchant_center_product_id_field][google.cloud.retail.v2beta.ProductLevelConfig.merchant_center_product_id_field] + is ``itemGroupId``, an INVALID_ARGUMENT error is returned. + + See `Using product + levels `__ + for more details. + merchant_center_product_id_field (str): + Which field of `Merchant Center + Product `__ + should be imported as + [Product.id][google.cloud.retail.v2beta.Product.id]. + Acceptable values are: + + - ``offerId`` (default): Import ``offerId`` as the product + ID. + - ``itemGroupId``: Import ``itemGroupId`` as the product + ID. Notice that Retail API will choose one item from the + ones with the same ``itemGroupId``, and use it to + represent the item group. + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + If this field is ``itemGroupId`` and + [ingestion_product_type][google.cloud.retail.v2beta.ProductLevelConfig.ingestion_product_type] + is ``variant``, an INVALID_ARGUMENT error is returned. + + See `Using product + levels `__ + for more details. + """ + + ingestion_product_type = proto.Field( + proto.STRING, + number=1, + ) + merchant_center_product_id_field = proto.Field( + proto.STRING, + number=2, + ) + + +class CatalogAttribute(proto.Message): + r"""Catalog level attribute config for an attribute. For example, + if customers want to enable/disable facet for a specific + attribute. + + Attributes: + key (str): + Required. Attribute name. For example: ``color``, + ``brands``, ``attributes.custom_attribute``, such as + ``attributes.xyz``. + in_use (bool): + Output only. Indicates whether this attribute has been used + by any products. ``True`` if at least one + [Product][google.cloud.retail.v2beta.Product] is using this + attribute in + [Product.attributes][google.cloud.retail.v2beta.Product.attributes]. + Otherwise, this field is ``False``. + + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + can be pre-loaded by using [AddCatalogAttribute][], + [ImportCatalogAttributes][], or [UpdateAttributesConfig][] + APIs. This field is ``False`` for pre-loaded + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s. + + Only + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s + that are not in use by products can be deleted. + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s + that are in use by products cannot be deleted; however, + their configuration properties will reset to default values + upon removal request. + + After catalog changes, it takes about 10 minutes for this + field to update. + type_ (google.cloud.retail_v2beta.types.CatalogAttribute.AttributeType): + Output only. The type of this attribute. This is derived + from the attribute in + [Product.attributes][google.cloud.retail.v2beta.Product.attributes]. + indexable_option (google.cloud.retail_v2beta.types.CatalogAttribute.IndexableOption): + When + [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] + is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if INDEXABLE_ENABLED + attribute values are indexed so that it can be filtered, + faceted, or boosted in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + dynamic_facetable_option (google.cloud.retail_v2beta.types.CatalogAttribute.DynamicFacetableOption): + If DYNAMIC_FACETABLE_ENABLED, attribute values are available + for dynamic facet. Could only be DYNAMIC_FACETABLE_DISABLED + if + [CatalogAttribute.indexable_option][google.cloud.retail.v2beta.CatalogAttribute.indexable_option] + is INDEXABLE_DISABLED. Otherwise, an INVALID_ARGUMENT error + is returned. + searchable_option (google.cloud.retail_v2beta.types.CatalogAttribute.SearchableOption): + When + [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] + is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if SEARCHABLE_ENABLED, + attribute values are searchable by text queries in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + If SEARCHABLE_ENABLED but attribute type is numerical, + attribute values will not be searchable by text queries in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], + as there are no text values associated to numerical + attributes. + """ + class AttributeType(proto.Enum): + r"""The type of an attribute.""" + UNKNOWN = 0 + TEXTUAL = 1 + NUMERICAL = 2 + + class IndexableOption(proto.Enum): + r"""The status of the indexable option of a catalog attribute.""" + INDEXABLE_OPTION_UNSPECIFIED = 0 + INDEXABLE_ENABLED = 1 + INDEXABLE_DISABLED = 2 + + class DynamicFacetableOption(proto.Enum): + r"""The status of the dynamic facetable option of a catalog + attribute. + """ + DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 + DYNAMIC_FACETABLE_ENABLED = 1 + DYNAMIC_FACETABLE_DISABLED = 2 + + class SearchableOption(proto.Enum): + r"""The status of the searchable option of a catalog attribute.""" + SEARCHABLE_OPTION_UNSPECIFIED = 0 + SEARCHABLE_ENABLED = 1 + SEARCHABLE_DISABLED = 2 + + key = proto.Field( + proto.STRING, + number=1, + ) + in_use = proto.Field( + proto.BOOL, + number=9, + ) + type_ = proto.Field( + proto.ENUM, + number=10, + enum=AttributeType, + ) + indexable_option = proto.Field( + proto.ENUM, + number=5, + enum=IndexableOption, + ) + dynamic_facetable_option = proto.Field( + proto.ENUM, + number=6, + enum=DynamicFacetableOption, + ) + searchable_option = proto.Field( + proto.ENUM, + number=7, + enum=SearchableOption, + ) + + +class AttributesConfig(proto.Message): + r"""Catalog level attribute config. + + Attributes: + name (str): + Required. Immutable. The fully qualified resource name of + the attribute config. Format: + ``projects/*/locations/*/catalogs/*/attributesConfig`` + catalog_attributes (Mapping[str, google.cloud.retail_v2beta.types.CatalogAttribute]): + Enable attribute(s) config at catalog level. For example, + indexable, dynamic_facetable, or searchable for each + attribute. + + The key is catalog attribute's name. For example: ``color``, + ``brands``, ``attributes.custom_attribute``, such as + ``attributes.xyz``. + + The maximum number of catalog attributes allowed in a + request is 1000. + attribute_config_level (google.cloud.retail_v2beta.types.AttributeConfigLevel): + Output only. The + [AttributeConfigLevel][google.cloud.retail.v2beta.AttributeConfigLevel] + used for this catalog. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + catalog_attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='CatalogAttribute', + ) + attribute_config_level = proto.Field( + proto.ENUM, + number=3, + enum=common.AttributeConfigLevel, + ) + + +class CompletionConfig(proto.Message): + r"""Catalog level autocomplete config for customers to customize + autocomplete feature's settings. + + Attributes: + name (str): + Required. Immutable. Fully qualified name + ``projects/*/locations/*/catalogs/*/completionConfig`` + matching_order (str): + Specifies the matching order for autocomplete suggestions, + e.g., a query consisting of 'sh' with 'out-of-order' + specified would suggest "women's shoes", whereas a query of + 'red s' with 'exact-prefix' specified would suggest "red + shoes". Currently supported values: + + - 'out-of-order' + - 'exact-prefix' + + Default value: 'exact-prefix'. + max_suggestions (int): + The maximum number of autocomplete + suggestions returned per term. The maximum + allowed max suggestions is 20. Default value is + 20. If left unset or set to 0, then will + fallback to default value. + min_prefix_length (int): + The minimum number of characters needed to be + typed in order to get suggestions. Default value + is 2. If left unset or set to 0, then will + fallback to default value. + auto_learning (bool): + If set to true, the auto learning function is enabled. Auto + learning uses user data to generate suggestions using ML + techniques. Default value is false. Only after enabling auto + learning can users use ``cloud-retail`` data in + [CompleteQueryRequest][google.cloud.retail.v2beta.CompleteQueryRequest]. + suggestions_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the + autocomplete phrases uploaded by the customer. + last_suggestions_import_operation (str): + Output only. Name of the LRO corresponding to the latest + suggestion terms list import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + denylist_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the / + autocomplete denylist phrases uploaded by the + customer. + last_denylist_import_operation (str): + Output only. LRO corresponding to the latest denylist + import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + allowlist_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): + Output only. The input config for the import + of the source data that contains the + autocomplete allowlist phrases uploaded by the + customer. + last_allowlist_import_operation (str): + Output only. LRO corresponding to the latest allowlist + import. + + Can use + [GetOperation][google.longrunning.Operations.GetOperation] + API to retrieve the latest state of the Long Running + Operation. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + matching_order = proto.Field( + proto.STRING, + number=2, + ) + max_suggestions = proto.Field( + proto.INT32, + number=3, + ) + min_prefix_length = proto.Field( + proto.INT32, + number=4, + ) + auto_learning = proto.Field( + proto.BOOL, + number=11, + ) + suggestions_input_config = proto.Field( + proto.MESSAGE, + number=5, + message=import_config.CompletionDataInputConfig, + ) + last_suggestions_import_operation = proto.Field( + proto.STRING, + number=6, + ) + denylist_input_config = proto.Field( + proto.MESSAGE, + number=7, + message=import_config.CompletionDataInputConfig, + ) + last_denylist_import_operation = proto.Field( + proto.STRING, + number=8, + ) + allowlist_input_config = proto.Field( + proto.MESSAGE, + number=9, + message=import_config.CompletionDataInputConfig, + ) + last_allowlist_import_operation = proto.Field( + proto.STRING, + number=10, + ) + + +class MerchantCenterLink(proto.Message): + r"""Represents a link between a Merchant Center account and a + branch. Once a link is established, products from the linked + merchant center account will be streamed to the linked branch. + + Attributes: + merchant_center_account_id (int): + Required. The linked `Merchant center account + id `__. + The account must be a standalone account or a sub-account of + a MCA. + branch_id (str): + The branch id (e.g. 0/1/2) within this catalog that products + from merchant_center_account_id are streamed to. When + updating this field, an empty value will use the currently + configured default branch. However, changing the default + branch later on won't change the linked branch here. + + A single branch id can only have one linked merchant center + account id. + destinations (Sequence[str]): + String representing the destination to import for, all if + left empty. List of possible values can be found here. + [https://support.google.com/merchants/answer/7501026] List + of allowed string values: "Shopping_ads", + "Buy_on_google_listings", "Display_ads", "Local_inventory + \_ads", "Free_listings", "Free_local_listings" NOTE: The + string values are case sensitive. + region_code (str): + Region code of offers to accept. 2-letter Uppercase ISO + 3166-1 alpha-2 code. List of values can be found + `here `__ + under the ``region`` tag. If left blank no region filtering + will be performed. + + Example value: ``US``. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. ISO + 639-1. + + This specifies the language of offers in Merchant Center + that will be accepted. If empty no language filtering will + be performed. + + Example value: ``en``. + """ + + merchant_center_account_id = proto.Field( + proto.INT64, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + destinations = proto.RepeatedField( + proto.STRING, + number=3, + ) + region_code = proto.Field( + proto.STRING, + number=4, + ) + language_code = proto.Field( + proto.STRING, + number=5, + ) + + +class MerchantCenterLinkingConfig(proto.Message): + r"""Configures Merchant Center linking. + Links contained in the config will be used to sync data from a + Merchant Center account to a Cloud Retail branch. + + Attributes: + links (Sequence[google.cloud.retail_v2beta.types.MerchantCenterLink]): + Links between Merchant Center accounts and + branches. + """ + + links = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MerchantCenterLink', + ) + + +class Catalog(proto.Message): + r"""The catalog configuration. + + Attributes: + name (str): + Required. Immutable. The fully qualified + resource name of the catalog. + display_name (str): + Required. Immutable. The catalog display name. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + product_level_config (google.cloud.retail_v2beta.types.ProductLevelConfig): + Required. The product level configuration. + merchant_center_linking_config (google.cloud.retail_v2beta.types.MerchantCenterLinkingConfig): + The Merchant Center linking configuration. + Once a link is added, the data stream from + Merchant Center to Cloud Retail will be enabled + automatically. The requester must have access to + the merchant center account in order to make + changes to this field. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + product_level_config = proto.Field( + proto.MESSAGE, + number=4, + message='ProductLevelConfig', + ) + merchant_center_linking_config = proto.Field( + proto.MESSAGE, + number=6, + message='MerchantCenterLinkingConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py new file mode 100644 index 00000000..c49ba005 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py @@ -0,0 +1,453 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'ListCatalogsRequest', + 'ListCatalogsResponse', + 'UpdateCatalogRequest', + 'SetDefaultBranchRequest', + 'GetDefaultBranchRequest', + 'GetDefaultBranchResponse', + 'GetCompletionConfigRequest', + 'UpdateCompletionConfigRequest', + 'GetAttributesConfigRequest', + 'UpdateAttributesConfigRequest', + 'AddCatalogAttributeRequest', + 'RemoveCatalogAttributeRequest', + 'ReplaceCatalogAttributeRequest', + }, +) + + +class ListCatalogsRequest(proto.Message): + r"""Request for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + + Attributes: + parent (str): + Required. The account resource name with an associated + location. + + If the caller does not have permission to list + [Catalog][google.cloud.retail.v2beta.Catalog]s under this + location, regardless of whether or not this location exists, + a PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [Catalog][google.cloud.retail.v2beta.Catalog]s to return. If + unspecified, defaults to 50. The maximum allowed value is + 1000. Values above 1000 will be coerced to 1000. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [ListCatalogsResponse.next_page_token][google.cloud.retail.v2beta.ListCatalogsResponse.next_page_token], + received from a previous + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCatalogsResponse(proto.Message): + r"""Response for + [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] + method. + + Attributes: + catalogs (Sequence[google.cloud.retail_v2beta.types.Catalog]): + All the customer's + [Catalog][google.cloud.retail.v2beta.Catalog]s. + next_page_token (str): + A token that can be sent as + [ListCatalogsRequest.page_token][google.cloud.retail.v2beta.ListCatalogsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + catalogs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateCatalogRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] + method. + + Attributes: + catalog (google.cloud.retail_v2beta.types.Catalog): + Required. The [Catalog][google.cloud.retail.v2beta.Catalog] + to update. + + If the caller does not have permission to update the + [Catalog][google.cloud.retail.v2beta.Catalog], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Catalog][google.cloud.retail.v2beta.Catalog] 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 + [Catalog][google.cloud.retail.v2beta.Catalog] to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + catalog = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.Catalog, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class SetDefaultBranchRequest(proto.Message): + r"""Request message to set a specified branch as new default_branch. + + Attributes: + catalog (str): + Full resource name of the catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + branch_id (str): + The final component of the resource name of a branch. + + This field must be one of "0", "1" or "2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If there are no sufficient active products in the targeted + branch and + [force][google.cloud.retail.v2beta.SetDefaultBranchRequest.force] + is not set, a FAILED_PRECONDITION error is returned. + note (str): + Some note on this request, this can be retrieved by + [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch] + before next valid default branch set occurs. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + force (bool): + If set to true, it permits switching to a branch with + [branch_id][google.cloud.retail.v2beta.SetDefaultBranchRequest.branch_id] + even if it has no sufficient active products. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + branch_id = proto.Field( + proto.STRING, + number=2, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + force = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetDefaultBranchRequest(proto.Message): + r"""Request message to show which branch is currently the default + branch. + + Attributes: + catalog (str): + The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDefaultBranchResponse(proto.Message): + r"""Response message of + [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. + + Attributes: + branch (str): + Full resource name of the branch id currently + set as default branch. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when this branch is set to default. + note (str): + This corresponds to + [SetDefaultBranchRequest.note][google.cloud.retail.v2beta.SetDefaultBranchRequest.note] + field, when this branch was set as default. + """ + + branch = proto.Field( + proto.STRING, + number=1, + ) + set_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + note = proto.Field( + proto.STRING, + number=3, + ) + + +class GetCompletionConfigRequest(proto.Message): + r"""Request for + [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] + method. + + Attributes: + name (str): + Required. Full CompletionConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateCompletionConfigRequest(proto.Message): + r"""Request for + [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] + method. + + Attributes: + completion_config (google.cloud.retail_v2beta.types.CompletionConfig): + Required. The + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. + + If the caller does not have permission to update the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], + then a PERMISSION_DENIED error is returned. + + If the + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + 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 + [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] + to update. The following are the only supported fields: + + - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] + - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] + - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] + - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] + + If not set, all supported fields are updated. + """ + + completion_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.CompletionConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetAttributesConfigRequest(proto.Message): + r"""Request for + [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] + method. + + Attributes: + name (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAttributesConfigRequest(proto.Message): + r"""Request for + [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] + method. + + Attributes: + attributes_config (google.cloud.retail_v2beta.types.AttributesConfig): + Required. The + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] + to update. The following is the only supported field: + + - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] + + If not set, all supported fields are updated. + """ + + attributes_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_catalog.AttributesConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class AddCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + catalog_attribute (google.cloud.retail_v2beta.types.CatalogAttribute): + Required. The + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to add. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + catalog_attribute = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_catalog.CatalogAttribute, + ) + + +class RemoveCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + key (str): + Required. The attribute name key of the + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to remove. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + key = proto.Field( + proto.STRING, + number=2, + ) + + +class ReplaceCatalogAttributeRequest(proto.Message): + r"""Request for + [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] + method. + + Attributes: + attributes_config (str): + Required. Full AttributesConfig resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig + catalog_attribute (google.cloud.retail_v2beta.types.CatalogAttribute): + Required. The updated + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + to update. The following are NOT supported: + + - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key] + + If not set, all supported fields are updated. + """ + + attributes_config = proto.Field( + proto.STRING, + number=1, + ) + catalog_attribute = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_catalog.CatalogAttribute, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py new file mode 100644 index 00000000..c40843c0 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py @@ -0,0 +1,1178 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'AttributeConfigLevel', + 'SolutionType', + 'SearchSolutionUseCase', + 'Condition', + 'Rule', + 'Audience', + 'ColorInfo', + 'CustomAttribute', + 'FulfillmentInfo', + 'Image', + 'Interval', + 'PriceInfo', + 'Rating', + 'UserInfo', + 'LocalInventory', + }, +) + + +class AttributeConfigLevel(proto.Enum): + r"""At which level we offer configuration for attributes.""" + ATTRIBUTE_CONFIG_LEVEL_UNSPECIFIED = 0 + PRODUCT_LEVEL_ATTRIBUTE_CONFIG = 1 + CATALOG_LEVEL_ATTRIBUTE_CONFIG = 2 + + +class SolutionType(proto.Enum): + r"""The type of solution.""" + SOLUTION_TYPE_UNSPECIFIED = 0 + SOLUTION_TYPE_RECOMMENDATION = 1 + SOLUTION_TYPE_SEARCH = 2 + + +class SearchSolutionUseCase(proto.Enum): + r"""The use case of Cloud Retail Search.""" + SEARCH_SOLUTION_USE_CASE_UNSPECIFIED = 0 + SEARCH_SOLUTION_USE_CASE_SEARCH = 1 + SEARCH_SOLUTION_USE_CASE_BROWSE = 2 + + +class Condition(proto.Message): + r"""Metadata that is used to define a condition that triggers an action. + A valid condition must specify at least one of 'query_terms' or + 'products_filter'. If multiple fields are specified, the condition + is met if all the fields are satisfied e.g. if a set of query terms + and product_filter are set, then only items matching the + product_filter for requests with a query matching the query terms + wil get boosted. + + Attributes: + query_terms (Sequence[google.cloud.retail_v2beta.types.Condition.QueryTerm]): + A list (up to 10 entries) of terms to match + the query on. If not specified, match all + queries. If many query terms are specified, the + condition is matched if any of the terms is a + match (i.e. using the OR operator). + active_time_range (Sequence[google.cloud.retail_v2beta.types.Condition.TimeRange]): + Range of time(s) specifying when Condition is + active. Condition true if any time range + matches. + """ + + class QueryTerm(proto.Message): + r"""Query terms that we want to match on. + + Attributes: + value (str): + The value of the term to match on. + Value cannot be empty. + Value can have at most 3 terms if specified as a + partial match. Each space separated string is + considered as one term. Example) "a b c" is 3 + terms and allowed, " a b c d" is 4 terms and not + allowed for partial match. + full_match (bool): + Whether this is supposed to be a full or + partial match. + """ + + value = proto.Field( + proto.STRING, + number=1, + ) + full_match = proto.Field( + proto.BOOL, + number=2, + ) + + class TimeRange(proto.Message): + r"""Used for time-dependent conditions. + Example: Want to have rule applied for week long sale. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start of time range. Range is inclusive. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End of time range. Range is inclusive. + """ + + start_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + query_terms = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=QueryTerm, + ) + active_time_range = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TimeRange, + ) + + +class Rule(proto.Message): + r"""A rule is a condition-action pair + + - A condition defines when a rule is to be triggered. + - An action specifies what occurs on that trigger. Currently only + boost rules are supported. Currently only supported by the search + endpoint. + + 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: + boost_action (google.cloud.retail_v2beta.types.Rule.BoostAction): + A boost action. + + This field is a member of `oneof`_ ``action``. + redirect_action (google.cloud.retail_v2beta.types.Rule.RedirectAction): + Redirects a shopper to a specific page. + + This field is a member of `oneof`_ ``action``. + oneway_synonyms_action (google.cloud.retail_v2beta.types.Rule.OnewaySynonymsAction): + Treats specific term as a synonym with a + group of terms. Group of terms will not be + treated as synonyms with the specific term. + + This field is a member of `oneof`_ ``action``. + do_not_associate_action (google.cloud.retail_v2beta.types.Rule.DoNotAssociateAction): + Prevents term from being associated with + other terms. + + This field is a member of `oneof`_ ``action``. + replacement_action (google.cloud.retail_v2beta.types.Rule.ReplacementAction): + Replaces specific terms in the query. + + This field is a member of `oneof`_ ``action``. + ignore_action (google.cloud.retail_v2beta.types.Rule.IgnoreAction): + Ignores specific terms from query during + search. + + This field is a member of `oneof`_ ``action``. + filter_action (google.cloud.retail_v2beta.types.Rule.FilterAction): + Filters results. + + This field is a member of `oneof`_ ``action``. + twoway_synonyms_action (google.cloud.retail_v2beta.types.Rule.TwowaySynonymsAction): + Treats a set of terms as synonyms of one + another. + + This field is a member of `oneof`_ ``action``. + condition (google.cloud.retail_v2beta.types.Condition): + Required. The condition that triggers the + rule. If the condition is empty, the rule will + always apply. + """ + + class BoostAction(proto.Message): + r"""A boost action to apply to results matching condition + specified above. + + Attributes: + boost (float): + Strength of the condition boost, which must be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + products_filter (str): + The filter can have a max size of 5000 characters. An + expression which specifies which products to apply an action + to. The syntax and supported fields are the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": *(id: + ANY("product_1", "product_2"))* *AND* *(colorFamilies: + ANY("Red", "Blue"))* + """ + + boost = proto.Field( + proto.FLOAT, + number=1, + ) + products_filter = proto.Field( + proto.STRING, + number=2, + ) + + class FilterAction(proto.Message): + r"""- Rule Condition: + + - No [Condition][query_terms] provided is a global match. + - 1 or more [Condition][query_terms] provided is combined with + OR operator. + + - Action Input: The request query and filter that will be applied + to the retrieved products, in addition to any filters already + provided with the SearchRequest. The AND operator is used to + combine the query's existing filters with the filter rule(s). + NOTE: May result in 0 results when filters conflict. + - Action Result: Filters the returned objects to be ONLY those that + passed the filter. + + Attributes: + filter (str): + A filter to apply on the matching condition results. + Supported features: + + - [filter][google.cloud.retail.v2beta.Rule.FilterAction.filter] + must be set. + - Filter syntax is identical to + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter]. + See more details at the Retail Search `user + guide `__. + - To filter products with product ID "product_1" or + "product_2", and color "Red" or "Blue": *(id: + ANY("product_1", "product_2"))* *AND* *(colorFamilies: + ANY("Red", "Blue"))* + """ + + filter = proto.Field( + proto.STRING, + number=1, + ) + + class RedirectAction(proto.Message): + r"""Redirects a shopper to a specific page. + + - Rule Condition: + + - Must specify [Condition][query_terms]. + + - Action Input: Request Query + - Action Result: Redirects shopper to provided uri. + + Attributes: + redirect_uri (str): + URL must have length equal or less than 2000 + characters. + """ + + redirect_uri = proto.Field( + proto.STRING, + number=1, + ) + + class TwowaySynonymsAction(proto.Message): + r"""Creates a set of terms that will be treated as synonyms of each + other. Example: synonyms of "sneakers" and "shoes". + + - "sneakers" will use a synonym of "shoes". + - "shoes" will use a synonym of "sneakers". + + Attributes: + synonyms (Sequence[str]): + Defines a set of synonyms. + Can specify up to 100 synonyms. + Must specify at least 2 synonyms. + """ + + synonyms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class OnewaySynonymsAction(proto.Message): + r"""Maps a set of terms to a set of synonyms. Set of synonyms will be + treated as synonyms of each query term only. ``query_terms`` will + not be treated as synonyms of each other. Example: "sneakers" will + use a synonym of "shoes". "shoes" will not use a synonym of + "sneakers". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. + Will treat synonyms as their synonyms. + Not themselves synonyms of the synonyms. + Can specify up to 100 terms. + synonyms (Sequence[str]): + Defines a set of synonyms. + Cannot contain duplicates. + Can specify up to 100 synonyms. + oneway_terms (Sequence[str]): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=3, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=4, + ) + oneway_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class DoNotAssociateAction(proto.Message): + r"""Prevents ``query_term`` from being associated with specified terms + during search. Example: Don't associate "gShoe" and "cheap". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. Will not consider + do_not_associate_terms for search if in search query. Can + specify up to 100 terms. + do_not_associate_terms (Sequence[str]): + Cannot contain duplicates or the query term. + Can specify up to 100 terms. + terms (Sequence[str]): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + do_not_associate_terms = proto.RepeatedField( + proto.STRING, + number=3, + ) + terms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class ReplacementAction(proto.Message): + r"""Replaces a term in the query. Multiple replacement candidates can be + specified. All ``query_terms`` will be replaced with the replacement + term. Example: Replace "gShoe" with "google shoe". + + Attributes: + query_terms (Sequence[str]): + Terms from the search query. + Will be replaced by replacement term. + Can specify up to 100 terms. + replacement_term (str): + Term that will be used for replacement. + term (str): + Will be [deprecated = true] post migration; + """ + + query_terms = proto.RepeatedField( + proto.STRING, + number=2, + ) + replacement_term = proto.Field( + proto.STRING, + number=3, + ) + term = proto.Field( + proto.STRING, + number=1, + ) + + class IgnoreAction(proto.Message): + r"""Prevents a term in the query from being used in search. + Example: Don't search for "shoddy". + + Attributes: + ignore_terms (Sequence[str]): + Terms to ignore in the search query. + """ + + ignore_terms = proto.RepeatedField( + proto.STRING, + number=1, + ) + + boost_action = proto.Field( + proto.MESSAGE, + number=2, + oneof='action', + message=BoostAction, + ) + redirect_action = proto.Field( + proto.MESSAGE, + number=3, + oneof='action', + message=RedirectAction, + ) + oneway_synonyms_action = proto.Field( + proto.MESSAGE, + number=6, + oneof='action', + message=OnewaySynonymsAction, + ) + do_not_associate_action = proto.Field( + proto.MESSAGE, + number=7, + oneof='action', + message=DoNotAssociateAction, + ) + replacement_action = proto.Field( + proto.MESSAGE, + number=8, + oneof='action', + message=ReplacementAction, + ) + ignore_action = proto.Field( + proto.MESSAGE, + number=9, + oneof='action', + message=IgnoreAction, + ) + filter_action = proto.Field( + proto.MESSAGE, + number=10, + oneof='action', + message=FilterAction, + ) + twoway_synonyms_action = proto.Field( + proto.MESSAGE, + number=11, + oneof='action', + message=TwowaySynonymsAction, + ) + condition = proto.Field( + proto.MESSAGE, + number=1, + message='Condition', + ) + + +class Audience(proto.Message): + r"""An intended audience of the + [Product][google.cloud.retail.v2beta.Product] for whom it's sold. + + Attributes: + genders (Sequence[str]): + The genders of the audience. Strongly encouraged to use the + standard values: "male", "female", "unisex". + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `gender `__. + Schema.org property + `Product.audience.suggestedGender `__. + age_groups (Sequence[str]): + The age groups of the audience. Strongly encouraged to use + the standard values: "newborn" (up to 3 months old), + "infant" (3–12 months old), "toddler" (1–5 years old), + "kids" (5–13 years old), "adult" (typically teens or older). + + At most 5 values are allowed. Each value must be a UTF-8 + encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `age_group `__. + Schema.org property + `Product.audience.suggestedMinAge `__ + and + `Product.audience.suggestedMaxAge `__. + """ + + genders = proto.RepeatedField( + proto.STRING, + number=1, + ) + age_groups = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class ColorInfo(proto.Message): + r"""The color information of a + [Product][google.cloud.retail.v2beta.Product]. + + Attributes: + color_families (Sequence[str]): + The standard color families. Strongly recommended to use the + following standard color groups: "Red", "Pink", "Orange", + "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", + "White", "Gray", "Black" and "Mixed". Normally it is + expected to have only 1 color family. May consider using + single "Mixed" instead of multiple values. + + A maximum of 5 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + colors (Sequence[str]): + The color display names, which may be different from + standard color family names, such as the color aliases used + in the website frontend. Normally it is expected to have + only 1 color. May consider using single "Mixed" instead of + multiple values. + + A maximum of 25 colors are allowed. Each value must be a + UTF-8 encoded string with a length limit of 128 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + """ + + color_families = proto.RepeatedField( + proto.STRING, + number=1, + ) + colors = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in + [Product][google.cloud.retail.v2beta.Product]. + + Attributes: + text (Sequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an INVALID_ARGUMENT + error is returned. + + Exactly one of + [text][google.cloud.retail.v2beta.CustomAttribute.text] or + [numbers][google.cloud.retail.v2beta.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + numbers (Sequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [text][google.cloud.retail.v2beta.CustomAttribute.text] or + [numbers][google.cloud.retail.v2beta.CustomAttribute.numbers] + should be set. Otherwise, an INVALID_ARGUMENT error is + returned. + searchable (bool): + This field will only be used when + [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] + of the [Catalog][google.cloud.retail.v2beta.Catalog] is + 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute + values are searchable by text queries in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2beta.UserEvent]. + + Only set if type + [text][google.cloud.retail.v2beta.CustomAttribute.text] is + set. Otherwise, a INVALID_ARGUMENT error is returned. + + This field is a member of `oneof`_ ``_searchable``. + indexable (bool): + This field will only be used when + [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] + of the [Catalog][google.cloud.retail.v2beta.Catalog] is + 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute + values are indexed, so that it can be filtered, faceted or + boosted in + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + This field is ignored in a + [UserEvent][google.cloud.retail.v2beta.UserEvent]. + + See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter], + [SearchRequest.facet_specs][google.cloud.retail.v2beta.SearchRequest.facet_specs] + and + [SearchRequest.boost_spec][google.cloud.retail.v2beta.SearchRequest.boost_spec] + for more details. + + This field is a member of `oneof`_ ``_indexable``. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + searchable = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + indexable = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + +class FulfillmentInfo(proto.Message): + r"""Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + Attributes: + type_ (str): + The fulfillment type, including commonly used types (such as + pickup in store and same day delivery), and custom types. + Customers have to map custom types to their display names + before rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + place_ids (Sequence[str]): + The IDs for this + [type][google.cloud.retail.v2beta.FulfillmentInfo.type], + such as the store IDs for + [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2beta.FulfillmentInfo.type] + or the region IDs for + [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2beta.FulfillmentInfo.type]. + + A maximum of 3000 values are allowed. Each value must be a + string with a length limit of 30 characters, matching the + pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". + Otherwise, an INVALID_ARGUMENT error is returned. + """ + + type_ = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class Image(proto.Message): + r"""[Product][google.cloud.retail.v2beta.Product] image. Recommendations + AI and Retail Search do not use product images to improve prediction + and search results. However, product images can be returned in + results, and are shown in prediction or search previews in the + console. + + Attributes: + uri (str): + Required. URI of the image. + + This field must be a valid UTF-8 encoded URI with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + height (int): + Height of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + width (int): + Width of the image in number of pixels. + + This field must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + height = proto.Field( + proto.INT32, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + + +class Interval(proto.Message): + r"""A floating point interval. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum = proto.Field( + proto.DOUBLE, + number=1, + oneof='min', + ) + exclusive_minimum = proto.Field( + proto.DOUBLE, + number=2, + oneof='min', + ) + maximum = proto.Field( + proto.DOUBLE, + number=3, + oneof='max', + ) + exclusive_maximum = proto.Field( + proto.DOUBLE, + number=4, + oneof='max', + ) + + +class PriceInfo(proto.Message): + r"""The price information of a + [Product][google.cloud.retail.v2beta.Product]. + + Attributes: + currency_code (str): + The 3-letter currency code defined in `ISO + 4217 `__. + + If this field is an unrecognizable currency code, an + INVALID_ARGUMENT error is returned. + + The + [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s with the same + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] + must share the same + [currency_code][google.cloud.retail.v2beta.PriceInfo.currency_code]. + Otherwise, a FAILED_PRECONDITION error is returned. + price (float): + Price of the product. + + Google Merchant Center property + `price `__. + Schema.org property + `Offer.price `__. + original_price (float): + Price of the product without any discount. If zero, by + default set to be the + [price][google.cloud.retail.v2beta.PriceInfo.price]. + cost (float): + The costs associated with the sale of a particular product. + Used for gross profit reporting. + + - Profit = + [price][google.cloud.retail.v2beta.PriceInfo.price] - + [cost][google.cloud.retail.v2beta.PriceInfo.cost] + + Google Merchant Center property + `cost_of_goods_sold `__. + price_effective_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2beta.PriceInfo.price] starts + to be effective. This can be set as a future timestamp, and + the [price][google.cloud.retail.v2beta.PriceInfo.price] is + only used for search after + [price_effective_time][google.cloud.retail.v2beta.PriceInfo.price_effective_time]. + If so, the + [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + is used before + [price_effective_time][google.cloud.retail.v2beta.PriceInfo.price_effective_time]. + + Do not set if + [price][google.cloud.retail.v2beta.PriceInfo.price] is + always effective because it will cause additional latency + during search. + price_expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the + [price][google.cloud.retail.v2beta.PriceInfo.price] stops to + be effective. The + [price][google.cloud.retail.v2beta.PriceInfo.price] is used + for search before + [price_expire_time][google.cloud.retail.v2beta.PriceInfo.price_expire_time]. + If this field is set, the + [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + must be set and + [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + is used after + [price_expire_time][google.cloud.retail.v2beta.PriceInfo.price_expire_time]. + + Do not set if + [price][google.cloud.retail.v2beta.PriceInfo.price] is + always effective because it will cause additional latency + during search. + price_range (google.cloud.retail_v2beta.types.PriceInfo.PriceRange): + Output only. The price range of all the child + [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s grouped + together on the + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]. Only + populated for + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct]. + Do not set this field in API requests. + """ + + class PriceRange(proto.Message): + r"""The price range of all + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] having the same + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. + + Attributes: + price (google.cloud.retail_v2beta.types.Interval): + The inclusive + [Product.pricing_info.price][google.cloud.retail.v2beta.PriceInfo.price] + interval of all + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] having the + same + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. + original_price (google.cloud.retail_v2beta.types.Interval): + The inclusive + [Product.pricing_info.original_price][google.cloud.retail.v2beta.PriceInfo.original_price] + internal of all + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] having the + same + [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. + """ + + price = proto.Field( + proto.MESSAGE, + number=1, + message='Interval', + ) + original_price = proto.Field( + proto.MESSAGE, + number=2, + message='Interval', + ) + + currency_code = proto.Field( + proto.STRING, + number=1, + ) + price = proto.Field( + proto.FLOAT, + number=2, + ) + original_price = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + price_effective_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + price_expire_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + price_range = proto.Field( + proto.MESSAGE, + number=7, + message=PriceRange, + ) + + +class Rating(proto.Message): + r"""The rating of a [Product][google.cloud.retail.v2beta.Product]. + + Attributes: + rating_count (int): + The total number of ratings. This value is independent of + the value of + [rating_histogram][google.cloud.retail.v2beta.Rating.rating_histogram]. + + This value must be nonnegative. Otherwise, an + INVALID_ARGUMENT error is returned. + average_rating (float): + The average rating of the + [Product][google.cloud.retail.v2beta.Product]. + + The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT + error is returned. + rating_histogram (Sequence[int]): + List of rating counts per rating value (index = rating - 1). + The list is empty if there is no rating. If the list is + non-empty, its size is always 5. Otherwise, an + INVALID_ARGUMENT error is returned. + + For example, [41, 14, 13, 47, 303]. It means that the + [Product][google.cloud.retail.v2beta.Product] got 41 ratings + with 1 star, 14 ratings with 2 star, and so on. + """ + + rating_count = proto.Field( + proto.INT32, + number=1, + ) + average_rating = proto.Field( + proto.FLOAT, + number=2, + ) + rating_histogram = proto.RepeatedField( + proto.INT32, + number=3, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. + + Always use a hashed value for this ID. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + ip_address (str): + The end user's IP address. This field is used to extract + location information for personalization. + + This field must be either an IPv4 address (e.g. + "104.133.9.80") or an IPv6 address (e.g. + "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an + INVALID_ARGUMENT error is returned. + + This should not be set when: + + - setting + [SearchRequest.user_info][google.cloud.retail.v2beta.SearchRequest.user_info]. + - using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2beta.UserInfo.direct_user_request] + is set. + user_agent (str): + User agent as included in the HTTP header. Required for + getting + [SearchResponse.sponsored_results][google.cloud.retail.v2beta.SearchResponse.sponsored_results]. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent] + or if + [direct_user_request][google.cloud.retail.v2beta.UserInfo.direct_user_request] + is set. + direct_user_request (bool): + True if the request is made directly from the end user, in + which case the + [ip_address][google.cloud.retail.v2beta.UserInfo.ip_address] + and + [user_agent][google.cloud.retail.v2beta.UserInfo.user_agent] + can be populated from the HTTP request. This flag should be + set only if the API request is made directly from the end + user such as a mobile app (and not if a gateway or a server + is processing and pushing the user events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent]. + """ + + user_id = proto.Field( + proto.STRING, + number=1, + ) + ip_address = proto.Field( + proto.STRING, + number=2, + ) + user_agent = proto.Field( + proto.STRING, + number=3, + ) + direct_user_request = proto.Field( + proto.BOOL, + number=4, + ) + + +class LocalInventory(proto.Message): + r"""The inventory information at a place (e.g. a store) + identified by a place ID. + + Attributes: + place_id (str): + The place ID for the current set of inventory + information. + price_info (google.cloud.retail_v2beta.types.PriceInfo): + Product price and cost information. + + Google Merchant Center property + `price `__. + attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): + Additional local inventory attributes, for example, store + name, promotion tags, etc. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - At most 30 attributes are allowed. + - The key must be a UTF-8 encoded string with a length + limit of 32 characters. + - The key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis + or KEY_1_LIKE_THIS. + - The attribute values must be of the same type (text or + number). + - Only 1 value is allowed for each attribute. + - For text values, the length limit is 256 UTF-8 + characters. + - The attribute does not support search. The ``searchable`` + field should be unset or set to false. + - The max summed total bytes of custom attribute keys and + values per product is 5MiB. + fulfillment_types (Sequence[str]): + Input only. Supported fulfillment types. Valid fulfillment + type values include commonly used types (such as pickup in + store and same day delivery), and custom types. Customers + have to map custom types to their display names before + rendering UI. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + All the elements must be distinct. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + place_id = proto.Field( + proto.STRING, + number=1, + ) + price_info = proto.Field( + proto.MESSAGE, + number=2, + message='PriceInfo', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='CustomAttribute', + ) + fulfillment_types = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py new file mode 100644 index 00000000..47e39772 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'CompleteQueryRequest', + 'CompleteQueryResponse', + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Auto-complete parameters. + + Attributes: + catalog (str): + Required. Catalog for which the completion is performed. + + Full resource name of catalog, such as + ``projects/*/locations/global/catalogs/default_catalog``. + query (str): + Required. The query used to generate + suggestions. + The maximum number of allowed characters is 255. + visitor_id (str): + Required field. A unique identifier for tracking visitors. + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + language_codes (Sequence[str]): + The language filters applied to the output suggestions. If + set, it should contain the language of the query. If not + set, suggestions are returned without considering language + restrictions. This is the BCP-47 language code, such as + "en-US" or "sr-Latn". For more information, see `Tags for + Identifying + Languages `__. The + maximum number of language codes is 3. + device_type (str): + The device type context for completion suggestions. It is + useful to apply different suggestions on different device + types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the + suggestions are across all device types. + + Supported formats: + + - ``UNKNOWN_DEVICE_TYPE`` + + - ``DESKTOP`` + + - ``MOBILE`` + + - A customized string starts with ``OTHER_``, e.g. + ``OTHER_IPHONE``. + dataset (str): + Determines which dataset to use for fetching completion. + "user-data" will use the imported dataset through + [CompletionService.ImportCompletionData][google.cloud.retail.v2beta.CompletionService.ImportCompletionData]. + "cloud-retail" will use the dataset generated by cloud + retail based on user events. If leave empty, it will use the + "user-data". + + Current supported values: + + - user-data + + - cloud-retail This option requires additional + allowlisting. Before using cloud-retail, contact Cloud + Retail support team first. + max_suggestions (int): + Completion max suggestions. If left unset or set to 0, then + will fallback to the configured value + [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions]. + + The maximum allowed max suggestions is 20. If it is set + higher, it will be capped by 20. + """ + + catalog = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + visitor_id = proto.Field( + proto.STRING, + number=7, + ) + language_codes = proto.RepeatedField( + proto.STRING, + number=3, + ) + device_type = proto.Field( + proto.STRING, + number=4, + ) + dataset = proto.Field( + proto.STRING, + number=6, + ) + max_suggestions = proto.Field( + proto.INT32, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response of the auto-complete query. + + Attributes: + completion_results (Sequence[google.cloud.retail_v2beta.types.CompleteQueryResponse.CompletionResult]): + Results of the matching suggestions. The + result list is ordered and the first result is + top suggestion. + attribution_token (str): + A unique complete token. This should be included in the + [UserEvent.completion_detail][google.cloud.retail.v2beta.UserEvent.completion_detail] + for search events resulting from this completion, which + enables accurate attribution of complete model performance. + recent_search_results (Sequence[google.cloud.retail_v2beta.types.CompleteQueryResponse.RecentSearchResult]): + Matched recent searches of this user. The maximum number of + recent searches is 10. This field is a restricted feature. + Contact Retail Search support team if you are interested in + enabling it. + + This feature is only available when + [CompleteQueryRequest.visitor_id][google.cloud.retail.v2beta.CompleteQueryRequest.visitor_id] + field is set and + [UserEvent][google.cloud.retail.v2beta.UserEvent] is + imported. The recent searches satisfy the follow rules: + + - They are ordered from latest to oldest. + - They are matched with + [CompleteQueryRequest.query][google.cloud.retail.v2beta.CompleteQueryRequest.query] + case insensitively. + - They are transformed to lower cases. + - They are UTF-8 safe. + + Recent searches are deduplicated. More recent searches will + be reserved when duplication happens. + """ + + class CompletionResult(proto.Message): + r"""Resource that represents completion results. + + Attributes: + suggestion (str): + The suggestion for the query. + attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): + Custom attributes for the suggestion term. + + - For "user-data", the attributes are additional custom + attributes ingested through BigQuery. + - For "cloud-retail", the attributes are product attributes + generated by Cloud Retail. + """ + + suggestion = proto.Field( + proto.STRING, + number=1, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=common.CustomAttribute, + ) + + class RecentSearchResult(proto.Message): + r"""Recent search of this user. + + Attributes: + recent_search (str): + The recent search query. + """ + + recent_search = proto.Field( + proto.STRING, + number=1, + ) + + completion_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=CompletionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + recent_search_results = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=RecentSearchResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py new file mode 100644 index 00000000..0c7cdc3d --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'Control', + }, +) + + +class Control(proto.Message): + r"""Configures dynamic serving time metadata that is used to pre + and post process search/recommendation model results. + + 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: + facet_spec (google.cloud.retail_v2beta.types.SearchRequest.FacetSpec): + A facet specification to perform faceted + search. + + This field is a member of `oneof`_ ``control``. + rule (google.cloud.retail_v2beta.types.Rule): + A rule control - a condition-action pair. + Enacts a set action when the condition is + triggered. For example: Boost "gShoe" when query + full matches "Running Shoes". + + This field is a member of `oneof`_ ``control``. + name (str): + Immutable. Fully qualified name + projects/\ */locations/global/catalogs/*/controls/\* + display_name (str): + Required. The human readable control display name. Used in + Retail UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is thrown. + associated_serving_config_ids (Sequence[str]): + Output only. List of serving configuration + ids that that are associated with this control. + Note the association is managed via the + ServingConfig, this is an output only + denormalizeed view. Assumed to be in the same + catalog. + solution_types (Sequence[google.cloud.retail_v2beta.types.SolutionType]): + Required. Immutable. The solution types that the serving + config is used for. Currently we support setting only one + type of solution at creation time. + + Only ``SOLUTION_TYPE_SEARCH`` value is supported at the + moment. If no solution type is provided at creation time, + will default to SOLUTION_TYPE_SEARCH. + """ + + facet_spec = proto.Field( + proto.MESSAGE, + number=3, + oneof='control', + message=search_service.SearchRequest.FacetSpec, + ) + rule = proto.Field( + proto.MESSAGE, + number=4, + oneof='control', + message=common.Rule, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + associated_serving_config_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + solution_types = proto.RepeatedField( + proto.ENUM, + number=6, + enum=common.SolutionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py new file mode 100644 index 00000000..17120bb5 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import control as gcr_control +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'CreateControlRequest', + 'UpdateControlRequest', + 'DeleteControlRequest', + 'GetControlRequest', + 'ListControlsRequest', + 'ListControlsResponse', + }, +) + + +class CreateControlRequest(proto.Message): + r"""Request for CreateControl method. + + Attributes: + parent (str): + Required. Full resource name of parent catalog. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + control (google.cloud.retail_v2beta.types.Control): + Required. The Control to create. + control_id (str): + Required. The ID to use for the Control, which will become + the final component of the Control's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-_/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + control = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_control.Control, + ) + control_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateControlRequest(proto.Message): + r"""Request for UpdateControl method. + + Attributes: + control (google.cloud.retail_v2beta.types.Control): + Required. The Control to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Control][google.cloud.retail.v2beta.Control] to update. The + following are NOT supported: + + - [Control.name][google.cloud.retail.v2beta.Control.name] + + If not set or empty, all supported fields are updated. + """ + + control = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_control.Control, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteControlRequest(proto.Message): + r"""Request for DeleteControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetControlRequest(proto.Message): + r"""Request for GetControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListControlsRequest(proto.Message): + r"""Request for ListControls method. + + Attributes: + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 50. Max + allowed value is 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListControls`` call. Provide this to retrieve the + subsequent page. + filter (str): + Optional. A filter to apply on the list results. Supported + features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2beta.ListControlsRequest.filter] + is unset. + - List controls that are used in a single ServingConfig: + 'serving_config = "boosted_home_page_cvr"' + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListControlsResponse(proto.Message): + r"""Response for ListControls method. + + Attributes: + controls (Sequence[google.cloud.retail_v2beta.types.Control]): + All the Controls for a given catalog. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + controls = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_control.Control, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py new file mode 100644 index 00000000..b020964a --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'ExportErrorsConfig', + 'ExportMetadata', + 'ExportProductsResponse', + 'ExportUserEventsResponse', + }, +) + + +class ExportErrorsConfig(proto.Message): + r"""Configuration of destination for Export related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage path for import errors. This must be an + empty, existing Cloud Storage bucket. Export errors will be + written to a file in this bucket, one per line, as a + JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ExportMetadata(proto.Message): + r"""Metadata related to the progress of the Export operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ExportProductsResponse(proto.Message): + r"""Response of the ExportProductsRequest. If the long running + operation is done, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2beta.types.ExportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExportErrorsConfig', + ) + + +class ExportUserEventsResponse(proto.Message): + r"""Response of the ExportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2beta.types.ExportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExportErrorsConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py new file mode 100644 index 00000000..a32de943 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py @@ -0,0 +1,691 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import user_event +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'GcsSource', + 'BigQuerySource', + 'ProductInlineSource', + 'UserEventInlineSource', + 'ImportErrorsConfig', + 'ImportProductsRequest', + 'ImportUserEventsRequest', + 'ImportCompletionDataRequest', + 'ProductInputConfig', + 'UserEventInputConfig', + 'CompletionDataInputConfig', + 'ImportMetadata', + 'ImportProductsResponse', + 'ImportUserEventsResponse', + 'UserEventImportSummary', + 'ImportCompletionDataResponse', + }, +) + + +class GcsSource(proto.Message): + r"""Google Cloud Storage location for input content. + format. + + Attributes: + input_uris (Sequence[str]): + Required. Google Cloud Storage URIs to input files. URI can + be up to 2000 characters long. URIs can match the full + object path (for example, + ``gs://bucket/directory/object.json``) or a pattern matching + one or more files, such as ``gs://bucket/directory/*.json``. + A request can contain at most 100 files, and each file can + be up to 2 GB. See `Importing product + information `__ + for the expected file format and setup instructions. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2beta.Product] per line. + Each product must have a valid + [Product.id][google.cloud.retail.v2beta.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2beta.UserEvent] per + line. + - ``user_event_ga360``: Using + https://support.google.com/analytics/answer/3437719. + + Supported values for control imports: + + - 'control' (default): One JSON + [Control][google.cloud.retail.v2beta.Control] per line. + + Supported values for catalog attribute imports: + + - 'catalog_attribute' (default): One CSV + [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] + per line. + """ + + input_uris = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2beta.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID (can be project # or ID) that + the BigQuery source is in with a length limit of + 128 characters. If not specified, inherits the + project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for product imports: + + - ``product`` (default): One JSON + [Product][google.cloud.retail.v2beta.Product] per line. + Each product must have a valid + [Product.id][google.cloud.retail.v2beta.Product.id]. + - ``product_merchant_center``: See `Importing catalog data + from Merchant + Center `__. + + Supported values for user events imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.retail.v2beta.UserEvent] per + line. + - ``user_event_ga360``: The schema is available here: + https://support.google.com/analytics/answer/3437719. + - ``user_event_ga4``: This feature is in private preview. + Please contact the support team for importing Google + Analytics 4 events. The schema is available here: + https://support.google.com/analytics/answer/7029846. + + Supported values for auto-completion imports: + + - ``suggestions`` (default): One JSON completion suggestion + per line. + - ``denylist``: One JSON deny suggestion per line. + - ``allowlist``: One JSON allow suggestion per line. + """ + + partition_date = proto.Field( + proto.MESSAGE, + number=6, + oneof='partition', + message=date_pb2.Date, + ) + project_id = proto.Field( + proto.STRING, + number=5, + ) + dataset_id = proto.Field( + proto.STRING, + number=1, + ) + table_id = proto.Field( + proto.STRING, + number=2, + ) + gcs_staging_dir = proto.Field( + proto.STRING, + number=3, + ) + data_schema = proto.Field( + proto.STRING, + number=4, + ) + + +class ProductInlineSource(proto.Message): + r"""The inline source for the input config for ImportProducts + method. + + Attributes: + products (Sequence[google.cloud.retail_v2beta.types.Product]): + Required. A list of products to update/create. Each product + must have a valid + [Product.id][google.cloud.retail.v2beta.Product.id]. + Recommended max of 100 items. + """ + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=product.Product, + ) + + +class UserEventInlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (Sequence[google.cloud.retail_v2beta.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + +class ImportErrorsConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Google Cloud Storage prefix for import errors. This must be + an empty, existing Cloud Storage directory. Import errors + will be written to sharded files in this directory, one per + line, as a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportProductsRequest(proto.Message): + r"""Request message for Import methods. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` + + If no updateMask is specified, requires products.create + permission. If updateMask is specified, requires + products.update permission. + request_id (str): + Deprecated. This field has no effect. + input_config (google.cloud.retail_v2beta.types.ProductInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported 'products' to update. If not set, will + by default update all fields. + reconciliation_mode (google.cloud.retail_v2beta.types.ImportProductsRequest.ReconciliationMode): + The mode of reconciliation between existing products and the + products to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2beta.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + + Only supported when + [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2beta.ImportProductsRequest.reconciliation_mode] + is set to ``FULL``. + """ + class ReconciliationMode(proto.Enum): + r"""Indicates how imported products are reconciled with the + existing products created or imported before. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + request_id = proto.Field( + proto.STRING, + number=6, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='ProductInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + reconciliation_mode = proto.Field( + proto.ENUM, + number=5, + enum=ReconciliationMode, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=7, + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + input_config (google.cloud.retail_v2beta.types.UserEventInputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='UserEventInputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=3, + message='ImportErrorsConfig', + ) + + +class ImportCompletionDataRequest(proto.Message): + r"""Request message for ImportCompletionData methods. + + Attributes: + parent (str): + Required. The catalog which the suggestions dataset belongs + to. + + Format: + ``projects/1234/locations/global/catalogs/default_catalog``. + input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): + Required. The desired input location of the + data. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + input_config = proto.Field( + proto.MESSAGE, + number=2, + message='CompletionDataInputConfig', + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=3, + ) + + +class ProductInputConfig(proto.Message): + r"""The input config source for products. + + 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: + product_inline_source (google.cloud.retail_v2beta.types.ProductInlineSource): + The Inline source for the input content for + products. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2beta.types.GcsSource): + Google Cloud Storage location for the input + content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + product_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='ProductInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class UserEventInputConfig(proto.Message): + r"""The input config source for user events. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user_event_inline_source (google.cloud.retail_v2beta.types.UserEventInlineSource): + Required. The Inline source for the input + content for UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.retail_v2beta.types.GcsSource): + Required. Google Cloud Storage location for + the input content. + + This field is a member of `oneof`_ ``source``. + big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): + Required. BigQuery input source. + + This field is a member of `oneof`_ ``source``. + """ + + user_event_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='UserEventInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + big_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='BigQuerySource', + ) + + +class CompletionDataInputConfig(proto.Message): + r"""The input config source for completion data. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): + Required. BigQuery input source. + Add the IAM permission "BigQuery Data Viewer" + for + cloud-retail-customer-data-access@system.gserviceaccount.com + before using this feature otherwise an error is + thrown. + + This field is a member of `oneof`_ ``source``. + """ + + big_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='BigQuerySource', + ) + + +class ImportMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + request_id (str): + Deprecated. This field is never set. + notification_pubsub_topic (str): + Pub/Sub topic for receiving notification. If this field is + set, when the import is finished, a notification will be + sent to specified Pub/Sub topic. The message data will be + JSON string of a [Operation][google.longrunning.Operation]. + Format of the Pub/Sub topic is + ``projects/{project}/topics/{topic}``. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=3, + ) + failure_count = proto.Field( + proto.INT64, + number=4, + ) + request_id = proto.Field( + proto.STRING, + number=5, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=6, + ) + + +class ImportProductsResponse(proto.Message): + r"""Response of the + [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + import_summary (google.cloud.retail_v2beta.types.UserEventImportSummary): + Aggregated statistics of user event import + status. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + import_summary = proto.Field( + proto.MESSAGE, + number=3, + message='UserEventImportSummary', + ) + + +class UserEventImportSummary(proto.Message): + r"""A summary of import result. The UserEventImportSummary + summarizes the import status for user events. + + Attributes: + joined_events_count (int): + Count of user events imported with complete + existing catalog information. + unjoined_events_count (int): + Count of user events imported, but with + catalog information not found in the imported + catalog. + """ + + joined_events_count = proto.Field( + proto.INT64, + number=1, + ) + unjoined_events_count = proto.Field( + proto.INT64, + number=2, + ) + + +class ImportCompletionDataResponse(proto.Message): + r"""Response of the + [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. + 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 (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py new file mode 100644 index 00000000..f31ba819 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import user_event as gcr_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'PredictRequest', + 'PredictResponse', + }, +) + + +class PredictRequest(proto.Message): + r"""Request message for Predict method. + + Attributes: + placement (str): + Required. Full resource name of the format: + {name=projects/*/locations/global/catalogs/default_catalog/placements/*} + The ID of the Recommendations AI placement. Before you can + request predictions from your model, you must create at + least one placement for it. For more information, see + `Managing + placements `__. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements + user_event (google.cloud.retail_v2beta.types.UserEvent): + Required. Context about the user, what they + are looking at and what action they took to + trigger the predict request. Note that this user + event detail won't be ingested to userEvent + logs. Thus, a separate userEvent write request + is required for event logging. + page_size (int): + Maximum number of results to return per page. + Set this property to the number of prediction + results needed. If zero, the service will choose + a reasonable default. The maximum allowed value + is 100. Values above 100 will be coerced to 100. + page_token (str): + The previous PredictResponse.next_page_token. + filter (str): + Filter for restricting prediction results with a length + limit of 5,000 characters. Accepts values for tags and the + ``filterOutOfStockItems`` flag. + + - Tag expressions. Restricts predictions to products that + match all of the specified tags. Boolean operators ``OR`` + and ``NOT`` are supported if the expression is enclosed + in parentheses, and must be separated from the tag values + by a space. ``-"tagA"`` is also supported and is + equivalent to ``NOT "tagA"``. Tag values must be double + quoted UTF-8 encoded strings with a size limit of 1,000 + characters. + + Note: "Recently viewed" models don't support tag + filtering at the moment. + + - filterOutOfStockItems. Restricts predictions to products + that do not have a stockState value of OUT_OF_STOCK. + + Examples: + + - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT + "promotional") + - filterOutOfStockItems tag=(-"promotional") + - filterOutOfStockItems + + If your filter blocks all prediction results, the API will + return generic (unfiltered) popular products. If you only + want results strictly matching the filters, set + ``strictFiltering`` to True in ``PredictRequest.params`` to + receive empty results instead. Note that the API will never + return items with storageStatus of "EXPIRED" or "DELETED" + regardless of filter choices. + validate_only (bool): + Use validate only mode for this prediction + query. If set to true, a dummy model will be + used that returns arbitrary products. Note that + the validate only mode should only be used for + testing the API, or if the model is not ready. + params (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific parameters for the predictions. + + Allowed values: + + - ``returnProduct``: Boolean. If set to true, the + associated product object will be returned in the + ``results.metadata`` field in the prediction response. + - ``returnScore``: Boolean. If set to true, the prediction + 'score' corresponding to each returned product will be + set in the ``results.metadata`` field in the prediction + response. The given 'score' indicates the probability of + an product being clicked/purchased given the user's + context and history. + - ``strictFiltering``: Boolean. True by default. If set to + false, the service will return generic (unfiltered) + popular products instead of empty if your filter blocks + all prediction results. + - ``priceRerankLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of + {'no-price-reranking', 'low-price-reranking', + 'medium-price-reranking', 'high-price-reranking'}. This + gives request-level control and adjusts prediction + results based on product price. + - ``diversityLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of {'no-diversity', + 'low-diversity', 'medium-diversity', 'high-diversity', + 'auto-diversity'}. This gives request-level control and + adjusts prediction results based on product category. + labels (Mapping[str, str]): + The labels applied to a resource must meet the following + requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters, and cannot be empty. Values can + be empty, and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + placement = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + filter = proto.Field( + proto.STRING, + number=5, + ) + validate_only = proto.Field( + proto.BOOL, + number=6, + ) + params = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class PredictResponse(proto.Message): + r"""Response message for predict method. + + Attributes: + results (Sequence[google.cloud.retail_v2beta.types.PredictResponse.PredictionResult]): + A list of recommended products. The order + represents the ranking (from the most relevant + product to the least). + attribution_token (str): + A unique attribution token. This should be included in the + [UserEvent][google.cloud.retail.v2beta.UserEvent] logs + resulting from this recommendation, which enables accurate + attribution of recommendation model performance. + missing_ids (Sequence[str]): + IDs of products in the request that were + missing from the inventory. + validate_only (bool): + True if the validateOnly property was set in + the request. + """ + + class PredictionResult(proto.Message): + r"""PredictionResult represents the recommendation prediction + results. + + Attributes: + id (str): + ID of the recommended product + metadata (Mapping[str, google.protobuf.struct_pb2.Value]): + Additional product metadata / annotations. + + Possible values: + + - ``product``: JSON representation of the product. Will be + set if ``returnProduct`` is set to true in + ``PredictRequest.params``. + - ``score``: Prediction score in double value. Will be set + if ``returnScore`` is set to true in + ``PredictRequest.params``. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + metadata = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=PredictionResult, + ) + attribution_token = proto.Field( + proto.STRING, + number=2, + ) + missing_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py new file mode 100644 index 00000000..bd0de773 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py @@ -0,0 +1,705 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import promotion +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'Product', + }, +) + + +class Product(proto.Message): + r"""Product captures all metadata information of items to be + recommended or searched. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this product becomes unavailable for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + If it is set, the + [Product][google.cloud.retail.v2beta.Product] is not + available for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + after + [expire_time][google.cloud.retail.v2beta.Product.expire_time]. + However, the product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + [expire_time][google.cloud.retail.v2beta.Product.expire_time] + must be later than + [available_time][google.cloud.retail.v2beta.Product.available_time] + and + [publish_time][google.cloud.retail.v2beta.Product.publish_time], + otherwise an INVALID_ARGUMENT error is thrown. + + Corresponding properties: Google Merchant Center property + `expiration_date `__. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Input only. The TTL (time to live) of the product. + + If it is set, it must be a non-negative value, and + [expire_time][google.cloud.retail.v2beta.Product.expire_time] + is set as current timestamp plus + [ttl][google.cloud.retail.v2beta.Product.ttl]. The derived + [expire_time][google.cloud.retail.v2beta.Product.expire_time] + is returned in the output and + [ttl][google.cloud.retail.v2beta.Product.ttl] is left blank + when retrieving the + [Product][google.cloud.retail.v2beta.Product]. + + If it is set, the product is not available for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + after current timestamp plus + [ttl][google.cloud.retail.v2beta.Product.ttl]. However, the + product can still be retrieved by + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] + and + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. + + This field is a member of `oneof`_ ``expiration``. + name (str): + Immutable. Full resource name of the product, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. + id (str): + Immutable. [Product][google.cloud.retail.v2beta.Product] + identifier, which is the final component of + [name][google.cloud.retail.v2beta.Product.name]. For + example, this field is "id_1", if + [name][google.cloud.retail.v2beta.Product.name] is + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `id `__. + Schema.org property + `Product.sku `__. + type_ (google.cloud.retail_v2beta.types.Product.Type): + Immutable. The type of the product. Default to + [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2beta.ProductLevelConfig.ingestion_product_type] + if unset. + primary_product_id (str): + Variant group identifier. Must be an + [id][google.cloud.retail.v2beta.Product.id], with the same + parent branch with this product. Otherwise, an error is + thrown. + + For + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]s, this field + can only be empty or set to the same value as + [id][google.cloud.retail.v2beta.Product.id]. + + For VARIANT [Product][google.cloud.retail.v2beta.Product]s, + this field cannot be empty. A maximum of 2,000 products are + allowed to share the same + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `item_group_id `__. + Schema.org property + `Product.inProductGroupWithID `__. + collection_member_ids (Sequence[str]): + The [id][google.cloud.retail.v2beta.Product.id] of the + collection members when + [type][google.cloud.retail.v2beta.Product.type] is + [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION]. + + Non-existent product ids are allowed. The + [type][google.cloud.retail.v2beta.Product.type] of the + members must be either + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + or + [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + otherwise and INVALID_ARGUMENT error is thrown. Should not + set it for other types. A maximum of 1000 values are + allowed. Otherwise, an INVALID_ARGUMENT error is return. + gtin (str): + The Global Trade Item Number (GTIN) of the product. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + This field must be a Unigram. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `gtin `__. + Schema.org property + `Product.isbn `__, + `Product.gtin8 `__, + `Product.gtin12 `__, + `Product.gtin13 `__, or + `Product.gtin14 `__. + + If the value is not a valid GTIN, an INVALID_ARGUMENT error + is returned. + categories (Sequence[str]): + Product categories. This field is repeated for supporting + one product belonging to several parallel categories. + Strongly recommended using the full path for better search / + recommendation quality. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + For example, if a shoes product belongs to both ["Shoes & + Accessories" -> "Shoes"] and ["Sports & Fitness" -> + "Athletic Clothing" -> "Shoes"], it could be represented as: + + :: + + "categories": [ + "Shoes & Accessories > Shoes", + "Sports & Fitness > Athletic Clothing > Shoes" + ] + + Must be set for + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] otherwise an + INVALID_ARGUMENT error is returned. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2beta.Product]. Empty values + are not allowed. Each value must be a UTF-8 encoded string + with a length limit of 5,000 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `google_product_category `__. + Schema.org property [Product.category] + (https://schema.org/category). + title (str): + Required. Product title. + + This field must be a UTF-8 encoded string with a length + limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `title `__. + Schema.org property + `Product.name `__. + brands (Sequence[str]): + The brands of the product. + + A maximum of 30 brands are allowed. Each brand must be a + UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `brand `__. + Schema.org property + `Product.brand `__. + description (str): + Product description. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `description `__. + Schema.org property + `Product.description `__. + language_code (str): + Language of the title/description and other string + attributes. Use language tags defined by `BCP + 47 `__. + + For product prediction, this field is ignored and the model + automatically detects the text language. The + [Product][google.cloud.retail.v2beta.Product] can include + text in different languages, but duplicating + [Product][google.cloud.retail.v2beta.Product]s to provide + text in multiple languages can result in degraded model + performance. + + For product search this field is in use. It defaults to + "en-US" if unset. + attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): + Highly encouraged. Extra product attributes to be included. + For example, for products, this could include the store + name, vendor, style, color, etc. These are very strong + signals for recommendation model, thus we highly recommend + providing the attributes here. + + Features that can take on one of a limited number of + possible values. Two types of features can be set are: + + Textual features. some examples would be the brand/maker of + a product, or country of a customer. Numerical features. + Some examples would be the height/weight of a product, or + age of a customer. + + For example: + ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - Max entries count: 200. + - The key must be a UTF-8 encoded string with a length + limit of 128 characters. + - For indexable attribute, the key must match the pattern: + ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, + ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a + non-empty UTF-8 encoded string with a length limit of 256 + characters. + - For number attributes, at most 400 values are allowed. + tags (Sequence[str]): + Custom tags associated with the product. + + At most 250 values are allowed per + [Product][google.cloud.retail.v2beta.Product]. This value + must be a UTF-8 encoded string with a length limit of 1,000 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This tag can be used for filtering recommendation results by + passing the tag as part of the + [PredictRequest.filter][google.cloud.retail.v2beta.PredictRequest.filter]. + + Corresponding properties: Google Merchant Center property + `custom_label_0–4 `__. + price_info (google.cloud.retail_v2beta.types.PriceInfo): + Product price and cost information. + + Corresponding properties: Google Merchant Center property + `price `__. + rating (google.cloud.retail_v2beta.types.Rating): + The rating of this product. + available_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when this + [Product][google.cloud.retail.v2beta.Product] becomes + available for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + availability (google.cloud.retail_v2beta.types.Product.Availability): + The online availability of the + [Product][google.cloud.retail.v2beta.Product]. Default to + [Availability.IN_STOCK][google.cloud.retail.v2beta.Product.Availability.IN_STOCK]. + + Corresponding properties: Google Merchant Center property + `availability `__. + Schema.org property + `Offer.availability `__. + available_quantity (google.protobuf.wrappers_pb2.Int32Value): + The available quantity of the item. + fulfillment_info (Sequence[google.cloud.retail_v2beta.types.FulfillmentInfo]): + Fulfillment information, such as the store IDs for in-store + pickup or region IDs for different shipping methods. + + All the elements must have distinct + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type]. + Otherwise, an INVALID_ARGUMENT error is returned. + uri (str): + Canonical URL directly linking to the product detail page. + + It is strongly recommended to provide a valid uri for the + product, otherwise the service performance could be + significantly degraded. + + This field must be a UTF-8 encoded string with a length + limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + + Corresponding properties: Google Merchant Center property + `link `__. + Schema.org property `Offer.url `__. + images (Sequence[google.cloud.retail_v2beta.types.Image]): + Product images for the product. We highly recommend putting + the main image first. + + A maximum of 300 images are allowed. + + Corresponding properties: Google Merchant Center property + `image_link `__. + Schema.org property + `Product.image `__. + audience (google.cloud.retail_v2beta.types.Audience): + The target group associated with a given + audience (e.g. male, veterans, car owners, + musicians, etc.) of the product. + color_info (google.cloud.retail_v2beta.types.ColorInfo): + The color of the product. + + Corresponding properties: Google Merchant Center property + `color `__. + Schema.org property + `Product.color `__. + sizes (Sequence[str]): + The size of the product. To represent different size systems + or size types, consider using this format: + [[[size_system:]size_type:]size_value]. + + For example, in "US:MENS:M", "US" represents size system; + "MENS" represents size type; "M" represents size value. In + "GIRLS:27", size system is empty; "GIRLS" represents size + type; "27" represents size value. In "32 inches", both size + system and size type are empty, while size value is "32 + inches". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2beta.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `size `__, + `size_type `__, + and + `size_system `__. + Schema.org property + `Product.size `__. + materials (Sequence[str]): + The material of the product. For example, "leather", + "wooden". + + A maximum of 20 values are allowed. Each value must be a + UTF-8 encoded string with a length limit of 200 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + Corresponding properties: Google Merchant Center property + `material `__. + Schema.org property + `Product.material `__. + patterns (Sequence[str]): + The pattern or graphic print of the product. For example, + "striped", "polka dot", "paisley". + + A maximum of 20 values are allowed per + [Product][google.cloud.retail.v2beta.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `pattern `__. + Schema.org property + `Product.pattern `__. + conditions (Sequence[str]): + The condition of the product. Strongly encouraged to use the + standard values: "new", "refurbished", "used". + + A maximum of 1 value is allowed per + [Product][google.cloud.retail.v2beta.Product]. Each value + must be a UTF-8 encoded string with a length limit of 128 + characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + Corresponding properties: Google Merchant Center property + `condition `__. + Schema.org property + `Offer.itemCondition `__. + promotions (Sequence[google.cloud.retail_v2beta.types.Promotion]): + The promotions applied to the product. A maximum of 10 + values are allowed per + [Product][google.cloud.retail.v2beta.Product]. Only + [Promotion.promotion_id][google.cloud.retail.v2beta.Promotion.promotion_id] + will be used, other fields will be ignored if set. + publish_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the product is published by the retailer + for the first time, which indicates the freshness of the + products. Note that this field is different from + [available_time][google.cloud.retail.v2beta.Product.available_time], + given it purely describes product freshness regardless of + when it is available on search and recommendation. + retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the + [Product][google.cloud.retail.v2beta.Product]s are returned + in + [SearchResponse][google.cloud.retail.v2beta.SearchResponse]. + + Supported fields for all + [type][google.cloud.retail.v2beta.Product.type]s: + + - [audience][google.cloud.retail.v2beta.Product.audience] + - [availability][google.cloud.retail.v2beta.Product.availability] + - [brands][google.cloud.retail.v2beta.Product.brands] + - [color_info][google.cloud.retail.v2beta.Product.color_info] + - [conditions][google.cloud.retail.v2beta.Product.conditions] + - [gtin][google.cloud.retail.v2beta.Product.gtin] + - [materials][google.cloud.retail.v2beta.Product.materials] + - [name][google.cloud.retail.v2beta.Product.name] + - [patterns][google.cloud.retail.v2beta.Product.patterns] + - [price_info][google.cloud.retail.v2beta.Product.price_info] + - [rating][google.cloud.retail.v2beta.Product.rating] + - [sizes][google.cloud.retail.v2beta.Product.sizes] + - [title][google.cloud.retail.v2beta.Product.title] + - [uri][google.cloud.retail.v2beta.Product.uri] + + Supported fields only for + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION]: + + - [categories][google.cloud.retail.v2beta.Product.categories] + - [description][google.cloud.retail.v2beta.Product.description] + - [images][google.cloud.retail.v2beta.Product.images] + + Supported fields only for + [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT]: + + - Only the first image in + [images][google.cloud.retail.v2beta.Product.images] + + To mark + [attributes][google.cloud.retail.v2beta.Product.attributes] + as retrievable, include paths of the form "attributes.key" + where "key" is the key of a custom attribute, as specified + in + [attributes][google.cloud.retail.v2beta.Product.attributes]. + + For + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + and + [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION], + the following fields are always returned in + [SearchResponse][google.cloud.retail.v2beta.SearchResponse] + by default: + + - [name][google.cloud.retail.v2beta.Product.name] + + For + [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT], + the following fields are always returned in by default: + + - [name][google.cloud.retail.v2beta.Product.name] + - [color_info][google.cloud.retail.v2beta.Product.color_info] + + Maximum number of paths is 30. Otherwise, an + INVALID_ARGUMENT error is returned. + + Note: Returning more fields in + [SearchResponse][google.cloud.retail.v2beta.SearchResponse] + may increase response payload size and serving latency. + variants (Sequence[google.cloud.retail_v2beta.types.Product]): + Output only. Product variants grouped together on primary + product which share similar product attributes. It's + automatically grouped by + [primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] + for all the product variants. Only populated for + [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]s. + + Note: This field is OUTPUT_ONLY for + [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct]. + Do not set this field in API requests. + """ + class Type(proto.Enum): + r"""The type of this product.""" + TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + VARIANT = 2 + COLLECTION = 3 + + class Availability(proto.Enum): + r"""Product availability. If this field is unspecified, the + product is assumed to be in stock. + """ + AVAILABILITY_UNSPECIFIED = 0 + IN_STOCK = 1 + OUT_OF_STOCK = 2 + PREORDER = 3 + BACKORDER = 4 + + expire_time = proto.Field( + proto.MESSAGE, + number=16, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl = proto.Field( + proto.MESSAGE, + number=17, + oneof='expiration', + message=duration_pb2.Duration, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + type_ = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + primary_product_id = proto.Field( + proto.STRING, + number=4, + ) + collection_member_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + gtin = proto.Field( + proto.STRING, + number=6, + ) + categories = proto.RepeatedField( + proto.STRING, + number=7, + ) + title = proto.Field( + proto.STRING, + number=8, + ) + brands = proto.RepeatedField( + proto.STRING, + number=9, + ) + description = proto.Field( + proto.STRING, + number=10, + ) + language_code = proto.Field( + proto.STRING, + number=11, + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message=common.CustomAttribute, + ) + tags = proto.RepeatedField( + proto.STRING, + number=13, + ) + price_info = proto.Field( + proto.MESSAGE, + number=14, + message=common.PriceInfo, + ) + rating = proto.Field( + proto.MESSAGE, + number=15, + message=common.Rating, + ) + available_time = proto.Field( + proto.MESSAGE, + number=18, + message=timestamp_pb2.Timestamp, + ) + availability = proto.Field( + proto.ENUM, + number=19, + enum=Availability, + ) + available_quantity = proto.Field( + proto.MESSAGE, + number=20, + message=wrappers_pb2.Int32Value, + ) + fulfillment_info = proto.RepeatedField( + proto.MESSAGE, + number=21, + message=common.FulfillmentInfo, + ) + uri = proto.Field( + proto.STRING, + number=22, + ) + images = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=common.Image, + ) + audience = proto.Field( + proto.MESSAGE, + number=24, + message=common.Audience, + ) + color_info = proto.Field( + proto.MESSAGE, + number=25, + message=common.ColorInfo, + ) + sizes = proto.RepeatedField( + proto.STRING, + number=26, + ) + materials = proto.RepeatedField( + proto.STRING, + number=27, + ) + patterns = proto.RepeatedField( + proto.STRING, + number=28, + ) + conditions = proto.RepeatedField( + proto.STRING, + number=29, + ) + promotions = proto.RepeatedField( + proto.MESSAGE, + number=34, + message=promotion.Promotion, + ) + publish_time = proto.Field( + proto.MESSAGE, + number=33, + message=timestamp_pb2.Timestamp, + ) + retrievable_fields = proto.Field( + proto.MESSAGE, + number=30, + message=field_mask_pb2.FieldMask, + ) + variants = proto.RepeatedField( + proto.MESSAGE, + number=31, + message='Product', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py new file mode 100644 index 00000000..06a23d13 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py @@ -0,0 +1,844 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'CreateProductRequest', + 'GetProductRequest', + 'UpdateProductRequest', + 'DeleteProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'SetInventoryRequest', + 'SetInventoryMetadata', + 'SetInventoryResponse', + 'AddFulfillmentPlacesRequest', + 'AddFulfillmentPlacesMetadata', + 'AddFulfillmentPlacesResponse', + 'AddLocalInventoriesRequest', + 'AddLocalInventoriesMetadata', + 'AddLocalInventoriesResponse', + 'RemoveLocalInventoriesRequest', + 'RemoveLocalInventoriesMetadata', + 'RemoveLocalInventoriesResponse', + 'RemoveFulfillmentPlacesRequest', + 'RemoveFulfillmentPlacesMetadata', + 'RemoveFulfillmentPlacesResponse', + }, +) + + +class CreateProductRequest(proto.Message): + r"""Request message for [CreateProduct][] method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. + product (google.cloud.retail_v2beta.types.Product): + Required. The [Product][google.cloud.retail.v2beta.Product] + to create. + product_id (str): + Required. The ID to use for the + [Product][google.cloud.retail.v2beta.Product], which will + become the final component of the + [Product.name][google.cloud.retail.v2beta.Product.name]. + + If the caller does not have permission to create the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + This field must be unique among all + [Product][google.cloud.retail.v2beta.Product]s with the same + [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. + Otherwise, an ALREADY_EXISTS error is returned. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + product_id = proto.Field( + proto.STRING, + number=3, + ) + + +class GetProductRequest(proto.Message): + r"""Request message for [GetProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the requested + [Product][google.cloud.retail.v2beta.Product] does not + exist, a NOT_FOUND error is returned. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateProductRequest(proto.Message): + r"""Request message for [UpdateProduct][] method. + + Attributes: + product (google.cloud.retail_v2beta.types.Product): + Required. The product to update/create. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not exist and + [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] + is not set, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Product][google.cloud.retail.v2beta.Product] to update. The + immutable and output only fields are NOT supported. If not + set, all supported fields (the fields that are neither + immutable nor output only) are updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + a new [Product][google.cloud.retail.v2beta.Product] will be + created. In this situation, ``update_mask`` is ignored. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteProductRequest(proto.Message): + r"""Request message for [DeleteProduct][] method. + + Attributes: + name (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to delete the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + delete does not exist, a NOT_FOUND error is returned. + + The [Product][google.cloud.retail.v2beta.Product] to delete + can neither be a + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product] member nor a + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] with more than + one + [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. + Otherwise, an INVALID_ARGUMENT error is returned. + + All inventory information for the named + [Product][google.cloud.retail.v2beta.Product] will be + deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProductsRequest(proto.Message): + r"""Request message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + Use ``default_branch`` as the branch ID, to list products + under the default branch. + + If the caller does not have permission to list + [Product][google.cloud.retail.v2beta.Product]s under this + branch, regardless of whether or not this branch exists, a + PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [Product][google.cloud.retail.v2beta.Product]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 + [ListProductsResponse.next_page_token][google.cloud.retail.v2beta.ListProductsResponse.next_page_token], + received from a previous + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + filter (str): + A filter to apply on the list results. Supported features: + + - List all the products under the parent branch if + [filter][google.cloud.retail.v2beta.ListProductsRequest.filter] + is unset. + - List + [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s sharing + the same + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product]. For + example: ``primary_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2beta.Product]s + bundled in a + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product]. For + example: ``collection_product_id = "some_product_id"`` + - List [Product][google.cloud.retail.v2beta.Product]s with + a partibular type. For example: ``type = "PRIMARY"`` + ``type = "VARIANT"`` ``type = "COLLECTION"`` + + If the field is unrecognizable, an INVALID_ARGUMENT error is + returned. + + If the specified + [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + [Product][google.cloud.retail.v2beta.Product] or + [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] + [Product][google.cloud.retail.v2beta.Product] does not + exist, a NOT_FOUND error is returned. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields of [Product][google.cloud.retail.v2beta.Product] + to return in the responses. If not set or empty, the + following fields are returned: + + - [Product.name][google.cloud.retail.v2beta.Product.name] + - [Product.id][google.cloud.retail.v2beta.Product.id] + - [Product.title][google.cloud.retail.v2beta.Product.title] + - [Product.uri][google.cloud.retail.v2beta.Product.uri] + - [Product.images][google.cloud.retail.v2beta.Product.images] + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.brands][google.cloud.retail.v2beta.Product.brands] + + If "*" is provided, all fields are returned. + [Product.name][google.cloud.retail.v2beta.Product.name] is + always returned no matter what mask is set. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class ListProductsResponse(proto.Message): + r"""Response message for + [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] + method. + + Attributes: + products (Sequence[google.cloud.retail_v2beta.types.Product]): + The [Product][google.cloud.retail.v2beta.Product]s. + next_page_token (str): + A token that can be sent as + [ListProductsRequest.page_token][google.cloud.retail.v2beta.ListProductsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class SetInventoryRequest(proto.Message): + r"""Request message for [SetInventory][] method. + + Attributes: + inventory (google.cloud.retail_v2beta.types.Product): + Required. The inventory information to update. The allowable + fields to update are: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + The updated inventory fields must be specified in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. + + If [SetInventoryRequest.inventory.name][] is empty or + invalid, an INVALID_ARGUMENT error is returned. + + If the caller does not have permission to update the + [Product][google.cloud.retail.v2beta.Product] named in + [Product.name][google.cloud.retail.v2beta.Product.name], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Product][google.cloud.retail.v2beta.Product] to + update does not have existing inventory information, the + provided inventory information will be inserted. + + If the [Product][google.cloud.retail.v2beta.Product] to + update has existing inventory information, the provided + inventory information will be merged while respecting the + last update time for each inventory field, using the + provided or default value for + [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. + + The caller can replace place IDs for a subset of fulfillment + types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types and + corresponding place IDs to update in + [SetInventoryRequest.inventory.fulfillment_info][] + + The caller can clear all place IDs from a subset of + fulfillment types in the following ways: + + - Adds "fulfillment_info" in + [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] + - Specifies only the desired fulfillment types to clear in + [SetInventoryRequest.inventory.fulfillment_info][] + - Checks that only the desired fulfillment info types have + empty + [SetInventoryRequest.inventory.fulfillment_info.place_ids][] + + The last update time is recorded for the following inventory + fields: + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + - [Product.availability][google.cloud.retail.v2beta.Product.availability] + - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] + - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] + + If a full overwrite of inventory information while ignoring + timestamps is needed, [UpdateProduct][] should be invoked + instead. + set_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided + [Product][google.cloud.retail.v2beta.Product] to update. + + At least one field must be provided. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + set_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the request is issued, used to + prevent out-of-order updates on inventory fields + with the last update time recorded. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] with name + [Product.name][google.cloud.retail.v2beta.Product.name] is + not found, the inventory update will still be processed and + retained for at most 1 day until the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + inventory = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + set_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + set_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=4, + ) + + +class SetInventoryMetadata(proto.Message): + r"""Metadata related to the progress of the SetInventory operation. + Currently empty because there is no meaningful metadata populated + from the [SetInventory][] method. + + """ + + +class SetInventoryResponse(proto.Message): + r"""Response of the SetInventoryRequest. Currently empty because there + is no meaningful response populated from the [SetInventory][] + method. + + """ + + +class AddFulfillmentPlacesRequest(proto.Message): + r"""Request message for [AddFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery" to be added for this + [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type]. + Duplicate IDs will be automatically ignored. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + + If the total number of place IDs exceeds 2000 for this + [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type] + after adding, then the update will be rejected. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + the fulfillment information will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + add_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class AddFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the AddFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [AddFulfillmentPlaces][] method. + + """ + + +class AddFulfillmentPlacesResponse(proto.Message): + r"""Response of the AddFulfillmentPlacesRequest. Currently empty because + there is no meaningful response populated from the + [AddFulfillmentPlaces][] method. + + """ + + +class AddLocalInventoriesRequest(proto.Message): + r"""Request message for [AddLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + local_inventories (Sequence[google.cloud.retail_v2beta.types.LocalInventory]): + Required. A list of inventory information at + difference places. Each place is identified by + its place ID. At most 3000 inventories are + allowed per request. + add_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which inventory fields in the provided list of + [LocalInventory][google.cloud.retail.v2beta.LocalInventory] + to update. The field is updated to the provided value. + + If a field is set while the place does not have a previous + local inventory, the local inventory at that store is + created. + + If a field is set while the value of that field is not + provided, the original field value, if it exists, is + deleted. + + If the mask is not set or set with empty paths, all + inventory fields will be updated. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned and the entire update + will be ignored. + add_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory updates are + issued. Used to prevent out-of-order updates on + local inventory fields. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + the local inventory will still be processed and retained for + at most 1 day and processed once the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + local_inventories = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.LocalInventory, + ) + add_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + add_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=6, + ) + + +class AddLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the AddLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [AddLocalInventories][] method. + + """ + + +class AddLocalInventoriesResponse(proto.Message): + r"""Response of the [AddLocalInventories][] API. Currently empty because + there is no meaningful response populated from the + [AddLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesRequest(proto.Message): + r"""Request message for [RemoveLocalInventories][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + place_ids (Sequence[str]): + Required. A list of place IDs to have their + inventory deleted. At most 3000 place IDs are + allowed per request. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the inventory deletions are + issued. Used to prevent out-of-order updates and + deletions on local inventory fields. If not + provided, the internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + the local inventory removal request will still be processed + and retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + + +class RemoveLocalInventoriesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveLocalInventories + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveLocalInventories][] method. + + """ + + +class RemoveLocalInventoriesResponse(proto.Message): + r"""Response of the [RemoveLocalInventories][] API. Currently empty + because there is no meaningful response populated from the + [RemoveLocalInventories][] method. + + """ + + +class RemoveFulfillmentPlacesRequest(proto.Message): + r"""Request message for [RemoveFulfillmentPlaces][] method. + + Attributes: + product (str): + Required. Full resource name of + [Product][google.cloud.retail.v2beta.Product], such as + ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. + + If the caller does not have permission to access the + [Product][google.cloud.retail.v2beta.Product], regardless of + whether or not it exists, a PERMISSION_DENIED error is + returned. + type_ (str): + Required. The fulfillment type, including commonly used + types (such as pickup in store and same day delivery), and + custom types. + + Supported values: + + - "pickup-in-store" + - "ship-to-store" + - "same-day-delivery" + - "next-day-delivery" + - "custom-type-1" + - "custom-type-2" + - "custom-type-3" + - "custom-type-4" + - "custom-type-5" + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + + This field directly corresponds to + [Product.fulfillment_info.type][]. + place_ids (Sequence[str]): + Required. The IDs for this + [type][google.cloud.retail.v2beta.RemoveFulfillmentPlacesRequest.type], + such as the store IDs for "pickup-in-store" or the region + IDs for "same-day-delivery", to be removed for this + [type][google.cloud.retail.v2beta.RemoveFulfillmentPlacesRequest.type]. + + At least 1 value is required, and a maximum of 2000 values + are allowed. Each value must be a string with a length limit + of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, + such as "store1" or "REGION-2". Otherwise, an + INVALID_ARGUMENT error is returned. + remove_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the fulfillment updates are + issued, used to prevent out-of-order updates on + fulfillment information. If not provided, the + internal system time will be used. + allow_missing (bool): + If set to true, and the + [Product][google.cloud.retail.v2beta.Product] is not found, + the fulfillment information will still be processed and + retained for at most 1 day and processed once the + [Product][google.cloud.retail.v2beta.Product] is created. If + set to false, a NOT_FOUND error is returned if the + [Product][google.cloud.retail.v2beta.Product] is not found. + """ + + product = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + place_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + remove_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + allow_missing = proto.Field( + proto.BOOL, + number=5, + ) + + +class RemoveFulfillmentPlacesMetadata(proto.Message): + r"""Metadata related to the progress of the RemoveFulfillmentPlaces + operation. Currently empty because there is no meaningful metadata + populated from the [RemoveFulfillmentPlaces][] method. + + """ + + +class RemoveFulfillmentPlacesResponse(proto.Message): + r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty + because there is no meaningful response populated from the + [RemoveFulfillmentPlaces][] method. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py new file mode 100644 index 00000000..be192a70 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'Promotion', + }, +) + + +class Promotion(proto.Message): + r"""Promotion information. + + Attributes: + promotion_id (str): + ID of the promotion. For example, "free gift". + + The value must be a UTF-8 encoded string with a length limit + of 128 characters, and match the pattern: + ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or + ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is + returned. + + Google Merchant Center property + `promotion `__. + """ + + promotion_id = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py new file mode 100644 index 00000000..95c99126 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'PurgeMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + }, +) + + +class PurgeMetadata(proto.Message): + r"""Metadata related to the progress of the Purge operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + """ + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + + Attributes: + parent (str): + Required. The resource name of the catalog under which the + events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}`` + filter (str): + Required. The filter string to specify the events to be + deleted with a length limit of 5,000 characters. Empty + string filter is not allowed. The eligible fields for + filtering are: + + - ``eventType``: Double quoted + [UserEvent.event_type][google.cloud.retail.v2beta.UserEvent.event_type] + string. + - ``eventTime``: in ISO 8601 "zulu" format. + - ``visitorId``: Double quoted string. Specifying this will + delete all events associated with a visitor. + - ``userId``: Double quoted string. Specifying this will + delete all events associated with a user. + + Examples: + + - Deleting all events in a time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + - Deleting specific eventType in time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + - Deleting all events for a specific visitor: + ``visitorId = "visitor1024"`` + + The filtering fields are assumed to have an implicit AND. + force (bool): + Actually perform the purge. If ``force`` is set to false, + the method will return the expected purge count without + deleting any user events. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsResponse(proto.Message): + r"""Response of the PurgeUserEventsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purged_events_count (int): + The total count of events purged as a result + of the operation. + """ + + purged_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py new file mode 100644 index 00000000..21447a27 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py @@ -0,0 +1,1074 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import product as gcr_product +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'SearchRequest', + 'SearchResponse', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + + Attributes: + placement (str): + Required. The resource name of the search engine placement, + such as + ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` + This field is used to identify the serving configuration + name and the set of models that will be used to make the + search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/catalogs/default_catalog/branches/0``. + + Use "default_branch" as the branch ID or leave this field + empty, to search products under the default branch. + query (str): + Raw search query. + visitor_id (str): + Required. A unique identifier for tracking visitors. For + example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor logs in or out of the website. + + This should be the same identifier as + [UserEvent.visitor_id][google.cloud.retail.v2beta.UserEvent.visitor_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2beta.types.UserInfo): + User information. + page_size (int): + Maximum number of + [Product][google.cloud.retail.v2beta.Product]s to return. If + unspecified, defaults to a reasonable value. The maximum + allowed value is 120. Values above 120 will be coerced to + 120. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [SearchResponse.next_page_token][google.cloud.retail.v2beta.SearchResponse.next_page_token], + received from a previous + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Product][google.cloud.retail.v2beta.Product]s deemed by the + API as relevant) in search results. This field is only + considered if + [page_token][google.cloud.retail.v2beta.SearchRequest.page_token] + is unset. + + If this field is negative, an INVALID_ARGUMENT is returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. Filter expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + canonical_filter (str): + The default filter that is applied when a user performs a + search without checking any filters on the search page. + + The filter applied to every search request when quality + improvement such as query expansion is needed. For example, + if a query does not have enough results, an expanded query + with + [SearchRequest.canonical_filter][google.cloud.retail.v2beta.SearchRequest.canonical_filter] + will be returned as a supplement of the original query. This + field is strongly recommended to achieve high search + quality. + + See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for more details about filter syntax. + order_by (str): + The order in which products are returned. Products can be + ordered by a field in an + [Product][google.cloud.retail.v2beta.Product] object. Leave + it unset if ordered by relevance. OrderBy expression is + case-sensitive. See more details at this `user + guide `__. + + If this field is unrecognizable, an INVALID_ARGUMENT is + returned. + facet_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + dynamic_facet_spec (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec): + Deprecated. Refer to + https://cloud.google.com/retail/docs/configs#dynamic + to enable dynamic facets. Do not set this field. + The specification for dynamically generated + facets. Notice that only textual facets can be + dynamically generated. + boost_spec (google.cloud.retail_v2beta.types.SearchRequest.BoostSpec): + Boost specification to boost certain products. See more + details at this `user + guide `__. + + Notice that if both + [ServingConfig.boost_control_ids][google.cloud.retail.v2beta.ServingConfig.boost_control_ids] + and [SearchRequest.boost_spec] are set, the boost conditions + from both places are evaluated. If a search request matches + multiple boost conditions, the final boost score is equal to + the sum of the boost scores from all matched boost + conditions. + query_expansion_spec (google.cloud.retail_v2beta.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that specifies the + conditions under which query expansion will occur. See more + details at this `user + guide `__. + variant_rollup_keys (Sequence[str]): + The keys to fetch and rollup the matching + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s attributes, + [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo] + or + [LocalInventory][google.cloud.retail.v2beta.LocalInventory]s + attributes. The attributes from all the matching + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s or + [LocalInventory][google.cloud.retail.v2beta.LocalInventory]s + are merged and de-duplicated. Notice that rollup attributes + will lead to extra query latency. Maximum number of keys is + 30. + + For + [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], + a fulfillment type and a fulfillment ID must be provided in + the format of "fulfillmentType.fulfillmentId". E.g., in + "pickupInStore.store123", "pickupInStore" is fulfillment + type and "store123" is the store ID. + + Supported keys are: + + - colorFamilies + - price + - originalPrice + - discount + - variantId + - inventory(place_id,price) + - inventory(place_id,original_price) + - inventory(place_id,attributes.key), where key is any key + in the [Product.inventories.attributes][] map. + - attributes.key, where key is any key in the + [Product.attributes][google.cloud.retail.v2beta.Product.attributes] + map. + - pickupInStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "pickup-in-store". + - shipToStore.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "ship-to-store". + - sameDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "same-day-delivery". + - nextDayDelivery.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "next-day-delivery". + - customFulfillment1.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-1". + - customFulfillment2.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-2". + - customFulfillment3.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-3". + - customFulfillment4.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-4". + - customFulfillment5.id, where id is any + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + for + [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] + "custom-type-5". + + If this field is set to an invalid value other than these, + an INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. Required for + category navigation queries to achieve good search quality. + The format should be the same as + [UserEvent.page_categories][google.cloud.retail.v2beta.UserEvent.page_categories]; + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + search_mode (google.cloud.retail_v2beta.types.SearchRequest.SearchMode): + The search mode of the search request. If not + specified, a single search request triggers both + product search and faceted search. + personalization_spec (google.cloud.retail_v2beta.types.SearchRequest.PersonalizationSpec): + The specification for personalization. + """ + class SearchMode(proto.Enum): + r"""The search mode of each search request.""" + SEARCH_MODE_UNSPECIFIED = 0 + PRODUCT_SEARCH_ONLY = 1 + FACETED_SEARCH_ONLY = 2 + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.retail_v2beta.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum of facet values that should be returned for this + facet. If unspecified, defaults to 20. The maximum allowed + value is 300. Values above 300 will be coerced to 300. + + If this field is negative, an INVALID_ARGUMENT is returned. + excluded_filter_keys (Sequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + For example, suppose there are 100 products with color facet + "Red" and 200 products with color facet "Blue". A query + containing the filter "colorFamilies:ANY("Red")" and have + "colorFamilies" as + [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] + will by default return the "Red" with count 100. + + If this field contains "colorFamilies", then the query + returns both the "Red" with count 100 and "Blue" with count + 200, because the "colorFamilies" key is now excluded from + the filter. + + A maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined by Google Retail Search. It will be ordered + together with dynamic facets if dynamic facets is enabled. + If set to false, the position of this facet in the response + will be the same as in the request, and it will be ranked + before the facets with dynamic position enable and all + dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response will be determined by Google Retail + Search. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enable, which will + generate a facet 'gender'. Then the final order of the + facets in the response can be ("price", "brands", "rating", + "gender") or ("price", "brands", "gender", "rating") depends + on how Google Retail Search orders "gender" and "rating" + facets. However, notice that "price" and "brands" will + always be ranked at 1st and 2nd position since their + enable_dynamic_position are false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Product][google.cloud.retail.v2beta.Product] object, over + which the facet values are computed. Facet key is + case-sensitive. + + Allowed facet keys when + [FacetKey.query][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.query] + is not specified: + + - textual_field = + + - "brands" + - "categories" + - "genders" + - "ageGroups" + - "availability" + - "colorFamilies" + - "colors" + - "sizes" + - "materials" + - "patterns" + - "conditions" + - "attributes.key" + - "pickupInStore" + - "shipToStore" + - "sameDayDelivery" + - "nextDayDelivery" + - "customFulfillment1" + - "customFulfillment2" + - "customFulfillment3" + - "customFulfillment4" + - "customFulfillment5" + - "inventory(place_id,attributes.key)" + + - numerical_field = + + - "price" + - "discount" + - "rating" + - "ratingCount" + - "attributes.key" + - "inventory(place_id,price)" + - "inventory(place_id,original_price)" + - "inventory(place_id,attributes.key)". + intervals (Sequence[google.cloud.retail_v2beta.types.Interval]): + Set only if values should be bucketized into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (Sequence[str]): + Only get facet for the given restricted values. For example, + when using "pickupInStore" as key and set restricted values + to ["store123", "store456"], only facets for "store123" and + "store456" are returned. Only supported on textual fields + and fulfillments. Maximum is 20. + + Must be set for the fulfillment facet keys: + + - pickupInStore + + - shipToStore + + - sameDayDelivery + + - nextDayDelivery + + - customFulfillment1 + + - customFulfillment2 + + - customFulfillment3 + + - customFulfillment4 + + - customFulfillment5 + prefixes (Sequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "categories" has three values "Women > Shoe", + "Women > Dress" and "Men > Shoe". If set + "prefixes" to "Women", the "categories" facet + will give only "Women > Shoe" and "Women > + Dress". Only supported on textual fields. + Maximum is 10. + contains (Sequence[str]): + Only get facet values that contains the given + strings. For example, suppose "categories" has + three values "Women > Shoe", "Women > Dress" and + "Men > Shoe". If set "contains" to "Shoe", the + "categories" facet will give only "Women > Shoe" + and "Men > Shoe". Only supported on textual + fields. Maximum is 10. + order_by (str): + The order in which [Facet.values][] are returned. + + Allowed values are: + + - "count desc", which means order by + [Facet.FacetValue.count][] descending. + + - "value desc", which means order by + [Facet.FacetValue.value][] descending. Only applies to + textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.intervals]; + [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] + are sorted in the order given by + [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.restricted_values]. + query (str): + The query that is used to compute facet for the given facet + key. When provided, it will override the default behavior of + facet computation. The query syntax is the same as a filter + expression. See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for detail syntax and limitations. Notice that there is no + limitation on + [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] + when query is specified. + + In the response, [FacetValue.value][] will be always "1" and + [FacetValue.count][] will be the number of results that + matches the query. + + For example, you can set a customized facet for + "shipToStore", where + [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] + is "customizedShipToStore", and + [FacetKey.query][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.query] + is "availability: ANY("IN_STOCK") AND shipToStore: + ANY("123")". Then the facet will count the products that are + both in stock and ship to store "123". + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + intervals = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes = proto.RepeatedField( + proto.STRING, + number=8, + ) + contains = proto.RepeatedField( + proto.STRING, + number=9, + ) + order_by = proto.Field( + proto.STRING, + number=4, + ) + query = proto.Field( + proto.STRING, + number=5, + ) + + facet_key = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.FacetSpec.FacetKey', + ) + limit = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position = proto.Field( + proto.BOOL, + number=4, + ) + + class DynamicFacetSpec(proto.Message): + r"""The specifications of dynamically generated facets. + + Attributes: + mode (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec.Mode): + Mode of the DynamicFacet feature. Defaults to + [Mode.DISABLED][google.cloud.retail.v2beta.SearchRequest.DynamicFacetSpec.Mode.DISABLED] + if it's unset. + """ + class Mode(proto.Enum): + r"""Enum to control DynamicFacet mode""" + MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.DynamicFacetSpec.Mode', + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain items. + + Attributes: + condition_boost_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a product + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 10. + skip_boost_spec_validation (bool): + Whether to skip boostspec validation. If this field is set + to true, invalid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] + will be ignored and valid + [BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] + will still be applied. + + This field is a member of `oneof`_ ``_skip_boost_spec_validation``. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to products which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost products with product ID "product_1" or + "product_2", and color "Red" or "Blue": + + - (id: ANY("product_1", "product_2")) AND + (colorFamilies: ANY("Red","Blue")) + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the item a big promotion. However, it + does not necessarily mean that the boosted item will be the + top result at all times, nor that other items will be + excluded. Results could still be shown even when none of + them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant items. + + Setting to -1.0 gives the item a big demotion. However, + results that are deeply relevant might still be shown. The + item will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition = proto.Field( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + skip_boost_spec_validation = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.retail_v2beta.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.retail.v2beta.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 3 + + condition = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.QueryExpansionSpec.Condition', + ) + pin_unexpanded_results = proto.Field( + proto.BOOL, + number=2, + ) + + class PersonalizationSpec(proto.Message): + r"""The specification for personalization. + + Attributes: + mode (google.cloud.retail_v2beta.types.SearchRequest.PersonalizationSpec.Mode): + Defaults to + [Mode.AUTO][google.cloud.retail.v2beta.SearchRequest.PersonalizationSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""The personalization mode of each search request.""" + MODE_UNSPECIFIED = 0 + AUTO = 1 + DISABLED = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.PersonalizationSpec.Mode', + ) + + placement = proto.Field( + proto.STRING, + number=1, + ) + branch = proto.Field( + proto.STRING, + number=2, + ) + query = proto.Field( + proto.STRING, + number=3, + ) + visitor_id = proto.Field( + proto.STRING, + number=4, + ) + user_info = proto.Field( + proto.MESSAGE, + number=5, + message=common.UserInfo, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + offset = proto.Field( + proto.INT32, + number=9, + ) + filter = proto.Field( + proto.STRING, + number=10, + ) + canonical_filter = proto.Field( + proto.STRING, + number=28, + ) + order_by = proto.Field( + proto.STRING, + number=11, + ) + facet_specs = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=FacetSpec, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=21, + message=DynamicFacetSpec, + ) + boost_spec = proto.Field( + proto.MESSAGE, + number=13, + message=BoostSpec, + ) + query_expansion_spec = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionSpec, + ) + variant_rollup_keys = proto.RepeatedField( + proto.STRING, + number=17, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=23, + ) + search_mode = proto.Field( + proto.ENUM, + number=31, + enum=SearchMode, + ) + personalization_spec = proto.Field( + proto.MESSAGE, + number=32, + message=PersonalizationSpec, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] + method. + + Attributes: + results (Sequence[google.cloud.retail_v2beta.types.SearchResponse.SearchResult]): + A list of matched items. The order represents + the ranking. + facets (Sequence[google.cloud.retail_v2beta.types.SearchResponse.Facet]): + Results of facets requested by user. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.retail.v2beta.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.retail.v2beta.SearchResponse.total_size] + that matches. + corrected_query (str): + If spell correction applies, the corrected + query. Otherwise, empty. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.retail.v2beta.UserEvent] logs + resulting from this search, which enables accurate + attribution of search model performance. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.retail.v2beta.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + query_expansion_info (google.cloud.retail_v2beta.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search will be performed, and only + [redirect_uri][google.cloud.retail.v2beta.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.retail.v2beta.SearchResponse.attribution_token] + will be set in the response. + applied_controls (Sequence[str]): + The fully qualified resource name of applied + `controls `__. + invalid_condition_boost_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + The invalid + [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] + that are not applied during serving. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Product.id][google.cloud.retail.v2beta.Product.id] of the + searched [Product][google.cloud.retail.v2beta.Product]. + product (google.cloud.retail_v2beta.types.Product): + The product data snippet in the search response. Only + [Product.name][google.cloud.retail.v2beta.Product.name] is + guaranteed to be populated. + + [Product.variants][google.cloud.retail.v2beta.Product.variants] + contains the product variants that match the search query. + If there are multiple product variants matching the query, + top 5 most relevant product variants are returned and + ordered by relevancy. + + If relevancy can be deternmined, use + [matching_variant_fields][google.cloud.retail.v2beta.SearchResponse.SearchResult.matching_variant_fields] + to look up matched product variants fields. If relevancy + cannot be determined, e.g. when searching "shoe" all + products in a shoe product can be a match, 5 product + variants are returned but order is meaningless. + matching_variant_count (int): + The count of matched + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product]s. + matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): + If a + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] matches the + search query, this map indicates which + [Product][google.cloud.retail.v2beta.Product] fields are + matched. The key is the + [Product.name][google.cloud.retail.v2beta.Product.name], the + value is a field mask of the matched + [Product][google.cloud.retail.v2beta.Product] fields. If + matched attributes cannot be determined, this map will be + empty. + + For example, a key "sku1" with field mask + "products.color_info" indicates there is a match between + "sku1" [ColorInfo][google.cloud.retail.v2beta.ColorInfo] and + the query. + variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): + The rollup matching + [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] + [Product][google.cloud.retail.v2beta.Product] attributes. + The key is one of the + [SearchRequest.variant_rollup_keys][google.cloud.retail.v2beta.SearchRequest.variant_rollup_keys]. + The values are the merged and de-duplicated + [Product][google.cloud.retail.v2beta.Product] attributes. + Notice that the rollup values are respect filter. For + example, when filtering by "colorFamilies:ANY("red")" and + rollup "colorFamilies", only "red" is returned. + + For textual and numerical attributes, the rollup values is a + list of string or double values with type + [google.protobuf.ListValue][google.protobuf.ListValue]. For + example, if there are two variants with colors "red" and + "blue", the rollup values are + + :: + + { key: "colorFamilies" + value { + list_value { + values { string_value: "red" } + values { string_value: "blue" } + } + } + } + + For + [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], + the rollup values is a double value with type + [google.protobuf.Value][google.protobuf.Value]. For example, + ``{key: "pickupInStore.store1" value { number_value: 10 }}`` + means a there are 10 variants in this product are available + in the store "store1". + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + product = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_product.Product, + ) + matching_variant_count = proto.Field( + proto.INT32, + number=3, + ) + matching_variant_fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + variant_rollup_values = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. E.g., "colorFamilies" + or "price" or "attributes.attr1". + values (Sequence[google.cloud.retail_v2beta.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Text value of a facet, such as "Black" for + facet "colorFamilies". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.retail_v2beta.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value = proto.Field( + proto.STRING, + number=1, + oneof='facet_value', + ) + interval = proto.Field( + proto.MESSAGE, + number=2, + oneof='facet_value', + message=common.Interval, + ) + count = proto.Field( + proto.INT64, + number=3, + ) + + key = proto.Field( + proto.STRING, + number=1, + ) + values = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SearchResponse.Facet.FacetValue', + ) + dynamic_facet = proto.Field( + proto.BOOL, + number=3, + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2beta.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count = proto.Field( + proto.INT64, + number=2, + ) + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + corrected_query = proto.Field( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + next_page_token = proto.Field( + proto.STRING, + number=6, + ) + query_expansion_info = proto.Field( + proto.MESSAGE, + number=7, + message=QueryExpansionInfo, + ) + redirect_uri = proto.Field( + proto.STRING, + number=10, + ) + applied_controls = proto.RepeatedField( + proto.STRING, + number=12, + ) + invalid_condition_boost_specs = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py new file mode 100644 index 00000000..f8b78591 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py @@ -0,0 +1,309 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'ServingConfig', + }, +) + + +class ServingConfig(proto.Message): + r"""Configures metadata that is used to generate serving time results + (e.g. search results or recommendation predictions). The + ServingConfig is passed in the search and predict request and + together with the Catalog.default_branch, generates results. + + Attributes: + name (str): + Immutable. Fully qualified name + projects/\ */locations/global/catalogs/*/servingConfig/\* + display_name (str): + Required. The human readable serving config display name. + Used in Retail UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + model_id (str): + The id of the model to use at serving time. Currently only + RecommendationModels are supported: + https://cloud.google.com/retail/recommendations-ai/docs/create-models + Can be changed but only to a compatible model (e.g. + others-you-may-like CTR to others-you-may-like CVR). + + Required when + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + price_reranking_level (str): + How much price ranking we want in serving results. Price + reranking causes product items with a similar recommendation + probability to be ordered by price, with the highest-priced + items first. This setting could result in a decrease in + click-through and conversion rates. Allowed values are: + + - 'no-price-reranking' + - 'low-price-raranking' + - 'medium-price-reranking' + - 'high-price-reranking' + + If not specified, we choose default based on model type. + Default value: 'no-price-reranking'. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + facet_control_ids (Sequence[str]): + Facet specifications for faceted search. If empty, no facets + are returned. The ids refer to the ids of + [Control][google.cloud.retail.v2beta.Control] resources with + only the Facet control set. These controls are assumed to be + in the same [Catalog][google.cloud.retail.v2beta.Catalog] as + the + [ServingConfig][google.cloud.retail.v2beta.ServingConfig]. A + maximum of 100 values are allowed. Otherwise, an + INVALID_ARGUMENT error is returned. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + dynamic_facet_spec (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec): + The specification for dynamically generated facets. Notice + that only textual facets can be dynamically generated. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + boost_control_ids (Sequence[str]): + Condition boost specifications. If a product matches + multiple conditions in the specifications, boost scores from + these specifications are all applied and combined in a + non-linear way. Maximum number of specifications is 100. + + Notice that if both + [ServingConfig.boost_control_ids][google.cloud.retail.v2beta.ServingConfig.boost_control_ids] + and [SearchRequest.boost_spec] are set, the boost conditions + from both places are evaluated. If a search request matches + multiple boost conditions, the final boost score is equal to + the sum of the boost scores from all matched boost + conditions. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + filter_control_ids (Sequence[str]): + Condition filter specifications. If a product matches + multiple conditions in the specifications, filters from + these specifications are all applied and combined via the + AND operator. Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + redirect_control_ids (Sequence[str]): + Condition redirect specifications. Only the first triggered + redirect action is applied, even if multiple apply. Maximum + number of specifications is 1000. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + twoway_synonyms_control_ids (Sequence[str]): + Condition synonyms specifications. If multiple syonyms + conditions match, all matching synonyms control in the list + will execute. Order of controls in the list will not matter. + Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + oneway_synonyms_control_ids (Sequence[str]): + Condition oneway synonyms specifications. If multiple oneway + synonyms conditions match, all matching oneway synonyms + controls in the list will execute. Order of controls in the + list will not matter. Maximum number of specifications is + 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + do_not_associate_control_ids (Sequence[str]): + Condition do not associate specifications. If multiple do + not associate conditions match, all matching do not + associate controls in the list will execute. + + - Order does not matter. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + replacement_control_ids (Sequence[str]): + Condition replacement specifications. + + - Applied according to the order in the list. + - A previously replaced term can not be re-replaced. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + ignore_control_ids (Sequence[str]): + Condition ignore specifications. If multiple ignore + conditions match, all matching ignore controls in the list + will execute. + + - Order does not matter. + - Maximum number of specifications is 100. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. + diversity_level (str): + How much diversity to use in recommendation model results + e.g. 'medium-diversity' or 'high-diversity'. Currently + supported values: + + - 'no-diversity' + - 'low-diversity' + - 'medium-diversity' + - 'high-diversity' + - 'auto-diversity' + + If not specified, we choose default based on recommendation + model type. Default value: 'no-diversity'. + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + enable_category_filter_level (str): + Whether to add additional category filters on the + 'similar-items' model. If not specified, we enable it by + default. Allowed values are: + + - 'no-category-match': No additional filtering of original + results from the model and the customer's filters. + - 'relaxed-category-match': Only keep results with + categories that match at least one item categories in the + PredictRequests's context item. + + - If customer also sends filters in the PredictRequest, + then the results will satisfy both conditions (user + given and category match). + + Can only be set if + [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + solution_types (Sequence[google.cloud.retail_v2beta.types.SolutionType]): + Required. Immutable. Specifies the solution + types that a serving config can be associated + with. Currently we support setting only one type + of solution. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + model_id = proto.Field( + proto.STRING, + number=3, + ) + price_reranking_level = proto.Field( + proto.STRING, + number=4, + ) + facet_control_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + dynamic_facet_spec = proto.Field( + proto.MESSAGE, + number=6, + message=search_service.SearchRequest.DynamicFacetSpec, + ) + boost_control_ids = proto.RepeatedField( + proto.STRING, + number=7, + ) + filter_control_ids = proto.RepeatedField( + proto.STRING, + number=9, + ) + redirect_control_ids = proto.RepeatedField( + proto.STRING, + number=10, + ) + twoway_synonyms_control_ids = proto.RepeatedField( + proto.STRING, + number=18, + ) + oneway_synonyms_control_ids = proto.RepeatedField( + proto.STRING, + number=12, + ) + do_not_associate_control_ids = proto.RepeatedField( + proto.STRING, + number=13, + ) + replacement_control_ids = proto.RepeatedField( + proto.STRING, + number=14, + ) + ignore_control_ids = proto.RepeatedField( + proto.STRING, + number=15, + ) + diversity_level = proto.Field( + proto.STRING, + number=8, + ) + enable_category_filter_level = proto.Field( + proto.STRING, + number=16, + ) + solution_types = proto.RepeatedField( + proto.ENUM, + number=19, + enum=common.SolutionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py new file mode 100644 index 00000000..20edced0 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py @@ -0,0 +1,234 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'CreateServingConfigRequest', + 'UpdateServingConfigRequest', + 'DeleteServingConfigRequest', + 'GetServingConfigRequest', + 'ListServingConfigsRequest', + 'ListServingConfigsResponse', + 'AddControlRequest', + 'RemoveControlRequest', + }, +) + + +class CreateServingConfigRequest(proto.Message): + r"""Request for CreateServingConfig method. + + Attributes: + parent (str): + Required. Full resource name of parent. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + serving_config (google.cloud.retail_v2beta.types.ServingConfig): + Required. The ServingConfig to create. + serving_config_id (str): + Required. The ID to use for the ServingConfig, which will + become the final component of the ServingConfig's resource + name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-_/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + serving_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_serving_config.ServingConfig, + ) + serving_config_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateServingConfigRequest(proto.Message): + r"""Request for UpdateServingConfig method. + + Attributes: + serving_config (google.cloud.retail_v2beta.types.ServingConfig): + Required. The ServingConfig to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [ServingConfig][google.cloud.retail.v2beta.ServingConfig] to + update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] + + If not set, all supported fields are updated. + """ + + serving_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_serving_config.ServingConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteServingConfigRequest(proto.Message): + r"""Request for DeleteServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to delete. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetServingConfigRequest(proto.Message): + r"""Request for GetServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to get. + Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListServingConfigsRequest(proto.Message): + r"""Request for ListServingConfigs method. + + Attributes: + parent (str): + Required. The catalog resource name. Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 100. If a + value greater than 100 is provided, at most 100 + results are returned. + page_token (str): + Optional. A page token, received from a previous + ``ListServingConfigs`` call. Provide this to retrieve the + subsequent page. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServingConfigsResponse(proto.Message): + r"""Response for ListServingConfigs method. + + Attributes: + serving_configs (Sequence[google.cloud.retail_v2beta.types.ServingConfig]): + All the ServingConfigs for a given catalog. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + serving_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_serving_config.ServingConfig, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class AddControlRequest(proto.Message): + r"""Request for AddControl method. + + Attributes: + serving_config (str): + Required. The source ServingConfig resource name . Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + control_id (str): + Required. The id of the control to apply. Assumed to be in + the same catalog as the serving config - if id is not found + a NOT_FOUND error is returned. + """ + + serving_config = proto.Field( + proto.STRING, + number=1, + ) + control_id = proto.Field( + proto.STRING, + number=2, + ) + + +class RemoveControlRequest(proto.Message): + r"""Request for RemoveControl method. + + Attributes: + serving_config (str): + Required. The source ServingConfig resource name . Format: + projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} + control_id (str): + Required. The id of the control to apply. + Assumed to be in the same catalog as the serving + config. + """ + + serving_config = proto.Field( + proto.STRING, + number=1, + ) + control_id = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py new file mode 100644 index 00000000..bf1b1aee --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py @@ -0,0 +1,507 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import product as gcr_product +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'UserEvent', + 'ProductDetail', + 'CompletionDetail', + 'PurchaseTransaction', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Retail API needs + to know about how end users interact with customers' website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + - ``add-to-cart``: Products being added to cart. + - ``category-page-view``: Special pages such as sale or + promotion pages viewed. + - ``detail-page-view``: Products detail page viewed. + - ``home-page-view``: Homepage viewed. + - ``promotion-offered``: Promotion is offered to a user. + - ``promotion-not-offered``: Promotion is not offered to a + user. + - ``purchase-complete``: User finishing a purchase. + - ``search``: Product search. + - ``shopping-cart-page-view``: User viewing a shopping + cart. + visitor_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + The field should not contain PII or user-data. We recommend + to use Google Analystics `Client + ID `__ + for this field. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the sesion_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add visitor_id as prefix. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.retail.v2beta.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + experiment_ids (Sequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups + (e.g. using Retail API, using different + recommendation models). + attribution_token (str): + Highly recommended for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2beta.PredictionService.Predict]. + This field enables accurate attribution of recommendation + model performance. + + The value must be a valid + [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] + for user events that are the result of + [PredictionService.Predict][google.cloud.retail.v2beta.PredictionService.Predict]. + The value must be a valid + [SearchResponse.attribution_token][google.cloud.retail.v2beta.SearchResponse.attribution_token] + for user events that are the result of + [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. + + This token enables us to accurately attribute page view or + purchase back to the event and the particular predict + response containing this clicked/purchased product. If user + clicks on product K in the recommendation results, pass + [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] + as a URL parameter to product K's page. When recording + events on product K's page, log the + [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] + to this field. + product_details (Sequence[google.cloud.retail_v2beta.types.ProductDetail]): + The main product details related to the event. + + This field is required for the following event types: + + - ``add-to-cart`` + - ``detail-page-view`` + - ``purchase-complete`` + - ``search`` + + In a ``search`` event, this field represents the products + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [product_details][google.cloud.retail.v2beta.UserEvent.product_details] + is desired. The end user may have not finished browsing the + whole page yet. + completion_detail (google.cloud.retail_v2beta.types.CompletionDetail): + The main auto-completion details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Retail API use those + custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + INVALID_ARGUMENT error is returned: + + - The key must be a UTF-8 encoded string with a length + limit of 5,000 characters. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a UTF-8 + encoded string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is traffic_channel, which is how a user arrives + at the site. Users can arrive at the site by coming to the + site directly, coming through Google search, or in other + ways. + cart_id (str): + The ID or name of the associated shopping cart. This ID is + used to associate multiple items added or present in the + cart before purchase. + + This can only be set for ``add-to-cart``, + ``purchase-complete``, or ``shopping-cart-page-view`` + events. + purchase_transaction (google.cloud.retail_v2beta.types.PurchaseTransaction): + A transaction represents the entire purchase transaction. + + Required for ``purchase-complete`` events. Other event types + should not set this field. Otherwise, an INVALID_ARGUMENT + error is returned. + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.retail.v2beta.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + At least one of + [search_query][google.cloud.retail.v2beta.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2beta.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + products being filtered. + + See + [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + order_by (str): + The order in which products are returned. + + See + [SearchRequest.order_by][google.cloud.retail.v2beta.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.retail.v2beta.SearchRequest.offset] + for definition. + + If this field is negative, an INVALID_ARGUMENT is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + INVALID_ARGUMENT error is returned. + page_categories (Sequence[str]): + The categories associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: "pageCategories" : ["Sales > 2017 Black + Friday Deals"]. + + Required for ``category-page-view`` events. At least one of + [search_query][google.cloud.retail.v2beta.UserEvent.search_query] + or + [page_categories][google.cloud.retail.v2beta.UserEvent.page_categories] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an INVALID_ARGUMENT error is + returned. + user_info (google.cloud.retail_v2beta.types.UserInfo): + User information. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. + page_view_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageViewId`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + """ + + event_type = proto.Field( + proto.STRING, + number=1, + ) + visitor_id = proto.Field( + proto.STRING, + number=2, + ) + session_id = proto.Field( + proto.STRING, + number=21, + ) + event_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + experiment_ids = proto.RepeatedField( + proto.STRING, + number=4, + ) + attribution_token = proto.Field( + proto.STRING, + number=5, + ) + product_details = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ProductDetail', + ) + completion_detail = proto.Field( + proto.MESSAGE, + number=22, + message='CompletionDetail', + ) + attributes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=common.CustomAttribute, + ) + cart_id = proto.Field( + proto.STRING, + number=8, + ) + purchase_transaction = proto.Field( + proto.MESSAGE, + number=9, + message='PurchaseTransaction', + ) + search_query = proto.Field( + proto.STRING, + number=10, + ) + filter = proto.Field( + proto.STRING, + number=16, + ) + order_by = proto.Field( + proto.STRING, + number=17, + ) + offset = proto.Field( + proto.INT32, + number=18, + ) + page_categories = proto.RepeatedField( + proto.STRING, + number=11, + ) + user_info = proto.Field( + proto.MESSAGE, + number=12, + message=common.UserInfo, + ) + uri = proto.Field( + proto.STRING, + number=13, + ) + referrer_uri = proto.Field( + proto.STRING, + number=14, + ) + page_view_id = proto.Field( + proto.STRING, + number=15, + ) + + +class ProductDetail(proto.Message): + r"""Detailed product information associated with a user event. + + Attributes: + product (google.cloud.retail_v2beta.types.Product): + Required. [Product][google.cloud.retail.v2beta.Product] + information. + + Required field(s): + + - [Product.id][google.cloud.retail.v2beta.Product.id] + + Optional override field(s): + + - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] + + If any supported optional fields are provided, we will treat + them as a full override when looking up product information + from the catalog. Thus, it is important to ensure that the + overriding fields are accurate and complete. + + All other product fields are ignored and instead populated + via catalog lookup after event ingestion. + quantity (google.protobuf.wrappers_pb2.Int32Value): + Quantity of the product associated with the user event. + + For example, this field will be 2 if two products are added + to the shopping cart for ``purchase-complete`` event. + Required for ``add-to-cart`` and ``purchase-complete`` event + types. + """ + + product = proto.Field( + proto.MESSAGE, + number=1, + message=gcr_product.Product, + ) + quantity = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +class CompletionDetail(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + completion_attribution_token (str): + Completion attribution token in + [CompleteQueryResponse.attribution_token][google.cloud.retail.v2beta.CompleteQueryResponse.attribution_token]. + selected_suggestion (str): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2beta.CompleteQueryResponse.CompletionResult.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2beta.CompleteQueryResponse.CompletionResult.suggestion] + position, starting from 0. + """ + + completion_attribution_token = proto.Field( + proto.STRING, + number=1, + ) + selected_suggestion = proto.Field( + proto.STRING, + number=2, + ) + selected_position = proto.Field( + proto.INT32, + number=3, + ) + + +class PurchaseTransaction(proto.Message): + r"""A transaction represents the entire purchase transaction. + + Attributes: + id (str): + The transaction ID with a length limit of 128 + characters. + revenue (float): + Required. Total non-zero revenue or grand + total associated with the transaction. This + value include shipping, tax, or other + adjustments to total revenue that you want to + include as part of your revenue calculations. + tax (float): + All the taxes associated with the + transaction. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [revenue][google.cloud.retail.v2beta.PurchaseTransaction.revenue] + - + [tax][google.cloud.retail.v2beta.PurchaseTransaction.tax] + - + [cost][google.cloud.retail.v2beta.PurchaseTransaction.cost] + currency_code (str): + Required. Currency code. Use three-character + ISO-4217 code. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + revenue = proto.Field( + proto.FLOAT, + number=2, + ) + tax = proto.Field( + proto.FLOAT, + number=3, + ) + cost = proto.Field( + proto.FLOAT, + number=4, + ) + currency_code = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py new file mode 100644 index 00000000..990180c4 --- /dev/null +++ b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.retail_v2beta.types import user_event as gcr_user_event + + +__protobuf__ = proto.module( + package='google.cloud.retail.v2beta', + manifest={ + 'WriteUserEventRequest', + 'CollectUserEventRequest', + 'RejoinUserEventsRequest', + 'RejoinUserEventsResponse', + 'RejoinUserEventsMetadata', + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (google.cloud.retail_v2beta.types.UserEvent): + Required. User event to write. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + Attributes: + parent (str): + Required. The parent catalog name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for 3rd party requests. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.STRING, + number=2, + ) + uri = proto.Field( + proto.STRING, + number=3, + ) + ets = proto.Field( + proto.INT64, + number=4, + ) + + +class RejoinUserEventsRequest(proto.Message): + r"""Request message for RejoinUserEvents method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog``. + user_event_rejoin_scope (google.cloud.retail_v2beta.types.RejoinUserEventsRequest.UserEventRejoinScope): + The type of the user event rejoin to define the scope and + range of the user events to be rejoined with the latest + product catalog. Defaults to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not + set, or set to an invalid integer value. + """ + class UserEventRejoinScope(proto.Enum): + r"""The scope of user events to be rejoined with the latest product + catalog. If the rejoining aims at reducing number of unjoined + events, set UserEventRejoinScope to UNJOINED_EVENTS. If the + rejoining aims at correcting product catalog information in joined + events, set UserEventRejoinScope to JOINED_EVENTS. If all events + needs to be rejoined, set UserEventRejoinScope to + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. + """ + USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 + JOINED_EVENTS = 1 + UNJOINED_EVENTS = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event_rejoin_scope = proto.Field( + proto.ENUM, + number=2, + enum=UserEventRejoinScope, + ) + + +class RejoinUserEventsResponse(proto.Message): + r"""Response message for RejoinUserEvents method. + + Attributes: + rejoined_user_events_count (int): + Number of user events that were joined with + latest product catalog. + """ + + rejoined_user_events_count = proto.Field( + proto.INT64, + number=1, + ) + + +class RejoinUserEventsMetadata(proto.Message): + r"""Metadata for RejoinUserEvents method. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/mypy.ini b/owl-bot-staging/v2beta/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v2beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2beta/noxfile.py b/owl-bot-staging/v2beta/noxfile.py new file mode 100644 index 00000000..5abd48a4 --- /dev/null +++ b/owl-bot-staging/v2beta/noxfile.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.6", + "3.7", + "3.8", + "3.9", + "3.10", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==19.10b0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.9" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/retail_v2beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py new file mode 100644 index 00000000..09847366 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_AddCatalogAttribute_async] +from google.cloud import retail_v2beta + + +async def sample_add_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_AddCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py new file mode 100644 index 00000000..4f05ae26 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync] +from google.cloud import retail_v2beta + + +def sample_add_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.AddCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.add_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py new file mode 100644 index 00000000..637bfe3a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetAttributesConfig_async] +from google.cloud import retail_v2beta + + +async def sample_get_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetAttributesConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py new file mode 100644 index 00000000..c347bee2 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetAttributesConfig_sync] +from google.cloud import retail_v2beta + + +def sample_get_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetAttributesConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetAttributesConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py new file mode 100644 index 00000000..2133e940 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetCompletionConfig_async] +from google.cloud import retail_v2beta + + +async def sample_get_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetCompletionConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py new file mode 100644 index 00000000..bb9bf00d --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetCompletionConfig_sync] +from google.cloud import retail_v2beta + + +def sample_get_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetCompletionConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetCompletionConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py new file mode 100644 index 00000000..e598ec09 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetDefaultBranch_async] +from google.cloud import retail_v2beta + + +async def sample_get_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetDefaultBranchRequest( + ) + + # Make the request + response = await client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py new file mode 100644 index 00000000..6adcb072 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_GetDefaultBranch_sync] +from google.cloud import retail_v2beta + + +def sample_get_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetDefaultBranchRequest( + ) + + # Make the request + response = client.get_default_branch(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py new file mode 100644 index 00000000..b4e3df0e --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_ListCatalogs_async] +from google.cloud import retail_v2beta + + +async def sample_list_catalogs(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py new file mode 100644 index 00000000..d938f3ae --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_ListCatalogs_sync] +from google.cloud import retail_v2beta + + +def sample_list_catalogs(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py new file mode 100644 index 00000000..032fb3c6 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async] +from google.cloud import retail_v2beta + + +async def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = await client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py new file mode 100644 index 00000000..f1ecc22b --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync] +from google.cloud import retail_v2beta + + +def sample_remove_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveCatalogAttributeRequest( + attributes_config="attributes_config_value", + key="key_value", + ) + + # Make the request + response = client.remove_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py new file mode 100644 index 00000000..8a87262f --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReplaceCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async] +from google.cloud import retail_v2beta + + +async def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = await client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py new file mode 100644 index 00000000..24b38d05 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReplaceCatalogAttribute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync] +from google.cloud import retail_v2beta + + +def sample_replace_catalog_attribute(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog_attribute = retail_v2beta.CatalogAttribute() + catalog_attribute.key = "key_value" + + request = retail_v2beta.ReplaceCatalogAttributeRequest( + attributes_config="attributes_config_value", + catalog_attribute=catalog_attribute, + ) + + # Make the request + response = client.replace_catalog_attribute(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py new file mode 100644 index 00000000..6eec0779 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_SetDefaultBranch_async] +from google.cloud import retail_v2beta + + +async def sample_set_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.SetDefaultBranchRequest( + ) + + # Make the request + await client.set_default_branch(request=request) + + +# [END retail_v2beta_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py new file mode 100644 index 00000000..a3deb8fd --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetDefaultBranch +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_SetDefaultBranch_sync] +from google.cloud import retail_v2beta + + +def sample_set_default_branch(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.SetDefaultBranchRequest( + ) + + # Make the request + client.set_default_branch(request=request) + + +# [END retail_v2beta_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py new file mode 100644 index 00000000..b4a235ec --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async] +from google.cloud import retail_v2beta + + +async def sample_update_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + attributes_config = retail_v2beta.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2beta.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = await client.update_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py new file mode 100644 index 00000000..8f82ee5d --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttributesConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync] +from google.cloud import retail_v2beta + + +def sample_update_attributes_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + attributes_config = retail_v2beta.AttributesConfig() + attributes_config.name = "name_value" + + request = retail_v2beta.UpdateAttributesConfigRequest( + attributes_config=attributes_config, + ) + + # Make the request + response = client.update_attributes_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py new file mode 100644 index 00000000..772504ff --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateCatalog_async] +from google.cloud import retail_v2beta + + +async def sample_update_catalog(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog = retail_v2beta.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2beta.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = await client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py new file mode 100644 index 00000000..ed59d356 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateCatalog_sync] +from google.cloud import retail_v2beta + + +def sample_update_catalog(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + catalog = retail_v2beta.Catalog() + catalog.name = "name_value" + catalog.display_name = "display_name_value" + + request = retail_v2beta.UpdateCatalogRequest( + catalog=catalog, + ) + + # Make the request + response = client.update_catalog(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py new file mode 100644 index 00000000..377166a7 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async] +from google.cloud import retail_v2beta + + +async def sample_update_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceAsyncClient() + + # Initialize request argument(s) + completion_config = retail_v2beta.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2beta.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = await client.update_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py new file mode 100644 index 00000000..f641f121 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCompletionConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync] +from google.cloud import retail_v2beta + + +def sample_update_completion_config(): + # Create a client + client = retail_v2beta.CatalogServiceClient() + + # Initialize request argument(s) + completion_config = retail_v2beta.CompletionConfig() + completion_config.name = "name_value" + + request = retail_v2beta.UpdateCompletionConfigRequest( + completion_config=completion_config, + ) + + # Make the request + response = client.update_completion_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py new file mode 100644 index 00000000..96fdc6a6 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CompletionService_CompleteQuery_async] +from google.cloud import retail_v2beta + + +async def sample_complete_query(): + # Create a client + client = retail_v2beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py new file mode 100644 index 00000000..afb0ba7d --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CompletionService_CompleteQuery_sync] +from google.cloud import retail_v2beta + + +def sample_complete_query(): + # Create a client + client = retail_v2beta.CompletionServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.CompleteQueryRequest( + catalog="catalog_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py new file mode 100644 index 00000000..912753e9 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CompletionService_ImportCompletionData_async] +from google.cloud import retail_v2beta + + +async def sample_import_completion_data(): + # Create a client + client = retail_v2beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2beta.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py new file mode 100644 index 00000000..2cbd277d --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_CompletionService_ImportCompletionData_sync] +from google.cloud import retail_v2beta + + +def sample_import_completion_data(): + # Create a client + client = retail_v2beta.CompletionServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.CompletionDataInputConfig() + input_config.big_query_source.dataset_id = "dataset_id_value" + input_config.big_query_source.table_id = "table_id_value" + + request = retail_v2beta.ImportCompletionDataRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_completion_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py new file mode 100644 index 00000000..51e0cb4f --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_CreateControl_async] +from google.cloud import retail_v2beta + + +async def sample_create_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = await client.create_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_CreateControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py new file mode 100644 index 00000000..8d16b152 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_CreateControl_sync] +from google.cloud import retail_v2beta + + +def sample_create_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateControlRequest( + parent="parent_value", + control=control, + control_id="control_id_value", + ) + + # Make the request + response = client.create_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_CreateControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py new file mode 100644 index 00000000..cb18f6ba --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_DeleteControl_async] +from google.cloud import retail_v2beta + + +async def sample_delete_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteControlRequest( + name="name_value", + ) + + # Make the request + await client.delete_control(request=request) + + +# [END retail_v2beta_generated_ControlService_DeleteControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py new file mode 100644 index 00000000..8a0d4f56 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_DeleteControl_sync] +from google.cloud import retail_v2beta + + +def sample_delete_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteControlRequest( + name="name_value", + ) + + # Make the request + client.delete_control(request=request) + + +# [END retail_v2beta_generated_ControlService_DeleteControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py new file mode 100644 index 00000000..f9eeb9fd --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_GetControl_async] +from google.cloud import retail_v2beta + + +async def sample_get_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetControlRequest( + name="name_value", + ) + + # Make the request + response = await client.get_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_GetControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py new file mode 100644 index 00000000..ee0de08a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_GetControl_sync] +from google.cloud import retail_v2beta + + +def sample_get_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetControlRequest( + name="name_value", + ) + + # Make the request + response = client.get_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_GetControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py new file mode 100644 index 00000000..9a645706 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListControls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_ListControls_async] +from google.cloud import retail_v2beta + + +async def sample_list_controls(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_ControlService_ListControls_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py new file mode 100644 index 00000000..97c8ba62 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListControls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_ListControls_sync] +from google.cloud import retail_v2beta + + +def sample_list_controls(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListControlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_controls(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_ControlService_ListControls_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py new file mode 100644 index 00000000..9a42018c --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_UpdateControl_async] +from google.cloud import retail_v2beta + + +async def sample_update_control(): + # Create a client + client = retail_v2beta.ControlServiceAsyncClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateControlRequest( + control=control, + ) + + # Make the request + response = await client.update_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_UpdateControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py new file mode 100644 index 00000000..2a306202 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ControlService_UpdateControl_sync] +from google.cloud import retail_v2beta + + +def sample_update_control(): + # Create a client + client = retail_v2beta.ControlServiceClient() + + # Initialize request argument(s) + control = retail_v2beta.Control() + control.facet_spec.facet_key.key = "key_value" + control.display_name = "display_name_value" + control.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateControlRequest( + control=control, + ) + + # Make the request + response = client.update_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ControlService_UpdateControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py new file mode 100644 index 00000000..fd37548f --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_PredictionService_Predict_async] +from google.cloud import retail_v2beta + + +async def sample_predict(): + # Create a client + client = retail_v2beta.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = await client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py new file mode 100644 index 00000000..6975056e --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_PredictionService_Predict_sync] +from google.cloud import retail_v2beta + + +def sample_predict(): + # Create a client + client = retail_v2beta.PredictionServiceClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.PredictRequest( + placement="placement_value", + user_event=user_event, + ) + + # Make the request + response = client.predict(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py new file mode 100644 index 00000000..92a7a7e1 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async] +from google.cloud import retail_v2beta + + +async def sample_add_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py new file mode 100644 index 00000000..d828edde --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync] +from google.cloud import retail_v2beta + + +def sample_add_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.add_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py new file mode 100644 index 00000000..ebcf5c80 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_AddLocalInventories_async] +from google.cloud import retail_v2beta + + +async def sample_add_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py new file mode 100644 index 00000000..9d3d9ab0 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_AddLocalInventories_sync] +from google.cloud import retail_v2beta + + +def sample_add_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddLocalInventoriesRequest( + product="product_value", + ) + + # Make the request + operation = client.add_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py new file mode 100644 index 00000000..2bba20c0 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_CreateProduct_async] +from google.cloud import retail_v2beta + + +async def sample_create_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = await client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py new file mode 100644 index 00000000..32bd03e2 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_CreateProduct_sync] +from google.cloud import retail_v2beta + + +def sample_create_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.CreateProductRequest( + parent="parent_value", + product=product, + product_id="product_id_value", + ) + + # Make the request + response = client.create_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py new file mode 100644 index 00000000..8f9591fa --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_DeleteProduct_async] +from google.cloud import retail_v2beta + + +async def sample_delete_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteProductRequest( + name="name_value", + ) + + # Make the request + await client.delete_product(request=request) + + +# [END retail_v2beta_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py new file mode 100644 index 00000000..56630734 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_DeleteProduct_sync] +from google.cloud import retail_v2beta + + +def sample_delete_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteProductRequest( + name="name_value", + ) + + # Make the request + client.delete_product(request=request) + + +# [END retail_v2beta_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py new file mode 100644 index 00000000..f8dcfc01 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_GetProduct_async] +from google.cloud import retail_v2beta + + +async def sample_get_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py new file mode 100644 index 00000000..ab5cd918 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_GetProduct_sync] +from google.cloud import retail_v2beta + + +def sample_get_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py new file mode 100644 index 00000000..aa4256cc --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_ImportProducts_async] +from google.cloud import retail_v2beta + + +async def sample_import_products(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2beta.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py new file mode 100644 index 00000000..b4bc8314 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_ImportProducts_sync] +from google.cloud import retail_v2beta + + +def sample_import_products(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.ProductInputConfig() + input_config.product_inline_source.products.title = "title_value" + + request = retail_v2beta.ImportProductsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_products(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py new file mode 100644 index 00000000..e259ecd6 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_ListProducts_async] +from google.cloud import retail_v2beta + + +async def sample_list_products(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py new file mode 100644 index 00000000..5cb40315 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_ListProducts_sync] +from google.cloud import retail_v2beta + + +def sample_list_products(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py new file mode 100644 index 00000000..1b18eb50 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async] +from google.cloud import retail_v2beta + + +async def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py new file mode 100644 index 00000000..f430e360 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveFulfillmentPlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync] +from google.cloud import retail_v2beta + + +def sample_remove_fulfillment_places(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveFulfillmentPlacesRequest( + product="product_value", + type_="type__value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_fulfillment_places(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py new file mode 100644 index 00000000..55fba819 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_RemoveLocalInventories_async] +from google.cloud import retail_v2beta + + +async def sample_remove_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py new file mode 100644 index 00000000..31d1e58e --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_RemoveLocalInventories_sync] +from google.cloud import retail_v2beta + + +def sample_remove_local_inventories(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveLocalInventoriesRequest( + product="product_value", + place_ids=['place_ids_value_1', 'place_ids_value_2'], + ) + + # Make the request + operation = client.remove_local_inventories(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py new file mode 100644 index 00000000..9b467025 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_SetInventory_async] +from google.cloud import retail_v2beta + + +async def sample_set_inventory(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + inventory = retail_v2beta.Product() + inventory.title = "title_value" + + request = retail_v2beta.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py new file mode 100644 index 00000000..d1061827 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_SetInventory_sync] +from google.cloud import retail_v2beta + + +def sample_set_inventory(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + inventory = retail_v2beta.Product() + inventory.title = "title_value" + + request = retail_v2beta.SetInventoryRequest( + inventory=inventory, + ) + + # Make the request + operation = client.set_inventory(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py new file mode 100644 index 00000000..8d9590cd --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_UpdateProduct_async] +from google.cloud import retail_v2beta + + +async def sample_update_product(): + # Create a client + client = retail_v2beta.ProductServiceAsyncClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.UpdateProductRequest( + product=product, + ) + + # Make the request + response = await client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py new file mode 100644 index 00000000..fc614e58 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ProductService_UpdateProduct_sync] +from google.cloud import retail_v2beta + + +def sample_update_product(): + # Create a client + client = retail_v2beta.ProductServiceClient() + + # Initialize request argument(s) + product = retail_v2beta.Product() + product.title = "title_value" + + request = retail_v2beta.UpdateProductRequest( + product=product, + ) + + # Make the request + response = client.update_product(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py new file mode 100644 index 00000000..967c9102 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_SearchService_Search_async] +from google.cloud import retail_v2beta + + +async def sample_search(): + # Create a client + client = retail_v2beta.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py new file mode 100644 index 00000000..1e6a5045 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_SearchService_Search_sync] +from google.cloud import retail_v2beta + + +def sample_search(): + # Create a client + client = retail_v2beta.SearchServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.SearchRequest( + placement="placement_value", + visitor_id="visitor_id_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py new file mode 100644 index 00000000..d6554386 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_AddControl_async] +from google.cloud import retail_v2beta + + +async def sample_add_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.add_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_AddControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py new file mode 100644 index 00000000..e61e4e2a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_AddControl_sync] +from google.cloud import retail_v2beta + + +def sample_add_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.AddControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.add_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_AddControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py new file mode 100644 index 00000000..b09fadf2 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_CreateServingConfig_async] +from google.cloud import retail_v2beta + + +async def sample_create_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = await client.create_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_CreateServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py new file mode 100644 index 00000000..5d4c0993 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync] +from google.cloud import retail_v2beta + + +def sample_create_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.CreateServingConfigRequest( + parent="parent_value", + serving_config=serving_config, + serving_config_id="serving_config_id_value", + ) + + # Make the request + response = client.create_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py new file mode 100644 index 00000000..c0b03659 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async] +from google.cloud import retail_v2beta + + +async def sample_delete_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_serving_config(request=request) + + +# [END retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py new file mode 100644 index 00000000..1db19c0a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync] +from google.cloud import retail_v2beta + + +def sample_delete_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.DeleteServingConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_serving_config(request=request) + + +# [END retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py new file mode 100644 index 00000000..64f6aeef --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_GetServingConfig_async] +from google.cloud import retail_v2beta + + +async def sample_get_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_GetServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py new file mode 100644 index 00000000..1cfab934 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_GetServingConfig_sync] +from google.cloud import retail_v2beta + + +def sample_get_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.GetServingConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_GetServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py new file mode 100644 index 00000000..7ad0a3aa --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServingConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_ListServingConfigs_async] +from google.cloud import retail_v2beta + + +async def sample_list_serving_configs(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END retail_v2beta_generated_ServingConfigService_ListServingConfigs_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py new file mode 100644 index 00000000..6a3e7e2a --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServingConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync] +from google.cloud import retail_v2beta + + +def sample_list_serving_configs(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.ListServingConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_serving_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py new file mode 100644 index 00000000..c9994a00 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_RemoveControl_async] +from google.cloud import retail_v2beta + + +async def sample_remove_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = await client.remove_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_RemoveControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py new file mode 100644 index 00000000..db6dfa93 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveControl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_RemoveControl_sync] +from google.cloud import retail_v2beta + + +def sample_remove_control(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RemoveControlRequest( + serving_config="serving_config_value", + control_id="control_id_value", + ) + + # Make the request + response = client.remove_control(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_RemoveControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py new file mode 100644 index 00000000..2a6bd3a0 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async] +from google.cloud import retail_v2beta + + +async def sample_update_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceAsyncClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = await client.update_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py new file mode 100644 index 00000000..f6441e46 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServingConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync] +from google.cloud import retail_v2beta + + +def sample_update_serving_config(): + # Create a client + client = retail_v2beta.ServingConfigServiceClient() + + # Initialize request argument(s) + serving_config = retail_v2beta.ServingConfig() + serving_config.display_name = "display_name_value" + serving_config.solution_types = "SOLUTION_TYPE_SEARCH" + + request = retail_v2beta.UpdateServingConfigRequest( + serving_config=serving_config, + ) + + # Make the request + response = client.update_serving_config(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 00000000..ce80fabf --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_CollectUserEvent_async] +from google.cloud import retail_v2beta + + +async def sample_collect_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 00000000..ff7df192 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_CollectUserEvent_sync] +from google.cloud import retail_v2beta + + +def sample_collect_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py new file mode 100644 index 00000000..259c3424 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_ImportUserEvents_async] +from google.cloud import retail_v2beta + + +async def sample_import_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + input_config = retail_v2beta.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2beta.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 00000000..89e0ec02 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_ImportUserEvents_sync] +from google.cloud import retail_v2beta + + +def sample_import_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + input_config = retail_v2beta.UserEventInputConfig() + input_config.user_event_inline_source.user_events.event_type = "event_type_value" + input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" + + request = retail_v2beta.ImportUserEventsRequest( + parent="parent_value", + input_config=input_config, + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py new file mode 100644 index 00000000..6f97cab1 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_PurgeUserEvents_async] +from google.cloud import retail_v2beta + + +async def sample_purge_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py new file mode 100644 index 00000000..212d2693 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_PurgeUserEvents_sync] +from google.cloud import retail_v2beta + + +def sample_purge_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py new file mode 100644 index 00000000..8a95e668 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_RejoinUserEvents_async] +from google.cloud import retail_v2beta + + +async def sample_rejoin_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = retail_v2beta.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py new file mode 100644 index 00000000..ebd635b8 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejoinUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_RejoinUserEvents_sync] +from google.cloud import retail_v2beta + + +def sample_rejoin_user_events(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + request = retail_v2beta.RejoinUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.rejoin_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py new file mode 100644 index 00000000..71317cac --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_WriteUserEvent_async] +from google.cloud import retail_v2beta + + +async def sample_write_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 00000000..e93e4df4 --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-retail + + +# [START retail_v2beta_generated_UserEventService_WriteUserEvent_sync] +from google.cloud import retail_v2beta + + +def sample_write_user_event(): + # Create a client + client = retail_v2beta.UserEventServiceClient() + + # Initialize request argument(s) + user_event = retail_v2beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.visitor_id = "visitor_id_value" + + request = retail_v2beta.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END retail_v2beta_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json b/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json new file mode 100644 index 00000000..591f20ca --- /dev/null +++ b/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json @@ -0,0 +1,6913 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.retail.v2beta", + "version": "v2beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-retail" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.add_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "AddCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "add_catalog_attribute" + }, + "description": "Sample for AddCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_AddCatalogAttribute_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.add_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "AddCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "add_catalog_attribute" + }, + "description": "Sample for AddCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetAttributesConfigRequest" + }, + { + "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.retail_v2beta.types.AttributesConfig", + "shortName": "get_attributes_config" + }, + "description": "Sample for GetAttributesConfig", + "file": "retail_v2beta_generated_catalog_service_get_attributes_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetAttributesConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_attributes_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetAttributesConfigRequest" + }, + { + "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.retail_v2beta.types.AttributesConfig", + "shortName": "get_attributes_config" + }, + "description": "Sample for GetAttributesConfig", + "file": "retail_v2beta_generated_catalog_service_get_attributes_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetAttributesConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_attributes_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_completion_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetCompletionConfigRequest" + }, + { + "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.retail_v2beta.types.CompletionConfig", + "shortName": "get_completion_config" + }, + "description": "Sample for GetCompletionConfig", + "file": "retail_v2beta_generated_catalog_service_get_completion_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetCompletionConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_completion_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_completion_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetCompletionConfigRequest" + }, + { + "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.retail_v2beta.types.CompletionConfig", + "shortName": "get_completion_config" + }, + "description": "Sample for GetCompletionConfig", + "file": "retail_v2beta_generated_catalog_service_get_completion_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetCompletionConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_completion_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2beta_generated_catalog_service_get_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetDefaultBranch_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_default_branch", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.GetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.GetDefaultBranchResponse", + "shortName": "get_default_branch" + }, + "description": "Sample for GetDefaultBranch", + "file": "retail_v2beta_generated_catalog_service_get_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_GetDefaultBranch_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_get_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListCatalogsRequest" + }, + { + "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.retail_v2beta.services.catalog_service.pagers.ListCatalogsAsyncPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2beta_generated_catalog_service_list_catalogs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_ListCatalogs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_list_catalogs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.list_catalogs", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.ListCatalogs", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListCatalogsRequest" + }, + { + "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.retail_v2beta.services.catalog_service.pagers.ListCatalogsPager", + "shortName": "list_catalogs" + }, + "description": "Sample for ListCatalogs", + "file": "retail_v2beta_generated_catalog_service_list_catalogs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_ListCatalogs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_list_catalogs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.remove_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "RemoveCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "remove_catalog_attribute" + }, + "description": "Sample for RemoveCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.remove_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "RemoveCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "remove_catalog_attribute" + }, + "description": "Sample for RemoveCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.replace_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ReplaceCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "replace_catalog_attribute" + }, + "description": "Sample for ReplaceCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.replace_catalog_attribute", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ReplaceCatalogAttribute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", + "shortName": "replace_catalog_attribute" + }, + "description": "Sample for ReplaceCatalogAttribute", + "file": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2beta_generated_catalog_service_set_default_branch_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_SetDefaultBranch_async", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_set_default_branch_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.set_default_branch", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.SetDefaultBranch", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "SetDefaultBranch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SetDefaultBranchRequest" + }, + { + "name": "catalog", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "set_default_branch" + }, + "description": "Sample for SetDefaultBranch", + "file": "retail_v2beta_generated_catalog_service_set_default_branch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_SetDefaultBranch_sync", + "segments": [ + { + "end": 41, + "start": 27, + "type": "FULL" + }, + { + "end": 41, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_set_default_branch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest" + }, + { + "name": "attributes_config", + "type": "google.cloud.retail_v2beta.types.AttributesConfig" + }, + { + "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.retail_v2beta.types.AttributesConfig", + "shortName": "update_attributes_config" + }, + "description": "Sample for UpdateAttributesConfig", + "file": "retail_v2beta_generated_catalog_service_update_attributes_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_attributes_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_attributes_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateAttributesConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest" + }, + { + "name": "attributes_config", + "type": "google.cloud.retail_v2beta.types.AttributesConfig" + }, + { + "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.retail_v2beta.types.AttributesConfig", + "shortName": "update_attributes_config" + }, + "description": "Sample for UpdateAttributesConfig", + "file": "retail_v2beta_generated_catalog_service_update_attributes_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_attributes_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2beta.types.Catalog" + }, + { + "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.retail_v2beta.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2beta_generated_catalog_service_update_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateCatalog_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_catalog", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCatalog", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateCatalogRequest" + }, + { + "name": "catalog", + "type": "google.cloud.retail_v2beta.types.Catalog" + }, + { + "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.retail_v2beta.types.Catalog", + "shortName": "update_catalog" + }, + "description": "Sample for UpdateCatalog", + "file": "retail_v2beta_generated_catalog_service_update_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateCatalog_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_completion_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest" + }, + { + "name": "completion_config", + "type": "google.cloud.retail_v2beta.types.CompletionConfig" + }, + { + "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.retail_v2beta.types.CompletionConfig", + "shortName": "update_completion_config" + }, + "description": "Sample for UpdateCompletionConfig", + "file": "retail_v2beta_generated_catalog_service_update_completion_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_completion_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_completion_config", + "method": { + "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCompletionConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest" + }, + { + "name": "completion_config", + "type": "google.cloud.retail_v2beta.types.CompletionConfig" + }, + { + "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.retail_v2beta.types.CompletionConfig", + "shortName": "update_completion_config" + }, + "description": "Sample for UpdateCompletionConfig", + "file": "retail_v2beta_generated_catalog_service_update_completion_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_catalog_service_update_completion_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2beta.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2beta_generated_completion_service_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CompletionService_CompleteQuery_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_completion_service_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CompletionServiceClient.complete_query", + "method": { + "fullName": "google.cloud.retail.v2beta.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.retail.v2beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "retail_v2beta_generated_completion_service_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CompletionService_CompleteQuery_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_completion_service_complete_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2beta.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2beta_generated_completion_service_import_completion_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CompletionService_ImportCompletionData_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_completion_service_import_completion_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.CompletionServiceClient.import_completion_data", + "method": { + "fullName": "google.cloud.retail.v2beta.CompletionService.ImportCompletionData", + "service": { + "fullName": "google.cloud.retail.v2beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportCompletionDataRequest" + }, + { + "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_completion_data" + }, + "description": "Sample for ImportCompletionData", + "file": "retail_v2beta_generated_completion_service_import_completion_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_CompletionService_ImportCompletionData_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_completion_service_import_completion_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.create_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.CreateControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "CreateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateControlRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "control", + "type": "google.cloud.retail_v2beta.types.Control" + }, + { + "name": "control_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.retail_v2beta.types.Control", + "shortName": "create_control" + }, + "description": "Sample for CreateControl", + "file": "retail_v2beta_generated_control_service_create_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_CreateControl_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_create_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.create_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.CreateControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "CreateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateControlRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "control", + "type": "google.cloud.retail_v2beta.types.Control" + }, + { + "name": "control_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.retail_v2beta.types.Control", + "shortName": "create_control" + }, + "description": "Sample for CreateControl", + "file": "retail_v2beta_generated_control_service_create_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_CreateControl_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_create_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.delete_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.DeleteControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "DeleteControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteControlRequest" + }, + { + "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_control" + }, + "description": "Sample for DeleteControl", + "file": "retail_v2beta_generated_control_service_delete_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_DeleteControl_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_delete_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.delete_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.DeleteControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "DeleteControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteControlRequest" + }, + { + "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_control" + }, + "description": "Sample for DeleteControl", + "file": "retail_v2beta_generated_control_service_delete_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_DeleteControl_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_delete_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.get_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.GetControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "GetControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetControlRequest" + }, + { + "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.retail_v2beta.types.Control", + "shortName": "get_control" + }, + "description": "Sample for GetControl", + "file": "retail_v2beta_generated_control_service_get_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_GetControl_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_get_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.get_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.GetControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "GetControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetControlRequest" + }, + { + "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.retail_v2beta.types.Control", + "shortName": "get_control" + }, + "description": "Sample for GetControl", + "file": "retail_v2beta_generated_control_service_get_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_GetControl_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_get_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.list_controls", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.ListControls", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListControlsRequest" + }, + { + "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.retail_v2beta.services.control_service.pagers.ListControlsAsyncPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "retail_v2beta_generated_control_service_list_controls_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_ListControls_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_list_controls_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.list_controls", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.ListControls", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListControlsRequest" + }, + { + "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.retail_v2beta.services.control_service.pagers.ListControlsPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "retail_v2beta_generated_control_service_list_controls_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_ListControls_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_list_controls_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", + "shortName": "ControlServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.update_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.UpdateControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "UpdateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateControlRequest" + }, + { + "name": "control", + "type": "google.cloud.retail_v2beta.types.Control" + }, + { + "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.retail_v2beta.types.Control", + "shortName": "update_control" + }, + "description": "Sample for UpdateControl", + "file": "retail_v2beta_generated_control_service_update_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_UpdateControl_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_update_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ControlServiceClient", + "shortName": "ControlServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ControlServiceClient.update_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ControlService.UpdateControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ControlService", + "shortName": "ControlService" + }, + "shortName": "UpdateControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateControlRequest" + }, + { + "name": "control", + "type": "google.cloud.retail_v2beta.types.Control" + }, + { + "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.retail_v2beta.types.Control", + "shortName": "update_control" + }, + "description": "Sample for UpdateControl", + "file": "retail_v2beta_generated_control_service_update_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ControlService_UpdateControl_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_control_service_update_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.PredictionServiceAsyncClient", + "shortName": "PredictionServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.PredictionServiceAsyncClient.predict", + "method": { + "fullName": "google.cloud.retail.v2beta.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2beta.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2beta_generated_prediction_service_predict_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_PredictionService_Predict_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_prediction_service_predict_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.PredictionServiceClient", + "shortName": "PredictionServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.PredictionServiceClient.predict", + "method": { + "fullName": "google.cloud.retail.v2beta.PredictionService.Predict", + "service": { + "fullName": "google.cloud.retail.v2beta.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.PredictRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.PredictResponse", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "retail_v2beta_generated_prediction_service_predict_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_PredictionService_Predict_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_prediction_service_predict_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2beta_generated_product_service_add_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_add_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.add_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "add_fulfillment_places" + }, + "description": "Sample for AddFulfillmentPlaces", + "file": "retail_v2beta_generated_product_service_add_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_add_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2beta_generated_product_service_add_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_AddLocalInventories_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_add_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.add_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.AddLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "AddLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddLocalInventoriesRequest" + }, + { + "name": "product", + "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": "add_local_inventories" + }, + "description": "Sample for AddLocalInventories", + "file": "retail_v2beta_generated_product_service_add_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_AddLocalInventories_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_add_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "name": "product_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.retail_v2beta.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2beta_generated_product_service_create_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_CreateProduct_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_create_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.create_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.CreateProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "CreateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateProductRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "product", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "name": "product_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.retail_v2beta.types.Product", + "shortName": "create_product" + }, + "description": "Sample for CreateProduct", + "file": "retail_v2beta_generated_product_service_create_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_CreateProduct_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_create_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2beta_generated_product_service_delete_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_DeleteProduct_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_delete_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.delete_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.DeleteProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "DeleteProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteProductRequest" + }, + { + "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_product" + }, + "description": "Sample for DeleteProduct", + "file": "retail_v2beta_generated_product_service_delete_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_DeleteProduct_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_delete_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetProductRequest" + }, + { + "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.retail_v2beta.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2beta_generated_product_service_get_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_GetProduct_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_get_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.get_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.GetProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetProductRequest" + }, + { + "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.retail_v2beta.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "retail_v2beta_generated_product_service_get_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_GetProduct_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_get_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2beta_generated_product_service_import_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_ImportProducts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_import_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.import_products", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.ImportProducts", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "ImportProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportProductsRequest" + }, + { + "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_products" + }, + "description": "Sample for ImportProducts", + "file": "retail_v2beta_generated_product_service_import_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_ImportProducts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_import_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListProductsRequest" + }, + { + "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.retail_v2beta.services.product_service.pagers.ListProductsAsyncPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2beta_generated_product_service_list_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_ListProducts_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_list_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.list_products", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.ListProducts", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListProductsRequest" + }, + { + "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.retail_v2beta.services.product_service.pagers.ListProductsPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "retail_v2beta_generated_product_service_list_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_ListProducts_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_list_products_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2beta_generated_product_service_remove_fulfillment_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_remove_fulfillment_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.remove_fulfillment_places", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveFulfillmentPlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest" + }, + { + "name": "product", + "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": "remove_fulfillment_places" + }, + "description": "Sample for RemoveFulfillmentPlaces", + "file": "retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2beta_generated_product_service_remove_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_RemoveLocalInventories_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_remove_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.remove_local_inventories", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.RemoveLocalInventories", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "RemoveLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest" + }, + { + "name": "product", + "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": "remove_local_inventories" + }, + "description": "Sample for RemoveLocalInventories", + "file": "retail_v2beta_generated_product_service_remove_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_RemoveLocalInventories_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_remove_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2beta_generated_product_service_set_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_SetInventory_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_set_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.set_inventory", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.SetInventory", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "SetInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SetInventoryRequest" + }, + { + "name": "inventory", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "name": "set_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "set_inventory" + }, + "description": "Sample for SetInventory", + "file": "retail_v2beta_generated_product_service_set_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_SetInventory_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_set_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", + "shortName": "ProductServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "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.retail_v2beta.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2beta_generated_product_service_update_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_UpdateProduct_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_update_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ProductServiceClient", + "shortName": "ProductServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ProductServiceClient.update_product", + "method": { + "fullName": "google.cloud.retail.v2beta.ProductService.UpdateProduct", + "service": { + "fullName": "google.cloud.retail.v2beta.ProductService", + "shortName": "ProductService" + }, + "shortName": "UpdateProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateProductRequest" + }, + { + "name": "product", + "type": "google.cloud.retail_v2beta.types.Product" + }, + { + "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.retail_v2beta.types.Product", + "shortName": "update_product" + }, + "description": "Sample for UpdateProduct", + "file": "retail_v2beta_generated_product_service_update_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ProductService_UpdateProduct_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_product_service_update_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.SearchServiceAsyncClient.search", + "method": { + "fullName": "google.cloud.retail.v2beta.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2beta.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2beta_generated_search_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_SearchService_Search_async", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_search_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.SearchServiceClient", + "shortName": "SearchServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.SearchServiceClient.search", + "method": { + "fullName": "google.cloud.retail.v2beta.SearchService.Search", + "service": { + "fullName": "google.cloud.retail.v2beta.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.services.search_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "retail_v2beta_generated_search_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_SearchService_Search_sync", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_search_service_search_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.add_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.AddControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "AddControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "add_control" + }, + "description": "Sample for AddControl", + "file": "retail_v2beta_generated_serving_config_service_add_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_AddControl_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_add_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.add_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.AddControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "AddControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.AddControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "add_control" + }, + "description": "Sample for AddControl", + "file": "retail_v2beta_generated_serving_config_service_add_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_AddControl_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_add_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.create_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.CreateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "CreateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateServingConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2beta.types.ServingConfig" + }, + { + "name": "serving_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "create_serving_config" + }, + "description": "Sample for CreateServingConfig", + "file": "retail_v2beta_generated_serving_config_service_create_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_CreateServingConfig_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_create_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.create_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.CreateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "CreateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CreateServingConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2beta.types.ServingConfig" + }, + { + "name": "serving_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "create_serving_config" + }, + "description": "Sample for CreateServingConfig", + "file": "retail_v2beta_generated_serving_config_service_create_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_create_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.delete_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.DeleteServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "DeleteServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteServingConfigRequest" + }, + { + "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_serving_config" + }, + "description": "Sample for DeleteServingConfig", + "file": "retail_v2beta_generated_serving_config_service_delete_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_delete_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.delete_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.DeleteServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "DeleteServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.DeleteServingConfigRequest" + }, + { + "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_serving_config" + }, + "description": "Sample for DeleteServingConfig", + "file": "retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.get_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.GetServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "GetServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetServingConfigRequest" + }, + { + "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.retail_v2beta.types.ServingConfig", + "shortName": "get_serving_config" + }, + "description": "Sample for GetServingConfig", + "file": "retail_v2beta_generated_serving_config_service_get_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_GetServingConfig_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_get_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.get_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.GetServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "GetServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.GetServingConfigRequest" + }, + { + "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.retail_v2beta.types.ServingConfig", + "shortName": "get_serving_config" + }, + "description": "Sample for GetServingConfig", + "file": "retail_v2beta_generated_serving_config_service_get_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_GetServingConfig_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_get_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.list_serving_configs", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.ListServingConfigs", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "ListServingConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListServingConfigsRequest" + }, + { + "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.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager", + "shortName": "list_serving_configs" + }, + "description": "Sample for ListServingConfigs", + "file": "retail_v2beta_generated_serving_config_service_list_serving_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_ListServingConfigs_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_list_serving_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.list_serving_configs", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.ListServingConfigs", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "ListServingConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ListServingConfigsRequest" + }, + { + "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.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsPager", + "shortName": "list_serving_configs" + }, + "description": "Sample for ListServingConfigs", + "file": "retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.remove_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.RemoveControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "RemoveControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "remove_control" + }, + "description": "Sample for RemoveControl", + "file": "retail_v2beta_generated_serving_config_service_remove_control_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_RemoveControl_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_remove_control_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.remove_control", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.RemoveControl", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "RemoveControl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RemoveControlRequest" + }, + { + "name": "serving_config", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.ServingConfig", + "shortName": "remove_control" + }, + "description": "Sample for RemoveControl", + "file": "retail_v2beta_generated_serving_config_service_remove_control_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_RemoveControl_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_remove_control_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.update_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.UpdateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "UpdateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateServingConfigRequest" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2beta.types.ServingConfig" + }, + { + "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.retail_v2beta.types.ServingConfig", + "shortName": "update_serving_config" + }, + "description": "Sample for UpdateServingConfig", + "file": "retail_v2beta_generated_serving_config_service_update_serving_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_update_serving_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.update_serving_config", + "method": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService.UpdateServingConfig", + "service": { + "fullName": "google.cloud.retail.v2beta.ServingConfigService", + "shortName": "ServingConfigService" + }, + "shortName": "UpdateServingConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.UpdateServingConfigRequest" + }, + { + "name": "serving_config", + "type": "google.cloud.retail_v2beta.types.ServingConfig" + }, + { + "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.retail_v2beta.types.ServingConfig", + "shortName": "update_serving_config" + }, + "description": "Sample for UpdateServingConfig", + "file": "retail_v2beta_generated_serving_config_service_update_serving_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_serving_config_service_update_serving_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2beta_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_CollectUserEvent_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "retail_v2beta_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_CollectUserEvent_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2beta_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_ImportUserEvents_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "retail_v2beta_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_ImportUserEvents_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2beta_generated_user_event_service_purge_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_PurgeUserEvents_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_purge_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.purge_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "retail_v2beta_generated_user_event_service_purge_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_PurgeUserEvents_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_purge_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2beta_generated_user_event_service_rejoin_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_RejoinUserEvents_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_rejoin_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.rejoin_user_events", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.RejoinUserEvents", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "RejoinUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.RejoinUserEventsRequest" + }, + { + "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": "rejoin_user_events" + }, + "description": "Sample for RejoinUserEvents", + "file": "retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_RejoinUserEvents_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2beta_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_WriteUserEvent_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.retail.v2beta.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.retail.v2beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.retail_v2beta.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.retail_v2beta.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "retail_v2beta_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "retail_v2beta_generated_UserEventService_WriteUserEvent_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ], + "title": "retail_v2beta_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py b/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py new file mode 100644 index 00000000..dbd16de7 --- /dev/null +++ b/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py @@ -0,0 +1,218 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class retailCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_catalog_attribute': ('attributes_config', 'catalog_attribute', ), + 'add_control': ('serving_config', 'control_id', ), + 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), + 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), + 'create_control': ('parent', 'control', 'control_id', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'create_serving_config': ('parent', 'serving_config', 'serving_config_id', ), + 'delete_control': ('name', ), + 'delete_product': ('name', ), + 'delete_serving_config': ('name', ), + 'get_attributes_config': ('name', ), + 'get_completion_config': ('name', ), + 'get_control': ('name', ), + 'get_default_branch': ('catalog', ), + 'get_product': ('name', ), + 'get_serving_config': ('name', ), + 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), + 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), + 'import_user_events': ('parent', 'input_config', 'errors_config', ), + 'list_catalogs': ('parent', 'page_size', 'page_token', ), + 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', ), + 'list_serving_configs': ('parent', 'page_size', 'page_token', ), + 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), + 'purge_user_events': ('parent', 'filter', 'force', ), + 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), + 'remove_catalog_attribute': ('attributes_config', 'key', ), + 'remove_control': ('serving_config', 'control_id', ), + 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), + 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), + 'replace_catalog_attribute': ('attributes_config', 'catalog_attribute', 'update_mask', ), + 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), + 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), + 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), + 'update_attributes_config': ('attributes_config', 'update_mask', ), + 'update_catalog': ('catalog', 'update_mask', ), + 'update_completion_config': ('completion_config', 'update_mask', ), + 'update_control': ('control', 'update_mask', ), + 'update_product': ('product', 'update_mask', 'allow_missing', ), + 'update_serving_config': ('serving_config', 'update_mask', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=retailCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the retail client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2beta/setup.py b/owl-bot-staging/v2beta/setup.py new file mode 100644 index 00000000..1103510b --- /dev/null +++ b/owl-bot-staging/v2beta/setup.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-retail', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-retail", + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 2.8.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'googleapis-common-protos >= 1.55.0, <2.0.0dev', + 'proto-plus >= 1.19.7', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2beta/tests/__init__.py b/owl-bot-staging/v2beta/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/tests/unit/__init__.py b/owl-bot-staging/v2beta/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py b/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py new file mode 100644 index 00000000..f0c0245c --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py @@ -0,0 +1,3843 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.catalog_service import CatalogServiceAsyncClient +from google.cloud.retail_v2beta.services.catalog_service import CatalogServiceClient +from google.cloud.retail_v2beta.services.catalog_service import pagers +from google.cloud.retail_v2beta.services.catalog_service import transports +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CatalogServiceClient._get_default_mtls_endpoint(None) is None + assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CatalogServiceGrpcTransport, "grpc"), + (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_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", [ + (CatalogServiceClient, "grpc"), + (CatalogServiceAsyncClient, "grpc_asyncio"), +]) +def test_catalog_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_catalog_service_client_get_transport_class(): + transport = CatalogServiceClient.get_transport_class() + available_transports = [ + transports.CatalogServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CatalogServiceClient.get_transport_class("grpc") + assert transport == transports.CatalogServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CatalogServiceClient, CatalogServiceAsyncClient +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_catalog_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ListCatalogsRequest, + dict, +]) +def test_list_catalogs(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_catalogs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalogs), + '__call__') as call: + client.list_catalogs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + +@pytest.mark.asyncio +async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_catalogs_async_from_dict(): + await test_list_catalogs_async(request_type=dict) + + +def test_list_catalogs_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = catalog_service.ListCatalogsResponse() + client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + await client.list_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_catalogs_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_catalogs( + 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_catalogs_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_catalogs_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_catalogs( + 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_catalogs_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalogs( + catalog_service.ListCatalogsRequest(), + parent='parent_value', + ) + + +def test_list_catalogs_pager(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_catalogs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, catalog.Catalog) + for i in results) +def test_list_catalogs_pages(transport_name: str = "grpc"): + client = CatalogServiceClient( + 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_catalogs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = list(client.list_catalogs(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_catalogs_async_pager(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_catalogs(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, catalog.Catalog) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_catalogs_async_pages(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalogs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + catalog.Catalog(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogsResponse( + catalogs=[], + next_page_token='def', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogsResponse( + catalogs=[ + catalog.Catalog(), + catalog.Catalog(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCatalogRequest, + dict, +]) +def test_update_catalog(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + ) + response = client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_catalog_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_catalog), + '__call__') as call: + client.update_catalog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + +@pytest.mark.asyncio +async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_catalog_async_from_dict(): + await test_update_catalog_async(request_type=dict) + + +def test_update_catalog_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = gcr_catalog.Catalog() + client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_catalog_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogRequest() + + request.catalog.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + await client.update_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog.name=name_value', + ) in kw['metadata'] + + +def test_update_catalog_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_catalog_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_catalog.Catalog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_catalog( + catalog=gcr_catalog.Catalog(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].catalog + mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog( + catalog_service.UpdateCatalogRequest(), + catalog=gcr_catalog.Catalog(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.SetDefaultBranchRequest, + dict, +]) +def test_set_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_set_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + client.set_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.SetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_set_default_branch_async_from_dict(): + await test_set_default_branch_async(request_type=dict) + + +def test_set_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = None + client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.SetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_set_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_set_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), + '__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.set_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetDefaultBranchRequest, + dict, +]) +def test_get_default_branch(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + ) + response = client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +def test_get_default_branch_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_default_branch), + '__call__') as call: + client.get_default_branch() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + +@pytest.mark.asyncio +async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( + branch='branch_value', + note='note_value', + )) + response = await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetDefaultBranchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == 'branch_value' + assert response.note == 'note_value' + + +@pytest.mark.asyncio +async def test_get_default_branch_async_from_dict(): + await test_get_default_branch_async(request_type=dict) + + +def test_get_default_branch_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = catalog_service.GetDefaultBranchResponse() + client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_default_branch_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetDefaultBranchRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + await client.get_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +def test_get_default_branch_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + + +def test_get_default_branch_flattened_error(): + client = CatalogServiceClient( + credentials=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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.GetDefaultBranchResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_default_branch( + catalog='catalog_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].catalog + mock_val = 'catalog_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_default_branch_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_default_branch( + catalog_service.GetDefaultBranchRequest(), + catalog='catalog_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetCompletionConfigRequest, + dict, +]) +def test_get_completion_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + ) + response = client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +def test_get_completion_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_completion_config), + '__call__') as call: + client.get_completion_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + +@pytest.mark.asyncio +async def test_get_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCompletionConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + )) + response = await client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +@pytest.mark.asyncio +async def test_get_completion_config_async_from_dict(): + await test_get_completion_config_async(request_type=dict) + + +def test_get_completion_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCompletionConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + call.return_value = catalog.CompletionConfig() + client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_completion_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCompletionConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + await client.get_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_completion_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_completion_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_completion_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_completion_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_completion_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_completion_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCompletionConfigRequest, + dict, +]) +def test_update_completion_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + ) + response = client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +def test_update_completion_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_completion_config), + '__call__') as call: + client.update_completion_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + +@pytest.mark.asyncio +async def test_update_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCompletionConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( + name='name_value', + matching_order='matching_order_value', + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation='last_suggestions_import_operation_value', + last_denylist_import_operation='last_denylist_import_operation_value', + last_allowlist_import_operation='last_allowlist_import_operation_value', + )) + response = await client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCompletionConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == 'name_value' + assert response.matching_order == 'matching_order_value' + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' + assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' + assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' + + +@pytest.mark.asyncio +async def test_update_completion_config_async_from_dict(): + await test_update_completion_config_async(request_type=dict) + + +def test_update_completion_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCompletionConfigRequest() + + request.completion_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + call.return_value = catalog.CompletionConfig() + client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'completion_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_completion_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCompletionConfigRequest() + + request.completion_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + await client.update_completion_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'completion_config.name=name_value', + ) in kw['metadata'] + + +def test_update_completion_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_completion_config( + completion_config=catalog.CompletionConfig(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].completion_config + mock_val = catalog.CompletionConfig(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_completion_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_completion_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CompletionConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_completion_config( + completion_config=catalog.CompletionConfig(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].completion_config + mock_val = catalog.CompletionConfig(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_completion_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetAttributesConfigRequest, + dict, +]) +def test_get_attributes_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_get_attributes_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_attributes_config), + '__call__') as call: + client.get_attributes_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + +@pytest.mark.asyncio +async def test_get_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetAttributesConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_get_attributes_config_async_from_dict(): + await test_get_attributes_config_async(request_type=dict) + + +def test_get_attributes_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetAttributesConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_attributes_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetAttributesConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.get_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_attributes_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_attributes_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_attributes_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_attributes_config( + catalog_service.GetAttributesConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_attributes_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_attributes_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_attributes_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_attributes_config( + catalog_service.GetAttributesConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateAttributesConfigRequest, + dict, +]) +def test_update_attributes_config(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_update_attributes_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=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_attributes_config), + '__call__') as call: + client.update_attributes_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + +@pytest.mark.asyncio +async def test_update_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateAttributesConfigRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateAttributesConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_update_attributes_config_async_from_dict(): + await test_update_attributes_config_async(request_type=dict) + + +def test_update_attributes_config_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateAttributesConfigRequest() + + request.attributes_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_attributes_config_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateAttributesConfigRequest() + + request.attributes_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.update_attributes_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config.name=name_value', + ) in kw['metadata'] + + +def test_update_attributes_config_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_attributes_config( + attributes_config=catalog.AttributesConfig(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].attributes_config + mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error(): + client = CatalogServiceClient( + credentials=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_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_attributes_config_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_attributes_config( + attributes_config=catalog.AttributesConfig(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].attributes_config + mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.AddCatalogAttributeRequest, + dict, +]) +def test_add_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_add_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + client.add_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_add_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.AddCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.AddCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_add_catalog_attribute_async_from_dict(): + await test_add_catalog_attribute_async(request_type=dict) + + +def test_add_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.AddCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.AddCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.add_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + catalog_service.RemoveCatalogAttributeRequest, + dict, +]) +def test_remove_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_remove_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + client.remove_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.RemoveCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.RemoveCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_async_from_dict(): + await test_remove_catalog_attribute_async(request_type=dict) + + +def test_remove_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.RemoveCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.RemoveCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.remove_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ReplaceCatalogAttributeRequest, + dict, +]) +def test_replace_catalog_attribute(request_type, transport: str = 'grpc'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + response = client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +def test_replace_catalog_attribute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + client.replace_catalog_attribute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ReplaceCatalogAttributeRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( + name='name_value', + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + )) + response = await client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == 'name_value' + assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_async_from_dict(): + await test_replace_catalog_attribute_async(request_type=dict) + + +def test_replace_catalog_attribute_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ReplaceCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + call.return_value = catalog.AttributesConfig() + client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_replace_catalog_attribute_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ReplaceCatalogAttributeRequest() + + request.attributes_config = 'attributes_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) + await client.replace_catalog_attribute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attributes_config=attributes_config_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CatalogServiceClient.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 = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CatalogServiceGrpcTransport, + ) + +def test_catalog_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_catalog_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_catalogs', + 'update_catalog', + 'set_default_branch', + 'get_default_branch', + 'get_completion_config', + 'update_completion_config', + 'get_attributes_config', + 'update_attributes_config', + 'add_catalog_attribute', + 'remove_catalog_attribute', + 'replace_catalog_attribute', + ) + 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_catalog_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.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport( + 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_catalog_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.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport() + adc.assert_called_once() + + +def test_catalog_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) + CatalogServiceClient() + 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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +def test_catalog_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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +def test_catalog_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.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_catalog_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_no_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_catalog_service_host_with_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_catalog_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcTransport( + 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_catalog_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcAsyncIOTransport( + 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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_attributes_config_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.attributes_config_path(project, location, catalog) + assert expected == actual + + +def test_parse_attributes_config_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CatalogServiceClient.attributes_config_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_attributes_config_path(path) + assert expected == actual + +def test_branch_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = CatalogServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "branch": "clam", + } + path = CatalogServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_branch_path(path) + assert expected == actual + +def test_catalog_path(): + project = "whelk" + location = "octopus" + catalog = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + } + path = CatalogServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_completion_config_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.completion_config_path(project, location, catalog) + assert expected == actual + + +def test_parse_completion_config_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + } + path = CatalogServiceClient.completion_config_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_completion_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CatalogServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = CatalogServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = CatalogServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CatalogServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CatalogServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CatalogServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = CatalogServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CatalogServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CatalogServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CatalogServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = CatalogServiceClient( + 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", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py new file mode 100644 index 00000000..49aa7f73 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py @@ -0,0 +1,1501 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.completion_service import CompletionServiceAsyncClient +from google.cloud.retail_v2beta.services.completion_service import CompletionServiceClient +from google.cloud.retail_v2beta.services.completion_service import transports +from google.cloud.retail_v2beta.types import completion_service +from google.cloud.retail_v2beta.types import import_config +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CompletionServiceClient._get_default_mtls_endpoint(None) is None + assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CompletionServiceGrpcTransport, "grpc"), + (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), +]) +def test_completion_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_completion_service_client_get_transport_class(): + transport = CompletionServiceClient.get_transport_class() + available_transports = [ + transports.CompletionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CompletionServiceClient.get_transport_class("grpc") + assert transport == transports.CompletionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CompletionServiceClient, CompletionServiceAsyncClient +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_completion_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CompletionServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + ) + response = client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +def test_complete_query_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + client.complete_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + +@pytest.mark.asyncio +async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( + attribution_token='attribution_token_value', + )) + response = await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == 'attribution_token_value' + + +@pytest.mark.asyncio +async def test_complete_query_async_from_dict(): + await test_complete_query_async(request_type=dict) + + +def test_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.catalog = 'catalog_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) + await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'catalog=catalog_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportCompletionDataRequest, + dict, +]) +def test_import_completion_data(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_completion_data_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + client.import_completion_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + +@pytest.mark.asyncio +async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionDataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_completion_data_async_from_dict(): + await test_import_completion_data_async(request_type=dict) + + +def test_import_completion_data_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # 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_completion_data_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionDataRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_completion_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = CompletionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CompletionServiceGrpcTransport, + ) + +def test_completion_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_completion_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'complete_query', + 'import_completion_data', + ) + 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_completion_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_completion_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport() + adc.assert_called_once() + + +def test_completion_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CompletionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionServiceGrpcTransport, grpc_helpers), + (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_completion_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_no_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_completion_service_host_with_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_completion_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_completion_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_completion_service_grpc_lro_client(): + client = CompletionServiceClient( + 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_completion_service_grpc_lro_async_client(): + client = CompletionServiceAsyncClient( + 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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CompletionServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CompletionServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CompletionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CompletionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = CompletionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CompletionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CompletionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CompletionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = CompletionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CompletionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CompletionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CompletionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CompletionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py new file mode 100644 index 00000000..0c2700da --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py @@ -0,0 +1,2604 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.control_service import ControlServiceAsyncClient +from google.cloud.retail_v2beta.services.control_service import ControlServiceClient +from google.cloud.retail_v2beta.services.control_service import pagers +from google.cloud.retail_v2beta.services.control_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service +from google.cloud.retail_v2beta.types import search_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ControlServiceClient._get_default_mtls_endpoint(None) is None + assert ControlServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ControlServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ControlServiceClient, "grpc"), + (ControlServiceAsyncClient, "grpc_asyncio"), +]) +def test_control_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ControlServiceGrpcTransport, "grpc"), + (transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_control_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", [ + (ControlServiceClient, "grpc"), + (ControlServiceAsyncClient, "grpc_asyncio"), +]) +def test_control_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_control_service_client_get_transport_class(): + transport = ControlServiceClient.get_transport_class() + available_transports = [ + transports.ControlServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ControlServiceClient.get_transport_class("grpc") + assert transport == transports.ControlServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +def test_control_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(ControlServiceClient, '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(ControlServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "true"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "false"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_control_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ControlServiceClient, ControlServiceAsyncClient +]) +@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) +@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) +def test_control_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_control_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_control_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_control_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.control_service.transports.ControlServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ControlServiceClient( + 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", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_control_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.CreateControlRequest, + dict, +]) +def test_create_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_create_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.create_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + +@pytest.mark.asyncio +async def test_create_control_async(transport: str = 'grpc_asyncio', request_type=control_service.CreateControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.CreateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_create_control_async_from_dict(): + await test_create_control_async(request_type=dict) + + +def test_create_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.CreateControlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + call.return_value = gcr_control.Control() + client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.CreateControlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + await client.create_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_control( + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) + assert arg == mock_val + arg = args[0].control_id + mock_val = 'control_id_value' + assert arg == mock_val + + +def test_create_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.CreateControlRequest(), + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_id_value', + ) + +@pytest.mark.asyncio +async def test_create_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_control( + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) + assert arg == mock_val + arg = args[0].control_id + mock_val = 'control_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.CreateControlRequest(), + parent='parent_value', + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + control_id='control_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.DeleteControlRequest, + dict, +]) +def test_delete_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.delete_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + +@pytest.mark.asyncio +async def test_delete_control_async(transport: str = 'grpc_asyncio', request_type=control_service.DeleteControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.DeleteControlRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_control_async_from_dict(): + await test_delete_control_async(request_type=dict) + + +def test_delete_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.DeleteControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__call__') as call: + call.return_value = None + client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.DeleteControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__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_control( + 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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.DeleteControlRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_control), + '__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_control( + 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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.DeleteControlRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.UpdateControlRequest, + dict, +]) +def test_update_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_update_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.update_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + +@pytest.mark.asyncio +async def test_update_control_async(transport: str = 'grpc_asyncio', request_type=control_service.UpdateControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.UpdateControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_update_control_async_from_dict(): + await test_update_control_async(request_type=dict) + + +def test_update_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.UpdateControlRequest() + + request.control.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + call.return_value = gcr_control.Control() + client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'control.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.UpdateControlRequest() + + request.control.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + await client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'control.name=name_value', + ) in kw['metadata'] + + +def test_update_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_control( + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_control( + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control + mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.GetControlRequest, + dict, +]) +def test_get_control(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), + ) + response = client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_get_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_control), + '__call__') as call: + client.get_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + +@pytest.mark.asyncio +async def test_get_control_async(transport: str = 'grpc_asyncio', request_type=control_service.GetControlRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control.Control( + name='name_value', + display_name='display_name_value', + associated_serving_config_ids=['associated_serving_config_ids_value'], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.GetControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_get_control_async_from_dict(): + await test_get_control_async(request_type=dict) + + +def test_get_control_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.GetControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + call.return_value = control.Control() + client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_control_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.GetControlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) + await client.get_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_control_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_control( + 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_control_flattened_error(): + client = ControlServiceClient( + credentials=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_control( + control_service.GetControlRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_control_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control.Control() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_control( + 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_control_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_control( + control_service.GetControlRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + control_service.ListControlsRequest, + dict, +]) +def test_list_controls(request_type, transport: str = 'grpc'): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_controls_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ControlServiceClient( + credentials=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_controls), + '__call__') as call: + client.list_controls() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + +@pytest.mark.asyncio +async def test_list_controls_async(transport: str = 'grpc_asyncio', request_type=control_service.ListControlsRequest): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == control_service.ListControlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_controls_async_from_dict(): + await test_list_controls_async(request_type=dict) + + +def test_list_controls_field_headers(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.ListControlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + call.return_value = control_service.ListControlsResponse() + client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_controls_field_headers_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = control_service.ListControlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) + await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_controls_flattened(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_controls( + 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_controls_flattened_error(): + client = ControlServiceClient( + credentials=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_controls( + control_service.ListControlsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_controls_flattened_async(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = control_service.ListControlsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_controls( + 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_controls_flattened_error_async(): + client = ControlServiceAsyncClient( + credentials=ga_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_controls( + control_service.ListControlsRequest(), + parent='parent_value', + ) + + +def test_list_controls_pager(transport_name: str = "grpc"): + client = ControlServiceClient( + 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_controls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_controls(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, control.Control) + for i in results) +def test_list_controls_pages(transport_name: str = "grpc"): + client = ControlServiceClient( + 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_controls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + pages = list(client.list_controls(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_controls_async_pager(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_controls(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, control.Control) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_controls_async_pages(): + client = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token='abc', + ), + control_service.ListControlsResponse( + controls=[], + next_page_token='def', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token='ghi', + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_controls(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ControlServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ControlServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ControlServiceClient.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 = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ControlServiceGrpcTransport, + ) + +def test_control_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ControlServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_control_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.control_service.transports.ControlServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ControlServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_control', + 'delete_control', + 'update_control', + 'get_control', + 'list_controls', + ) + 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_control_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.retail_v2beta.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ControlServiceTransport( + 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_control_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.retail_v2beta.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ControlServiceTransport() + adc.assert_called_once() + + +def test_control_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) + ControlServiceClient() + 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.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + ], +) +def test_control_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.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + ], +) +def test_control_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.ControlServiceGrpcTransport, grpc_helpers), + (transports.ControlServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_control_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_control_service_host_no_port(transport_name): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_control_service_host_with_port(transport_name): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_control_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ControlServiceGrpcTransport( + 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_control_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ControlServiceGrpcAsyncIOTransport( + 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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) +def test_control_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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = ControlServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = ControlServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_control_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + control = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) + actual = ControlServiceClient.control_path(project, location, catalog, control) + assert expected == actual + + +def test_parse_control_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "control": "clam", + } + path = ControlServiceClient.control_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_control_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ControlServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ControlServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ControlServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ControlServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ControlServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ControlServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ControlServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ControlServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.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 = ControlServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ControlServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ControlServiceClient.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.ControlServiceTransport, '_prep_wrapped_messages') as prep: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ControlServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ControlServiceClient.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 = ControlServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ControlServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ControlServiceClient( + 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", [ + (ControlServiceClient, transports.ControlServiceGrpcTransport), + (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py new file mode 100644 index 00000000..8e7a1380 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py @@ -0,0 +1,1329 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.prediction_service import PredictionServiceAsyncClient +from google.cloud.retail_v2beta.services.prediction_service import PredictionServiceClient +from google.cloud.retail_v2beta.services.prediction_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import prediction_service +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import promotion +from google.cloud.retail_v2beta.types import user_event +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PredictionServiceClient._get_default_mtls_endpoint(None) is None + assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionServiceGrpcTransport, "grpc"), + (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_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", [ + (PredictionServiceClient, "grpc"), + (PredictionServiceAsyncClient, "grpc_asyncio"), +]) +def test_prediction_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_prediction_service_client_get_transport_class(): + transport = PredictionServiceClient.get_transport_class() + available_transports = [ + transports.PredictionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = PredictionServiceClient.get_transport_class("grpc") + assert transport == transports.PredictionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + PredictionServiceClient, PredictionServiceAsyncClient +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_prediction_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_service.PredictRequest, + dict, +]) +def test_predict(request_type, transport: str = 'grpc'): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + response = client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_predict_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + client.predict() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + +@pytest.mark.asyncio +async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + )) + response = await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +@pytest.mark.asyncio +async def test_predict_async_from_dict(): + await test_predict_async(request_type=dict) + + +def test_predict_field_headers(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_predict_field_headers_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) + await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = PredictionServiceClient.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 = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'predict', + ) + 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport( + 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport() + adc.assert_called_once() + + +def test_prediction_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) + PredictionServiceClient() + 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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +def test_prediction_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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +def test_prediction_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.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_prediction_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_no_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_prediction_service_host_with_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_prediction_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcTransport( + 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_prediction_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcAsyncIOTransport( + 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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_product_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + product = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + "branch": "winkle", + "product": "nautilus", + } + path = PredictionServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PredictionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = PredictionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = PredictionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = PredictionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PredictionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = PredictionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = PredictionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = PredictionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = PredictionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PredictionServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = PredictionServiceClient( + 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", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py new file mode 100644 index 00000000..59b69742 --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py @@ -0,0 +1,4135 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.product_service import ProductServiceAsyncClient +from google.cloud.retail_v2beta.services.product_service import ProductServiceClient +from google.cloud.retail_v2beta.services.product_service import pagers +from google.cloud.retail_v2beta.services.product_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service +from google.cloud.retail_v2beta.types import promotion +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProductServiceClient._get_default_mtls_endpoint(None) is None + assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProductServiceGrpcTransport, "grpc"), + (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_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", [ + (ProductServiceClient, "grpc"), + (ProductServiceAsyncClient, "grpc_asyncio"), +]) +def test_product_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_product_service_client_get_transport_class(): + transport = ProductServiceClient.get_transport_class() + available_transports = [ + transports.ProductServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ProductServiceClient.get_transport_class("grpc") + assert transport == transports.ProductServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_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(ProductServiceClient, '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(ProductServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ProductServiceClient, ProductServiceAsyncClient +]) +@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) +@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) +def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_product_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.CreateProductRequest, + dict, +]) +def test_create_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_create_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.create_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + +@pytest.mark.asyncio +async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_create_product_async_from_dict(): + await test_create_product_async(request_type=dict) + + +def test_create_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.CreateProductRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + + +def test_create_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + +@pytest.mark.asyncio +async def test_create_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product( + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].product_id + mock_val = 'product_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.CreateProductRequest(), + parent='parent_value', + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + product_id='product_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_get_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.get_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + +@pytest.mark.asyncio +async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( + name='name_value', + id='id_value', + type_=product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_get_product_async_from_dict(): + await test_get_product_async(request_type=dict) + + +def test_get_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = product.Product() + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.GetProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.GetProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.list_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + +@pytest.mark.asyncio +async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_products_async_from_dict(): + await test_list_products_async(request_type=dict) + + +def test_list_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = product_service.ListProductsResponse() + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products( + 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_products_flattened_error(): + client = ProductServiceClient( + credentials=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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = product_service.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products( + 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_products_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_products( + product_service.ListProductsRequest(), + parent='parent_value', + ) + + +def test_list_products_pager(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_products(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, product.Product) + for i in results) +def test_list_products_pages(transport_name: str = "grpc"): + client = ProductServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(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_products_async_pager(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(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, product.Product) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token='abc', + ), + product_service.ListProductsResponse( + products=[], + next_page_token='def', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token='ghi', + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_products(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + product_service.UpdateProductRequest, + dict, +]) +def test_update_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + expire_time=timestamp_pb2.Timestamp(seconds=751), + ) + response = client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +def test_update_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.update_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + +@pytest.mark.asyncio +async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( + name='name_value', + id='id_value', + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id='primary_product_id_value', + collection_member_ids=['collection_member_ids_value'], + gtin='gtin_value', + categories=['categories_value'], + title='title_value', + brands=['brands_value'], + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + availability=gcr_product.Product.Availability.IN_STOCK, + uri='uri_value', + sizes=['sizes_value'], + materials=['materials_value'], + patterns=['patterns_value'], + conditions=['conditions_value'], + )) + response = await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == 'primary_product_id_value' + assert response.collection_member_ids == ['collection_member_ids_value'] + assert response.gtin == 'gtin_value' + assert response.categories == ['categories_value'] + assert response.title == 'title_value' + assert response.brands == ['brands_value'] + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == 'uri_value' + assert response.sizes == ['sizes_value'] + assert response.materials == ['materials_value'] + assert response.patterns == ['patterns_value'] + assert response.conditions == ['conditions_value'] + + +@pytest.mark.asyncio +async def test_update_product_async_from_dict(): + await test_update_product_async(request_type=dict) + + +def test_update_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = gcr_product.Product() + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.UpdateProductRequest() + + request.product.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] + + +def test_update_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_product.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product( + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + 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].product + mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.DeleteProductRequest, + dict, +]) +def test_delete_product(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_product), + '__call__') as call: + client.delete_product() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + +@pytest.mark.asyncio +async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_product_async_from_dict(): + await test_delete_product_async(request_type=dict) + + +def test_delete_product_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = None + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_product_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.DeleteProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_product_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error(): + client = ProductServiceClient( + credentials=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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_product_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product), + '__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_product( + 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_product_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_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_product( + product_service.DeleteProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportProductsRequest, + dict, +]) +def test_import_products(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_products_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=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_products), + '__call__') as call: + client.import_products() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + +@pytest.mark.asyncio +async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__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_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_products_async_from_dict(): + await test_import_products_async(request_type=dict) + + +def test_import_products_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + product_service.SetInventoryRequest, + dict, +]) +def test_set_inventory(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_inventory_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + client.set_inventory() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + +@pytest.mark.asyncio +async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.SetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_set_inventory_async_from_dict(): + await test_set_inventory_async(request_type=dict) + + +def test_set_inventory_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_inventory_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.SetInventoryRequest() + + request.inventory.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.set_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'inventory.name=name_value', + ) in kw['metadata'] + + +def test_set_inventory_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_set_inventory_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_set_inventory_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_inventory( + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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].inventory + mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) + assert arg == mock_val + arg = args[0].set_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_inventory_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddFulfillmentPlacesRequest, + dict, +]) +def test_add_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + client.add_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_async_from_dict(): + await test_add_fulfillment_places_async(request_type=dict) + + +def test_add_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), + '__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.add_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveFulfillmentPlacesRequest, + dict, +]) +def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_fulfillment_places_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + client.remove_fulfillment_places() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveFulfillmentPlacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_async_from_dict(): + await test_remove_fulfillment_places_async(request_type=dict) + + +def test_remove_fulfillment_places_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveFulfillmentPlacesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_fulfillment_places_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_fulfillment_places_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), + '__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.remove_fulfillment_places( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_fulfillment_places_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.AddLocalInventoriesRequest, + dict, +]) +def test_add_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + client.add_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.AddLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_local_inventories_async_from_dict(): + await test_add_local_inventories_async(request_type=dict) + + +def test_add_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.AddLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_add_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_add_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), + '__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.add_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product='product_value', + ) + + +@pytest.mark.parametrize("request_type", [ + product_service.RemoveLocalInventoriesRequest, + dict, +]) +def test_remove_local_inventories(request_type, transport: str = 'grpc'): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_local_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + client.remove_local_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + +@pytest.mark.asyncio +async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == product_service.RemoveLocalInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_local_inventories_async_from_dict(): + await test_remove_local_inventories_async(request_type=dict) + + +def test_remove_local_inventories_field_headers(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_local_inventories_field_headers_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_service.RemoveLocalInventoriesRequest() + + request.product = 'product_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'product=product_value', + ) in kw['metadata'] + + +def test_remove_local_inventories_flattened(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + + +def test_remove_local_inventories_flattened_error(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), + '__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.remove_local_inventories( + product='product_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].product + mock_val = 'product_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_local_inventories_flattened_error_async(): + client = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product='product_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ProductServiceClient.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 = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProductServiceGrpcTransport, + ) + +def test_product_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_product_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.product_service.transports.ProductServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProductServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_product', + 'get_product', + 'list_products', + 'update_product', + 'delete_product', + 'import_products', + 'set_inventory', + 'add_fulfillment_places', + 'remove_fulfillment_places', + 'add_local_inventories', + 'remove_local_inventories', + ) + 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_product_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.retail_v2beta.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport( + 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_product_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.retail_v2beta.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductServiceTransport() + adc.assert_called_once() + + +def test_product_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) + ProductServiceClient() + 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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + ], +) +def test_product_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.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + ], +) +def test_product_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.ProductServiceGrpcTransport, grpc_helpers), + (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_product_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_no_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_product_service_host_with_port(transport_name): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_product_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcTransport( + 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_product_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductServiceGrpcAsyncIOTransport( + 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) +def test_product_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_product_service_grpc_lro_client(): + client = ProductServiceClient( + 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_product_service_grpc_lro_async_client(): + client = ProductServiceAsyncClient( + 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" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = ProductServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = ProductServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = ProductServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = ProductServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProductServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ProductServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProductServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ProductServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProductServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ProductServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ProductServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ProductServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ProductServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ProductServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ProductServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ProductServiceClient( + 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", [ + (ProductServiceClient, transports.ProductServiceGrpcTransport), + (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py new file mode 100644 index 00000000..3ba459cc --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py @@ -0,0 +1,1546 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.search_service import SearchServiceAsyncClient +from google.cloud.retail_v2beta.services.search_service import SearchServiceClient +from google.cloud.retail_v2beta.services.search_service import pagers +from google.cloud.retail_v2beta.services.search_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SearchServiceClient._get_default_mtls_endpoint(None) is None + assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SearchServiceGrpcTransport, "grpc"), + (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), +]) +def test_search_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_search_service_client_get_transport_class(): + transport = SearchServiceClient.get_transport_class() + available_transports = [ + transports.SearchServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SearchServiceClient.get_transport_class("grpc") + assert transport == transports.SearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SearchServiceClient, SearchServiceAsyncClient +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SearchServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + search_service.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( + total_size=1086, + corrected_query='corrected_query_value', + attribution_token='attribution_token_value', + next_page_token='next_page_token_value', + redirect_uri='redirect_uri_value', + applied_controls=['applied_controls_value'], + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.total_size == 1086 + assert response.corrected_query == 'corrected_query_value' + assert response.attribution_token == 'attribution_token_value' + assert response.next_page_token == 'next_page_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.applied_controls == ['applied_controls_value'] + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + + +def test_search_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = search_service.SearchResponse() + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.placement = 'placement_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'placement=placement_value', + ) in kw['metadata'] + + +def test_search_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('placement', ''), + )), + ) + pager = client.search(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_async_pager(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = SearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_search_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_search_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport() + adc.assert_called_once() + + +def test_search_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SearchServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SearchServiceGrpcTransport, grpc_helpers), + (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_search_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_no_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_search_service_host_with_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_branch_path(): + project = "squid" + location = "clam" + catalog = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) + actual = SearchServiceClient.branch_path(project, location, catalog, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "branch": "mussel", + } + path = SearchServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_branch_path(path) + assert expected == actual + +def test_product_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + branch = "abalone" + product = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = SearchServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "branch": "oyster", + "product": "nudibranch", + } + path = SearchServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py new file mode 100644 index 00000000..6471cb0b --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py @@ -0,0 +1,3329 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.serving_config_service import ServingConfigServiceAsyncClient +from google.cloud.retail_v2beta.services.serving_config_service import ServingConfigServiceClient +from google.cloud.retail_v2beta.services.serving_config_service import pagers +from google.cloud.retail_v2beta.services.serving_config_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import search_service +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ServingConfigServiceClient._get_default_mtls_endpoint(None) is None + assert ServingConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ServingConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ServingConfigServiceClient, "grpc"), + (ServingConfigServiceAsyncClient, "grpc_asyncio"), +]) +def test_serving_config_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 == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ServingConfigServiceGrpcTransport, "grpc"), + (transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_serving_config_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", [ + (ServingConfigServiceClient, "grpc"), + (ServingConfigServiceAsyncClient, "grpc_asyncio"), +]) +def test_serving_config_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 == ( + 'retail.googleapis.com:443' + ) + + +def test_serving_config_service_client_get_transport_class(): + transport = ServingConfigServiceClient.get_transport_class() + available_transports = [ + transports.ServingConfigServiceGrpcTransport, + ] + assert transport in available_transports + + transport = ServingConfigServiceClient.get_transport_class("grpc") + assert transport == transports.ServingConfigServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +def test_serving_config_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(ServingConfigServiceClient, '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(ServingConfigServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "true"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "false"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_serving_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ServingConfigServiceClient, ServingConfigServiceAsyncClient +]) +@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) +@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) +def test_serving_config_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_serving_config_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_serving_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_serving_config_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ServingConfigServiceClient( + 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", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_serving_config_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.CreateServingConfigRequest, + dict, +]) +def test_create_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_create_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.create_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + +@pytest.mark.asyncio +async def test_create_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.CreateServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.CreateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_create_serving_config_async_from_dict(): + await test_create_serving_config_async(request_type=dict) + + +def test_create_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.CreateServingConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.CreateServingConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.create_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_serving_config( + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].serving_config + mock_val = gcr_serving_config.ServingConfig(name='name_value') + assert arg == mock_val + arg = args[0].serving_config_id + mock_val = 'serving_config_id_value' + assert arg == mock_val + + +def test_create_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.CreateServingConfigRequest(), + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_serving_config( + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].serving_config + mock_val = gcr_serving_config.ServingConfig(name='name_value') + assert arg == mock_val + arg = args[0].serving_config_id + mock_val = 'serving_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.CreateServingConfigRequest(), + parent='parent_value', + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + serving_config_id='serving_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.DeleteServingConfigRequest, + dict, +]) +def test_delete_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.delete_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + +@pytest.mark.asyncio +async def test_delete_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.DeleteServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.DeleteServingConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_serving_config_async_from_dict(): + await test_delete_serving_config_async(request_type=dict) + + +def test_delete_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.DeleteServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__call__') as call: + call.return_value = None + client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.DeleteServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__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_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.DeleteServingConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), + '__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_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.DeleteServingConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.UpdateServingConfigRequest, + dict, +]) +def test_update_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_update_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.update_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + +@pytest.mark.asyncio +async def test_update_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.UpdateServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.UpdateServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_update_serving_config_async_from_dict(): + await test_update_serving_config_async(request_type=dict) + + +def test_update_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.UpdateServingConfigRequest() + + request.serving_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.UpdateServingConfigRequest() + + request.serving_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config.name=name_value', + ) in kw['metadata'] + + +def test_update_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_serving_config( + serving_config=gcr_serving_config.ServingConfig(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].serving_config + mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_serving_config( + serving_config=gcr_serving_config.ServingConfig(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].serving_config + mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.GetServingConfigRequest, + dict, +]) +def test_get_serving_config(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_get_serving_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_config), + '__call__') as call: + client.get_serving_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + +@pytest.mark.asyncio +async def test_get_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.GetServingConfigRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.GetServingConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_get_serving_config_async_from_dict(): + await test_get_serving_config_async(request_type=dict) + + +def test_get_serving_config_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.GetServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + call.return_value = serving_config.ServingConfig() + client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_serving_config_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.GetServingConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) + await client.get_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_serving_config_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_serving_config_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_config( + serving_config_service.GetServingConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_serving_config_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_serving_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_serving_config_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_config( + serving_config_service.GetServingConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.ListServingConfigsRequest, + dict, +]) +def test_list_serving_configs(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_serving_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=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_serving_configs), + '__call__') as call: + client.list_serving_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + +@pytest.mark.asyncio +async def test_list_serving_configs_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.ListServingConfigsRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.ListServingConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_serving_configs_async_from_dict(): + await test_list_serving_configs_async(request_type=dict) + + +def test_list_serving_configs_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.ListServingConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + call.return_value = serving_config_service.ListServingConfigsResponse() + client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_serving_configs_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.ListServingConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) + await client.list_serving_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_serving_configs_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_serving_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_serving_configs_flattened_error(): + client = ServingConfigServiceClient( + credentials=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_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_serving_configs_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = serving_config_service.ListServingConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_serving_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_serving_configs_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_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_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent='parent_value', + ) + + +def test_list_serving_configs_pager(transport_name: str = "grpc"): + client = ServingConfigServiceClient( + 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_serving_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_serving_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, serving_config.ServingConfig) + for i in results) +def test_list_serving_configs_pages(transport_name: str = "grpc"): + client = ServingConfigServiceClient( + 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_serving_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_serving_configs(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_serving_configs_async_pager(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_serving_configs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, serving_config.ServingConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_serving_configs_async_pages(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token='abc', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token='def', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token='ghi', + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_serving_configs(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + serving_config_service.AddControlRequest, + dict, +]) +def test_add_control(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_add_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + client.add_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + +@pytest.mark.asyncio +async def test_add_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.AddControlRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.AddControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_add_control_async_from_dict(): + await test_add_control_async(request_type=dict) + + +def test_add_control_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.AddControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_control_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.AddControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.add_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_add_control_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + + +def test_add_control_flattened_error(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_control( + serving_config_service.AddControlRequest(), + serving_config='serving_config_value', + ) + +@pytest.mark.asyncio +async def test_add_control_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_control_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_control( + serving_config_service.AddControlRequest(), + serving_config='serving_config_value', + ) + + +@pytest.mark.parametrize("request_type", [ + serving_config_service.RemoveControlRequest, + dict, +]) +def test_remove_control(request_type, transport: str = 'grpc'): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + response = client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +def test_remove_control_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + client.remove_control() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + +@pytest.mark.asyncio +async def test_remove_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.RemoveControlRequest): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( + name='name_value', + display_name='display_name_value', + model_id='model_id_value', + price_reranking_level='price_reranking_level_value', + facet_control_ids=['facet_control_ids_value'], + boost_control_ids=['boost_control_ids_value'], + filter_control_ids=['filter_control_ids_value'], + redirect_control_ids=['redirect_control_ids_value'], + twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], + oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], + do_not_associate_control_ids=['do_not_associate_control_ids_value'], + replacement_control_ids=['replacement_control_ids_value'], + ignore_control_ids=['ignore_control_ids_value'], + diversity_level='diversity_level_value', + enable_category_filter_level='enable_category_filter_level_value', + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + )) + response = await client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == serving_config_service.RemoveControlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.model_id == 'model_id_value' + assert response.price_reranking_level == 'price_reranking_level_value' + assert response.facet_control_ids == ['facet_control_ids_value'] + assert response.boost_control_ids == ['boost_control_ids_value'] + assert response.filter_control_ids == ['filter_control_ids_value'] + assert response.redirect_control_ids == ['redirect_control_ids_value'] + assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] + assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] + assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] + assert response.replacement_control_ids == ['replacement_control_ids_value'] + assert response.ignore_control_ids == ['ignore_control_ids_value'] + assert response.diversity_level == 'diversity_level_value' + assert response.enable_category_filter_level == 'enable_category_filter_level_value' + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.asyncio +async def test_remove_control_async_from_dict(): + await test_remove_control_async(request_type=dict) + + +def test_remove_control_field_headers(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.RemoveControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + call.return_value = gcr_serving_config.ServingConfig() + client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_control_field_headers_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = serving_config_service.RemoveControlRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + await client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_remove_control_flattened(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + + +def test_remove_control_flattened_error(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config='serving_config_value', + ) + +@pytest.mark.asyncio +async def test_remove_control_flattened_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_control), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_serving_config.ServingConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_control( + serving_config='serving_config_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].serving_config + mock_val = 'serving_config_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_control_flattened_error_async(): + client = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config='serving_config_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServingConfigServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = ServingConfigServiceClient.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 = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ServingConfigServiceGrpcTransport, + ) + +def test_serving_config_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ServingConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_serving_config_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ServingConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_serving_config', + 'delete_serving_config', + 'update_serving_config', + 'get_serving_config', + 'list_serving_configs', + 'add_control', + 'remove_control', + ) + 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_serving_config_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.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServingConfigServiceTransport( + 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_serving_config_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.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServingConfigServiceTransport() + adc.assert_called_once() + + +def test_serving_config_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) + ServingConfigServiceClient() + 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.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + ], +) +def test_serving_config_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.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + ], +) +def test_serving_config_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.ServingConfigServiceGrpcTransport, grpc_helpers), + (transports.ServingConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_serving_config_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( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_serving_config_service_host_no_port(transport_name): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_serving_config_service_host_with_port(transport_name): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_serving_config_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServingConfigServiceGrpcTransport( + 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_serving_config_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + 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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) +def test_serving_config_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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = ServingConfigServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = ServingConfigServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + serving_config = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, serving_config=serving_config, ) + actual = ServingConfigServiceClient.serving_config_path(project, location, catalog, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "serving_config": "clam", + } + path = ServingConfigServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ServingConfigServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ServingConfigServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ServingConfigServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ServingConfigServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ServingConfigServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ServingConfigServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ServingConfigServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ServingConfigServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.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 = ServingConfigServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ServingConfigServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ServingConfigServiceClient.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.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ServingConfigServiceClient.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 = ServingConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ServingConfigServiceClient( + 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 = [ + 'grpc', + ] + for transport in transports: + client = ServingConfigServiceClient( + 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", [ + (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport), + (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py new file mode 100644 index 00000000..cf30324f --- /dev/null +++ b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py @@ -0,0 +1,2038 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.retail_v2beta.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.retail_v2beta.services.user_event_service import UserEventServiceClient +from google.cloud.retail_v2beta.services.user_event_service import transports +from google.cloud.retail_v2beta.types import common +from google.cloud.retail_v2beta.types import import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import promotion +from google.cloud.retail_v2beta.types import purge_config +from google.cloud.retail_v2beta.types import user_event +from google.cloud.retail_v2beta.types import user_event_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), +]) +def test_user_event_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + ) + response = client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +def test_write_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( + event_type='event_type_value', + visitor_id='visitor_id_value', + session_id='session_id_value', + experiment_ids=['experiment_ids_value'], + attribution_token='attribution_token_value', + cart_id='cart_id_value', + search_query='search_query_value', + filter='filter_value', + order_by='order_by_value', + offset=647, + page_categories=['page_categories_value'], + uri='uri_value', + referrer_uri='referrer_uri_value', + page_view_id='page_view_id_value', + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.visitor_id == 'visitor_id_value' + assert response.session_id == 'session_id_value' + assert response.experiment_ids == ['experiment_ids_value'] + assert response.attribution_token == 'attribution_token_value' + assert response.cart_id == 'cart_id_value' + assert response.search_query == 'search_query_value' + assert response.filter == 'filter_value' + assert response.order_by == 'order_by_value' + assert response.offset == 647 + assert response.page_categories == ['page_categories_value'] + assert response.uri == 'uri_value' + assert response.referrer_uri == 'referrer_uri_value' + assert response.page_view_id == 'page_view_id_value' + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) + await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeUserEventsRequest, + dict, +]) +def test_purge_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + client.purge_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + +@pytest.mark.asyncio +async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_user_events_async_from_dict(): + await test_purge_user_events_async(request_type=dict) + + +def test_purge_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_purge_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.RejoinUserEventsRequest, + dict, +]) +def test_rejoin_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_rejoin_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + client.rejoin_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + +@pytest.mark.asyncio +async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.RejoinUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_rejoin_user_events_async_from_dict(): + await test_rejoin_user_events_async(request_type=dict) + + +def test_rejoin_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_rejoin_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.RejoinUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.rejoin_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, +]) +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", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'purge_user_events', + 'import_user_events', + 'rejoin_user_events', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_user_event_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_user_event_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +def test_user_event_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + UserEventServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "retail.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="retail.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'retail.googleapis.com:8000' + ) + +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = UserEventServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = UserEventServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_product_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + branch = "nautilus" + product = "scallop" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) + actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "abalone", + "location": "squid", + "catalog": "clam", + "branch": "whelk", + "product": "octopus", + } + path = UserEventServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From a53b52ab323d3134dccb7a33eb704a3871e5fb76 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 5 Jul 2022 23:13:27 +0000 Subject: [PATCH 06/11] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- owl-bot-staging/v2/.coveragerc | 17 - owl-bot-staging/v2/.flake8 | 33 - owl-bot-staging/v2/MANIFEST.in | 2 - owl-bot-staging/v2/README.rst | 49 - owl-bot-staging/v2/docs/conf.py | 376 - owl-bot-staging/v2/docs/index.rst | 7 - .../v2/docs/retail_v2/catalog_service.rst | 10 - .../v2/docs/retail_v2/completion_service.rst | 6 - .../v2/docs/retail_v2/prediction_service.rst | 6 - .../v2/docs/retail_v2/product_service.rst | 10 - .../v2/docs/retail_v2/search_service.rst | 10 - .../v2/docs/retail_v2/services.rst | 11 - owl-bot-staging/v2/docs/retail_v2/types.rst | 7 - .../v2/docs/retail_v2/user_event_service.rst | 6 - .../v2/google/cloud/retail/__init__.py | 193 - .../v2/google/cloud/retail/py.typed | 2 - .../v2/google/cloud/retail_v2/__init__.py | 194 - .../cloud/retail_v2/gapic_metadata.json | 333 - .../v2/google/cloud/retail_v2/py.typed | 2 - .../cloud/retail_v2/services/__init__.py | 15 - .../services/catalog_service/__init__.py | 22 - .../services/catalog_service/async_client.py | 653 -- .../services/catalog_service/client.py | 862 -- .../services/catalog_service/pagers.py | 140 - .../catalog_service/transports/__init__.py | 33 - .../catalog_service/transports/base.py | 198 - .../catalog_service/transports/grpc.py | 381 - .../transports/grpc_asyncio.py | 380 - .../services/completion_service/__init__.py | 22 - .../completion_service/async_client.py | 391 - .../services/completion_service/client.py | 593 -- .../completion_service/transports/__init__.py | 33 - .../completion_service/transports/base.py | 176 - .../completion_service/transports/grpc.py | 325 - .../transports/grpc_asyncio.py | 324 - .../services/prediction_service/__init__.py | 22 - .../prediction_service/async_client.py | 279 - .../services/prediction_service/client.py | 480 -- .../prediction_service/transports/__init__.py | 33 - .../prediction_service/transports/base.py | 154 - .../prediction_service/transports/grpc.py | 264 - .../transports/grpc_asyncio.py | 263 - .../services/product_service/__init__.py | 22 - .../services/product_service/async_client.py | 1701 ---- .../services/product_service/client.py | 1904 ----- .../services/product_service/pagers.py | 140 - .../product_service/transports/__init__.py | 33 - .../product_service/transports/base.py | 312 - .../product_service/transports/grpc.py | 680 -- .../transports/grpc_asyncio.py | 679 -- .../services/search_service/__init__.py | 22 - .../services/search_service/async_client.py | 303 - .../services/search_service/client.py | 513 -- .../services/search_service/pagers.py | 139 - .../search_service/transports/__init__.py | 33 - .../search_service/transports/base.py | 154 - .../search_service/transports/grpc.py | 270 - .../search_service/transports/grpc_asyncio.py | 269 - .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 730 -- .../services/user_event_service/client.py | 930 --- .../user_event_service/transports/__init__.py | 33 - .../user_event_service/transports/base.py | 235 - .../user_event_service/transports/grpc.py | 417 - .../transports/grpc_asyncio.py | 416 - .../google/cloud/retail_v2/types/__init__.py | 194 - .../google/cloud/retail_v2/types/catalog.py | 131 - .../cloud/retail_v2/types/catalog_service.py | 248 - .../v2/google/cloud/retail_v2/types/common.py | 736 -- .../retail_v2/types/completion_service.py | 229 - .../cloud/retail_v2/types/import_config.py | 697 -- .../retail_v2/types/prediction_service.py | 275 - .../google/cloud/retail_v2/types/product.py | 701 -- .../cloud/retail_v2/types/product_service.py | 858 -- .../google/cloud/retail_v2/types/promotion.py | 50 - .../cloud/retail_v2/types/purge_config.py | 107 - .../cloud/retail_v2/types/search_service.py | 1150 --- .../cloud/retail_v2/types/user_event.py | 508 -- .../retail_v2/types/user_event_service.py | 154 - owl-bot-staging/v2/mypy.ini | 3 - owl-bot-staging/v2/noxfile.py | 180 - ...atalog_service_get_default_branch_async.py | 44 - ...catalog_service_get_default_branch_sync.py | 44 - ...ted_catalog_service_list_catalogs_async.py | 46 - ...ated_catalog_service_list_catalogs_sync.py | 46 - ...atalog_service_set_default_branch_async.py | 42 - ...catalog_service_set_default_branch_sync.py | 42 - ...ed_catalog_service_update_catalog_async.py | 49 - ...ted_catalog_service_update_catalog_sync.py | 49 - ...completion_service_complete_query_async.py | 46 - ..._completion_service_complete_query_sync.py | 46 - ...on_service_import_completion_data_async.py | 54 - ...ion_service_import_completion_data_sync.py | 54 - ...erated_prediction_service_predict_async.py | 50 - ...nerated_prediction_service_predict_sync.py | 50 - ...ct_service_add_fulfillment_places_async.py | 51 - ...uct_service_add_fulfillment_places_sync.py | 51 - ...uct_service_add_local_inventories_async.py | 49 - ...duct_service_add_local_inventories_sync.py | 49 - ...ed_product_service_create_product_async.py | 50 - ...ted_product_service_create_product_sync.py | 50 - ...ed_product_service_delete_product_async.py | 43 - ...ted_product_service_delete_product_sync.py | 43 - ...rated_product_service_get_product_async.py | 45 - ...erated_product_service_get_product_sync.py | 45 - ...d_product_service_import_products_async.py | 53 - ...ed_product_service_import_products_sync.py | 53 - ...ted_product_service_list_products_async.py | 46 - ...ated_product_service_list_products_sync.py | 46 - ...service_remove_fulfillment_places_async.py | 51 - ..._service_remove_fulfillment_places_sync.py | 51 - ..._service_remove_local_inventories_async.py | 50 - ...t_service_remove_local_inventories_sync.py | 50 - ...ted_product_service_set_inventory_async.py | 52 - ...ated_product_service_set_inventory_sync.py | 52 - ...ed_product_service_update_product_async.py | 48 - ...ted_product_service_update_product_sync.py | 48 - ...2_generated_search_service_search_async.py | 47 - ...v2_generated_search_service_search_sync.py | 47 - ..._event_service_collect_user_event_async.py | 46 - ...r_event_service_collect_user_event_sync.py | 46 - ..._event_service_import_user_events_async.py | 54 - ...r_event_service_import_user_events_sync.py | 54 - ...r_event_service_purge_user_events_async.py | 50 - ...er_event_service_purge_user_events_sync.py | 50 - ..._event_service_rejoin_user_events_async.py | 49 - ...r_event_service_rejoin_user_events_sync.py | 49 - ...er_event_service_write_user_event_async.py | 50 - ...ser_event_service_write_user_event_sync.py | 50 - .../snippet_metadata_retail_v2.json | 3826 --------- .../v2/scripts/fixup_retail_v2_keywords.py | 199 - owl-bot-staging/v2/setup.py | 59 - owl-bot-staging/v2/tests/__init__.py | 16 - owl-bot-staging/v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../v2/tests/unit/gapic/retail_v2/__init__.py | 16 - .../gapic/retail_v2/test_catalog_service.py | 2317 ------ .../retail_v2/test_completion_service.py | 1501 ---- .../retail_v2/test_prediction_service.py | 1329 ---- .../gapic/retail_v2/test_product_service.py | 4135 ---------- .../gapic/retail_v2/test_search_service.py | 1546 ---- .../retail_v2/test_user_event_service.py | 2038 ----- owl-bot-staging/v2alpha/.coveragerc | 17 - owl-bot-staging/v2alpha/.flake8 | 33 - owl-bot-staging/v2alpha/MANIFEST.in | 2 - owl-bot-staging/v2alpha/README.rst | 49 - owl-bot-staging/v2alpha/docs/conf.py | 376 - owl-bot-staging/v2alpha/docs/index.rst | 7 - .../docs/retail_v2alpha/catalog_service.rst | 10 - .../retail_v2alpha/completion_service.rst | 6 - .../docs/retail_v2alpha/control_service.rst | 10 - .../retail_v2alpha/prediction_service.rst | 6 - .../docs/retail_v2alpha/product_service.rst | 10 - .../docs/retail_v2alpha/search_service.rst | 10 - .../v2alpha/docs/retail_v2alpha/services.rst | 13 - .../retail_v2alpha/serving_config_service.rst | 10 - .../v2alpha/docs/retail_v2alpha/types.rst | 7 - .../retail_v2alpha/user_event_service.rst | 6 - .../v2alpha/google/cloud/retail/__init__.py | 281 - .../v2alpha/google/cloud/retail/py.typed | 2 - .../google/cloud/retail_v2alpha/__init__.py | 282 - .../cloud/retail_v2alpha/gapic_metadata.json | 561 -- .../google/cloud/retail_v2alpha/py.typed | 2 - .../cloud/retail_v2alpha/services/__init__.py | 15 - .../services/catalog_service/__init__.py | 22 - .../services/catalog_service/async_client.py | 1352 ---- .../services/catalog_service/client.py | 1582 ---- .../services/catalog_service/pagers.py | 140 - .../catalog_service/transports/__init__.py | 33 - .../catalog_service/transports/base.py | 297 - .../catalog_service/transports/grpc.py | 600 -- .../transports/grpc_asyncio.py | 599 -- .../services/completion_service/__init__.py | 22 - .../completion_service/async_client.py | 391 - .../services/completion_service/client.py | 593 -- .../completion_service/transports/__init__.py | 33 - .../completion_service/transports/base.py | 176 - .../completion_service/transports/grpc.py | 325 - .../transports/grpc_asyncio.py | 324 - .../services/control_service/__init__.py | 22 - .../services/control_service/async_client.py | 744 -- .../services/control_service/client.py | 953 --- .../services/control_service/pagers.py | 140 - .../control_service/transports/__init__.py | 33 - .../control_service/transports/base.py | 213 - .../control_service/transports/grpc.py | 382 - .../transports/grpc_asyncio.py | 381 - .../services/prediction_service/__init__.py | 22 - .../prediction_service/async_client.py | 279 - .../services/prediction_service/client.py | 480 -- .../prediction_service/transports/__init__.py | 33 - .../prediction_service/transports/base.py | 154 - .../prediction_service/transports/grpc.py | 264 - .../transports/grpc_asyncio.py | 263 - .../services/product_service/__init__.py | 22 - .../services/product_service/async_client.py | 1804 ----- .../services/product_service/client.py | 2008 ----- .../services/product_service/pagers.py | 140 - .../product_service/transports/__init__.py | 33 - .../product_service/transports/base.py | 327 - .../product_service/transports/grpc.py | 726 -- .../transports/grpc_asyncio.py | 725 -- .../services/search_service/__init__.py | 22 - .../services/search_service/async_client.py | 303 - .../services/search_service/client.py | 513 -- .../services/search_service/pagers.py | 139 - .../search_service/transports/__init__.py | 33 - .../search_service/transports/base.py | 154 - .../search_service/transports/grpc.py | 270 - .../search_service/transports/grpc_asyncio.py | 269 - .../serving_config_service/__init__.py | 22 - .../serving_config_service/async_client.py | 954 --- .../services/serving_config_service/client.py | 1163 --- .../services/serving_config_service/pagers.py | 140 - .../transports/__init__.py | 33 - .../serving_config_service/transports/base.py | 241 - .../serving_config_service/transports/grpc.py | 440 - .../transports/grpc_asyncio.py | 439 - .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 730 -- .../services/user_event_service/client.py | 930 --- .../user_event_service/transports/__init__.py | 33 - .../user_event_service/transports/base.py | 235 - .../user_event_service/transports/grpc.py | 417 - .../transports/grpc_asyncio.py | 416 - .../cloud/retail_v2alpha/types/__init__.py | 284 - .../cloud/retail_v2alpha/types/catalog.py | 528 -- .../retail_v2alpha/types/catalog_service.py | 453 -- .../cloud/retail_v2alpha/types/common.py | 1179 --- .../types/completion_service.py | 223 - .../cloud/retail_v2alpha/types/control.py | 123 - .../retail_v2alpha/types/control_service.py | 197 - .../retail_v2alpha/types/export_config.py | 134 - .../retail_v2alpha/types/import_config.py | 691 -- .../types/prediction_service.py | 263 - .../cloud/retail_v2alpha/types/product.py | 705 -- .../retail_v2alpha/types/product_service.py | 877 -- .../cloud/retail_v2alpha/types/promotion.py | 50 - .../retail_v2alpha/types/purge_config.py | 251 - .../retail_v2alpha/types/search_service.py | 1099 --- .../retail_v2alpha/types/serving_config.py | 309 - .../types/serving_config_service.py | 234 - .../cloud/retail_v2alpha/types/user_event.py | 507 -- .../types/user_event_service.py | 154 - owl-bot-staging/v2alpha/mypy.ini | 3 - owl-bot-staging/v2alpha/noxfile.py | 180 - ...log_service_add_catalog_attribute_async.py | 49 - ...alog_service_add_catalog_attribute_sync.py | 49 - ...log_service_get_attributes_config_async.py | 45 - ...alog_service_get_attributes_config_sync.py | 45 - ...log_service_get_completion_config_async.py | 45 - ...alog_service_get_completion_config_sync.py | 45 - ...atalog_service_get_default_branch_async.py | 44 - ...catalog_service_get_default_branch_sync.py | 44 - ...ted_catalog_service_list_catalogs_async.py | 46 - ...ated_catalog_service_list_catalogs_sync.py | 46 - ..._service_remove_catalog_attribute_async.py | 46 - ...g_service_remove_catalog_attribute_sync.py | 46 - ...service_replace_catalog_attribute_async.py | 49 - ..._service_replace_catalog_attribute_sync.py | 49 - ...atalog_service_set_default_branch_async.py | 42 - ...catalog_service_set_default_branch_sync.py | 42 - ..._service_update_attributes_config_async.py | 48 - ...g_service_update_attributes_config_sync.py | 48 - ...ed_catalog_service_update_catalog_async.py | 49 - ...ted_catalog_service_update_catalog_sync.py | 49 - ..._service_update_completion_config_async.py | 48 - ...g_service_update_completion_config_sync.py | 48 - ...completion_service_complete_query_async.py | 46 - ..._completion_service_complete_query_sync.py | 46 - ...on_service_import_completion_data_async.py | 54 - ...ion_service_import_completion_data_sync.py | 54 - ...ed_control_service_create_control_async.py | 53 - ...ted_control_service_create_control_sync.py | 53 - ...ed_control_service_delete_control_async.py | 43 - ...ted_control_service_delete_control_sync.py | 43 - ...rated_control_service_get_control_async.py | 45 - ...erated_control_service_get_control_sync.py | 45 - ...ted_control_service_list_controls_async.py | 46 - ...ated_control_service_list_controls_sync.py | 46 - ...ed_control_service_update_control_async.py | 51 - ...ted_control_service_update_control_sync.py | 51 - ...erated_prediction_service_predict_async.py | 50 - ...nerated_prediction_service_predict_sync.py | 50 - ...ct_service_add_fulfillment_places_async.py | 51 - ...uct_service_add_fulfillment_places_sync.py | 51 - ...uct_service_add_local_inventories_async.py | 49 - ...duct_service_add_local_inventories_sync.py | 49 - ...ed_product_service_create_product_async.py | 50 - ...ted_product_service_create_product_sync.py | 50 - ...ed_product_service_delete_product_async.py | 43 - ...ted_product_service_delete_product_sync.py | 43 - ...rated_product_service_get_product_async.py | 45 - ...erated_product_service_get_product_sync.py | 45 - ...d_product_service_import_products_async.py | 53 - ...ed_product_service_import_products_sync.py | 53 - ...ted_product_service_list_products_async.py | 46 - ...ated_product_service_list_products_sync.py | 46 - ...ed_product_service_purge_products_async.py | 50 - ...ted_product_service_purge_products_sync.py | 50 - ...service_remove_fulfillment_places_async.py | 51 - ..._service_remove_fulfillment_places_sync.py | 51 - ..._service_remove_local_inventories_async.py | 50 - ...t_service_remove_local_inventories_sync.py | 50 - ...ted_product_service_set_inventory_async.py | 52 - ...ated_product_service_set_inventory_sync.py | 52 - ...ed_product_service_update_product_async.py | 48 - ...ted_product_service_update_product_sync.py | 48 - ...a_generated_search_service_search_async.py | 47 - ...ha_generated_search_service_search_sync.py | 47 - ...erving_config_service_add_control_async.py | 46 - ...serving_config_service_add_control_sync.py | 46 - ...fig_service_create_serving_config_async.py | 51 - ...nfig_service_create_serving_config_sync.py | 51 - ...fig_service_delete_serving_config_async.py | 43 - ...nfig_service_delete_serving_config_sync.py | 43 - ...config_service_get_serving_config_async.py | 45 - ..._config_service_get_serving_config_sync.py | 45 - ...nfig_service_list_serving_configs_async.py | 46 - ...onfig_service_list_serving_configs_sync.py | 46 - ...ing_config_service_remove_control_async.py | 46 - ...ving_config_service_remove_control_sync.py | 46 - ...fig_service_update_serving_config_async.py | 49 - ...nfig_service_update_serving_config_sync.py | 49 - ..._event_service_collect_user_event_async.py | 46 - ...r_event_service_collect_user_event_sync.py | 46 - ..._event_service_import_user_events_async.py | 54 - ...r_event_service_import_user_events_sync.py | 54 - ...r_event_service_purge_user_events_async.py | 50 - ...er_event_service_purge_user_events_sync.py | 50 - ..._event_service_rejoin_user_events_async.py | 49 - ...r_event_service_rejoin_user_events_sync.py | 49 - ...er_event_service_write_user_event_async.py | 50 - ...ser_event_service_write_user_event_sync.py | 50 - .../snippet_metadata_retail_v2alpha.json | 7066 ----------------- .../scripts/fixup_retail_v2alpha_keywords.py | 219 - owl-bot-staging/v2alpha/setup.py | 59 - owl-bot-staging/v2alpha/tests/__init__.py | 16 - .../v2alpha/tests/unit/__init__.py | 16 - .../v2alpha/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/retail_v2alpha/__init__.py | 16 - .../retail_v2alpha/test_catalog_service.py | 3843 --------- .../retail_v2alpha/test_completion_service.py | 1501 ---- .../retail_v2alpha/test_control_service.py | 2616 ------ .../retail_v2alpha/test_prediction_service.py | 1329 ---- .../retail_v2alpha/test_product_service.py | 4287 ---------- .../retail_v2alpha/test_search_service.py | 1546 ---- .../test_serving_config_service.py | 3329 -------- .../retail_v2alpha/test_user_event_service.py | 2038 ----- owl-bot-staging/v2beta/.coveragerc | 17 - owl-bot-staging/v2beta/.flake8 | 33 - owl-bot-staging/v2beta/MANIFEST.in | 2 - owl-bot-staging/v2beta/README.rst | 49 - owl-bot-staging/v2beta/docs/conf.py | 376 - owl-bot-staging/v2beta/docs/index.rst | 7 - .../docs/retail_v2beta/catalog_service.rst | 10 - .../docs/retail_v2beta/completion_service.rst | 6 - .../docs/retail_v2beta/control_service.rst | 10 - .../docs/retail_v2beta/prediction_service.rst | 6 - .../docs/retail_v2beta/product_service.rst | 10 - .../docs/retail_v2beta/search_service.rst | 10 - .../v2beta/docs/retail_v2beta/services.rst | 13 - .../retail_v2beta/serving_config_service.rst | 10 - .../v2beta/docs/retail_v2beta/types.rst | 7 - .../docs/retail_v2beta/user_event_service.rst | 6 - .../v2beta/google/cloud/retail/__init__.py | 275 - .../v2beta/google/cloud/retail/py.typed | 2 - .../google/cloud/retail_v2beta/__init__.py | 276 - .../cloud/retail_v2beta/gapic_metadata.json | 551 -- .../google/cloud/retail_v2beta/py.typed | 2 - .../cloud/retail_v2beta/services/__init__.py | 15 - .../services/catalog_service/__init__.py | 22 - .../services/catalog_service/async_client.py | 1350 ---- .../services/catalog_service/client.py | 1580 ---- .../services/catalog_service/pagers.py | 140 - .../catalog_service/transports/__init__.py | 33 - .../catalog_service/transports/base.py | 297 - .../catalog_service/transports/grpc.py | 600 -- .../transports/grpc_asyncio.py | 599 -- .../services/completion_service/__init__.py | 22 - .../completion_service/async_client.py | 391 - .../services/completion_service/client.py | 593 -- .../completion_service/transports/__init__.py | 33 - .../completion_service/transports/base.py | 176 - .../completion_service/transports/grpc.py | 325 - .../transports/grpc_asyncio.py | 324 - .../services/control_service/__init__.py | 22 - .../services/control_service/async_client.py | 742 -- .../services/control_service/client.py | 951 --- .../services/control_service/pagers.py | 140 - .../control_service/transports/__init__.py | 33 - .../control_service/transports/base.py | 213 - .../control_service/transports/grpc.py | 382 - .../transports/grpc_asyncio.py | 381 - .../services/prediction_service/__init__.py | 22 - .../prediction_service/async_client.py | 279 - .../services/prediction_service/client.py | 480 -- .../prediction_service/transports/__init__.py | 33 - .../prediction_service/transports/base.py | 154 - .../prediction_service/transports/grpc.py | 264 - .../transports/grpc_asyncio.py | 263 - .../services/product_service/__init__.py | 22 - .../services/product_service/async_client.py | 1692 ---- .../services/product_service/client.py | 1895 ----- .../services/product_service/pagers.py | 140 - .../product_service/transports/__init__.py | 33 - .../product_service/transports/base.py | 312 - .../product_service/transports/grpc.py | 680 -- .../transports/grpc_asyncio.py | 679 -- .../services/search_service/__init__.py | 22 - .../services/search_service/async_client.py | 303 - .../services/search_service/client.py | 513 -- .../services/search_service/pagers.py | 139 - .../search_service/transports/__init__.py | 33 - .../search_service/transports/base.py | 154 - .../search_service/transports/grpc.py | 270 - .../search_service/transports/grpc_asyncio.py | 269 - .../serving_config_service/__init__.py | 22 - .../serving_config_service/async_client.py | 954 --- .../services/serving_config_service/client.py | 1163 --- .../services/serving_config_service/pagers.py | 140 - .../transports/__init__.py | 33 - .../serving_config_service/transports/base.py | 241 - .../serving_config_service/transports/grpc.py | 440 - .../transports/grpc_asyncio.py | 439 - .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 730 -- .../services/user_event_service/client.py | 930 --- .../user_event_service/transports/__init__.py | 33 - .../user_event_service/transports/base.py | 235 - .../user_event_service/transports/grpc.py | 417 - .../transports/grpc_asyncio.py | 416 - .../cloud/retail_v2beta/types/__init__.py | 278 - .../cloud/retail_v2beta/types/catalog.py | 528 -- .../retail_v2beta/types/catalog_service.py | 453 -- .../cloud/retail_v2beta/types/common.py | 1178 --- .../retail_v2beta/types/completion_service.py | 223 - .../cloud/retail_v2beta/types/control.py | 112 - .../retail_v2beta/types/control_service.py | 197 - .../retail_v2beta/types/export_config.py | 134 - .../retail_v2beta/types/import_config.py | 691 -- .../retail_v2beta/types/prediction_service.py | 263 - .../cloud/retail_v2beta/types/product.py | 705 -- .../retail_v2beta/types/product_service.py | 844 -- .../cloud/retail_v2beta/types/promotion.py | 50 - .../cloud/retail_v2beta/types/purge_config.py | 107 - .../retail_v2beta/types/search_service.py | 1074 --- .../retail_v2beta/types/serving_config.py | 309 - .../types/serving_config_service.py | 234 - .../cloud/retail_v2beta/types/user_event.py | 507 -- .../retail_v2beta/types/user_event_service.py | 154 - owl-bot-staging/v2beta/mypy.ini | 3 - owl-bot-staging/v2beta/noxfile.py | 180 - ...log_service_add_catalog_attribute_async.py | 49 - ...alog_service_add_catalog_attribute_sync.py | 49 - ...log_service_get_attributes_config_async.py | 45 - ...alog_service_get_attributes_config_sync.py | 45 - ...log_service_get_completion_config_async.py | 45 - ...alog_service_get_completion_config_sync.py | 45 - ...atalog_service_get_default_branch_async.py | 44 - ...catalog_service_get_default_branch_sync.py | 44 - ...ted_catalog_service_list_catalogs_async.py | 46 - ...ated_catalog_service_list_catalogs_sync.py | 46 - ..._service_remove_catalog_attribute_async.py | 46 - ...g_service_remove_catalog_attribute_sync.py | 46 - ...service_replace_catalog_attribute_async.py | 49 - ..._service_replace_catalog_attribute_sync.py | 49 - ...atalog_service_set_default_branch_async.py | 42 - ...catalog_service_set_default_branch_sync.py | 42 - ..._service_update_attributes_config_async.py | 48 - ...g_service_update_attributes_config_sync.py | 48 - ...ed_catalog_service_update_catalog_async.py | 49 - ...ted_catalog_service_update_catalog_sync.py | 49 - ..._service_update_completion_config_async.py | 48 - ...g_service_update_completion_config_sync.py | 48 - ...completion_service_complete_query_async.py | 46 - ..._completion_service_complete_query_sync.py | 46 - ...on_service_import_completion_data_async.py | 54 - ...ion_service_import_completion_data_sync.py | 54 - ...ed_control_service_create_control_async.py | 52 - ...ted_control_service_create_control_sync.py | 52 - ...ed_control_service_delete_control_async.py | 43 - ...ted_control_service_delete_control_sync.py | 43 - ...rated_control_service_get_control_async.py | 45 - ...erated_control_service_get_control_sync.py | 45 - ...ted_control_service_list_controls_async.py | 46 - ...ated_control_service_list_controls_sync.py | 46 - ...ed_control_service_update_control_async.py | 50 - ...ted_control_service_update_control_sync.py | 50 - ...erated_prediction_service_predict_async.py | 50 - ...nerated_prediction_service_predict_sync.py | 50 - ...ct_service_add_fulfillment_places_async.py | 51 - ...uct_service_add_fulfillment_places_sync.py | 51 - ...uct_service_add_local_inventories_async.py | 49 - ...duct_service_add_local_inventories_sync.py | 49 - ...ed_product_service_create_product_async.py | 50 - ...ted_product_service_create_product_sync.py | 50 - ...ed_product_service_delete_product_async.py | 43 - ...ted_product_service_delete_product_sync.py | 43 - ...rated_product_service_get_product_async.py | 45 - ...erated_product_service_get_product_sync.py | 45 - ...d_product_service_import_products_async.py | 53 - ...ed_product_service_import_products_sync.py | 53 - ...ted_product_service_list_products_async.py | 46 - ...ated_product_service_list_products_sync.py | 46 - ...service_remove_fulfillment_places_async.py | 51 - ..._service_remove_fulfillment_places_sync.py | 51 - ..._service_remove_local_inventories_async.py | 50 - ...t_service_remove_local_inventories_sync.py | 50 - ...ted_product_service_set_inventory_async.py | 52 - ...ated_product_service_set_inventory_sync.py | 52 - ...ed_product_service_update_product_async.py | 48 - ...ted_product_service_update_product_sync.py | 48 - ...a_generated_search_service_search_async.py | 47 - ...ta_generated_search_service_search_sync.py | 47 - ...erving_config_service_add_control_async.py | 46 - ...serving_config_service_add_control_sync.py | 46 - ...fig_service_create_serving_config_async.py | 51 - ...nfig_service_create_serving_config_sync.py | 51 - ...fig_service_delete_serving_config_async.py | 43 - ...nfig_service_delete_serving_config_sync.py | 43 - ...config_service_get_serving_config_async.py | 45 - ..._config_service_get_serving_config_sync.py | 45 - ...nfig_service_list_serving_configs_async.py | 46 - ...onfig_service_list_serving_configs_sync.py | 46 - ...ing_config_service_remove_control_async.py | 46 - ...ving_config_service_remove_control_sync.py | 46 - ...fig_service_update_serving_config_async.py | 49 - ...nfig_service_update_serving_config_sync.py | 49 - ..._event_service_collect_user_event_async.py | 46 - ...r_event_service_collect_user_event_sync.py | 46 - ..._event_service_import_user_events_async.py | 54 - ...r_event_service_import_user_events_sync.py | 54 - ...r_event_service_purge_user_events_async.py | 50 - ...er_event_service_purge_user_events_sync.py | 50 - ..._event_service_rejoin_user_events_async.py | 49 - ...r_event_service_rejoin_user_events_sync.py | 49 - ...er_event_service_write_user_event_async.py | 50 - ...ser_event_service_write_user_event_sync.py | 50 - .../snippet_metadata_retail_v2beta.json | 6913 ---------------- .../scripts/fixup_retail_v2beta_keywords.py | 218 - owl-bot-staging/v2beta/setup.py | 59 - owl-bot-staging/v2beta/tests/__init__.py | 16 - owl-bot-staging/v2beta/tests/unit/__init__.py | 16 - .../v2beta/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/retail_v2beta/__init__.py | 16 - .../retail_v2beta/test_catalog_service.py | 3843 --------- .../retail_v2beta/test_completion_service.py | 1501 ---- .../retail_v2beta/test_control_service.py | 2604 ------ .../retail_v2beta/test_prediction_service.py | 1329 ---- .../retail_v2beta/test_product_service.py | 4135 ---------- .../retail_v2beta/test_search_service.py | 1546 ---- .../test_serving_config_service.py | 3329 -------- .../retail_v2beta/test_user_event_service.py | 2038 ----- .../gapic/retail_v2/test_catalog_service.py | 1 - .../retail_v2/test_completion_service.py | 1 - .../retail_v2/test_prediction_service.py | 1 - .../gapic/retail_v2/test_product_service.py | 1 - .../gapic/retail_v2/test_search_service.py | 1 - .../retail_v2/test_user_event_service.py | 1 - .../retail_v2alpha/test_catalog_service.py | 1 - .../retail_v2alpha/test_completion_service.py | 1 - .../retail_v2alpha/test_control_service.py | 1 - .../retail_v2alpha/test_prediction_service.py | 1 - .../retail_v2alpha/test_product_service.py | 1 - .../retail_v2alpha/test_search_service.py | 1 - .../test_serving_config_service.py | 1 - .../retail_v2alpha/test_user_event_service.py | 1 - .../retail_v2beta/test_catalog_service.py | 1 - .../retail_v2beta/test_completion_service.py | 1 - .../retail_v2beta/test_control_service.py | 1 - .../retail_v2beta/test_prediction_service.py | 1 - .../retail_v2beta/test_product_service.py | 1 - .../retail_v2beta/test_search_service.py | 1 - .../test_serving_config_service.py | 1 - .../retail_v2beta/test_user_event_service.py | 1 - 576 files changed, 175515 deletions(-) delete mode 100644 owl-bot-staging/v2/.coveragerc delete mode 100644 owl-bot-staging/v2/.flake8 delete mode 100644 owl-bot-staging/v2/MANIFEST.in delete mode 100644 owl-bot-staging/v2/README.rst delete mode 100644 owl-bot-staging/v2/docs/conf.py delete mode 100644 owl-bot-staging/v2/docs/index.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/catalog_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/completion_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/prediction_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/product_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/search_service.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/services.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/types.rst delete mode 100644 owl-bot-staging/v2/docs/retail_v2/user_event_service.rst delete mode 100644 owl-bot-staging/v2/google/cloud/retail/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/common.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/product.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py delete mode 100644 owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py delete mode 100644 owl-bot-staging/v2/mypy.ini delete mode 100644 owl-bot-staging/v2/noxfile.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json delete mode 100644 owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py delete mode 100644 owl-bot-staging/v2/setup.py delete mode 100644 owl-bot-staging/v2/tests/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py delete mode 100644 owl-bot-staging/v2alpha/.coveragerc delete mode 100644 owl-bot-staging/v2alpha/.flake8 delete mode 100644 owl-bot-staging/v2alpha/MANIFEST.in delete mode 100644 owl-bot-staging/v2alpha/README.rst delete mode 100644 owl-bot-staging/v2alpha/docs/conf.py delete mode 100644 owl-bot-staging/v2alpha/docs/index.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst delete mode 100644 owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail/py.typed delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py delete mode 100644 owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py delete mode 100644 owl-bot-staging/v2alpha/mypy.ini delete mode 100644 owl-bot-staging/v2alpha/noxfile.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py delete mode 100644 owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json delete mode 100644 owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py delete mode 100644 owl-bot-staging/v2alpha/setup.py delete mode 100644 owl-bot-staging/v2alpha/tests/__init__.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py delete mode 100644 owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py delete mode 100644 owl-bot-staging/v2beta/.coveragerc delete mode 100644 owl-bot-staging/v2beta/.flake8 delete mode 100644 owl-bot-staging/v2beta/MANIFEST.in delete mode 100644 owl-bot-staging/v2beta/README.rst delete mode 100644 owl-bot-staging/v2beta/docs/conf.py delete mode 100644 owl-bot-staging/v2beta/docs/index.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/services.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/types.rst delete mode 100644 owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail/py.typed delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py delete mode 100644 owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py delete mode 100644 owl-bot-staging/v2beta/mypy.ini delete mode 100644 owl-bot-staging/v2beta/noxfile.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py delete mode 100644 owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json delete mode 100644 owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py delete mode 100644 owl-bot-staging/v2beta/setup.py delete mode 100644 owl-bot-staging/v2beta/tests/__init__.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py delete mode 100644 owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc deleted file mode 100644 index a8b114f0..00000000 --- a/owl-bot-staging/v2/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/retail/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2/.flake8 b/owl-bot-staging/v2/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v2/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in deleted file mode 100644 index 985b915c..00000000 --- a/owl-bot-staging/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/retail *.py -recursive-include google/cloud/retail_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst deleted file mode 100644 index cb039760..00000000 --- a/owl-bot-staging/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Retail API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Retail API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py deleted file mode 100644 index 5be9eb4b..00000000 --- a/owl-bot-staging/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-retail documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-retail" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-retail-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-retail.tex", - u"google-cloud-retail Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-retail", - u"Google Cloud Retail Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-retail", - u"google-cloud-retail Documentation", - author, - "google-cloud-retail", - "GAPIC library for Google Cloud Retail API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst deleted file mode 100644 index c70f61bc..00000000 --- a/owl-bot-staging/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - retail_v2/services - retail_v2/types diff --git a/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst b/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst deleted file mode 100644 index 5b7227d9..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/catalog_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CatalogService --------------------------------- - -.. automodule:: google.cloud.retail_v2.services.catalog_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2.services.catalog_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/completion_service.rst b/owl-bot-staging/v2/docs/retail_v2/completion_service.rst deleted file mode 100644 index 551f89ed..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/completion_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CompletionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2.services.completion_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst b/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst deleted file mode 100644 index 12ffb6ee..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/prediction_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -PredictionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2.services.prediction_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/product_service.rst b/owl-bot-staging/v2/docs/retail_v2/product_service.rst deleted file mode 100644 index 0b8fa911..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/product_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ProductService --------------------------------- - -.. automodule:: google.cloud.retail_v2.services.product_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2.services.product_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/search_service.rst b/owl-bot-staging/v2/docs/retail_v2/search_service.rst deleted file mode 100644 index af72819d..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SearchService -------------------------------- - -.. automodule:: google.cloud.retail_v2.services.search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2.services.search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/retail_v2/services.rst b/owl-bot-staging/v2/docs/retail_v2/services.rst deleted file mode 100644 index f86138d7..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/services.rst +++ /dev/null @@ -1,11 +0,0 @@ -Services for Google Cloud Retail v2 API -======================================= -.. toctree:: - :maxdepth: 2 - - catalog_service - completion_service - prediction_service - product_service - search_service - user_event_service diff --git a/owl-bot-staging/v2/docs/retail_v2/types.rst b/owl-bot-staging/v2/docs/retail_v2/types.rst deleted file mode 100644 index 54951beb..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Retail v2 API -==================================== - -.. automodule:: google.cloud.retail_v2.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst b/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst deleted file mode 100644 index 00e214a9..00000000 --- a/owl-bot-staging/v2/docs/retail_v2/user_event_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.retail_v2.services.user_event_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/google/cloud/retail/__init__.py b/owl-bot-staging/v2/google/cloud/retail/__init__.py deleted file mode 100644 index 0d70ed64..00000000 --- a/owl-bot-staging/v2/google/cloud/retail/__init__.py +++ /dev/null @@ -1,193 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.retail_v2.services.catalog_service.client import CatalogServiceClient -from google.cloud.retail_v2.services.catalog_service.async_client import CatalogServiceAsyncClient -from google.cloud.retail_v2.services.completion_service.client import CompletionServiceClient -from google.cloud.retail_v2.services.completion_service.async_client import CompletionServiceAsyncClient -from google.cloud.retail_v2.services.prediction_service.client import PredictionServiceClient -from google.cloud.retail_v2.services.prediction_service.async_client import PredictionServiceAsyncClient -from google.cloud.retail_v2.services.product_service.client import ProductServiceClient -from google.cloud.retail_v2.services.product_service.async_client import ProductServiceAsyncClient -from google.cloud.retail_v2.services.search_service.client import SearchServiceClient -from google.cloud.retail_v2.services.search_service.async_client import SearchServiceAsyncClient -from google.cloud.retail_v2.services.user_event_service.client import UserEventServiceClient -from google.cloud.retail_v2.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.retail_v2.types.catalog import Catalog -from google.cloud.retail_v2.types.catalog import ProductLevelConfig -from google.cloud.retail_v2.types.catalog_service import GetDefaultBranchRequest -from google.cloud.retail_v2.types.catalog_service import GetDefaultBranchResponse -from google.cloud.retail_v2.types.catalog_service import ListCatalogsRequest -from google.cloud.retail_v2.types.catalog_service import ListCatalogsResponse -from google.cloud.retail_v2.types.catalog_service import SetDefaultBranchRequest -from google.cloud.retail_v2.types.catalog_service import UpdateCatalogRequest -from google.cloud.retail_v2.types.common import Audience -from google.cloud.retail_v2.types.common import ColorInfo -from google.cloud.retail_v2.types.common import CustomAttribute -from google.cloud.retail_v2.types.common import FulfillmentInfo -from google.cloud.retail_v2.types.common import Image -from google.cloud.retail_v2.types.common import Interval -from google.cloud.retail_v2.types.common import LocalInventory -from google.cloud.retail_v2.types.common import PriceInfo -from google.cloud.retail_v2.types.common import Rating -from google.cloud.retail_v2.types.common import UserInfo -from google.cloud.retail_v2.types.completion_service import CompleteQueryRequest -from google.cloud.retail_v2.types.completion_service import CompleteQueryResponse -from google.cloud.retail_v2.types.import_config import BigQuerySource -from google.cloud.retail_v2.types.import_config import CompletionDataInputConfig -from google.cloud.retail_v2.types.import_config import GcsSource -from google.cloud.retail_v2.types.import_config import ImportCompletionDataRequest -from google.cloud.retail_v2.types.import_config import ImportCompletionDataResponse -from google.cloud.retail_v2.types.import_config import ImportErrorsConfig -from google.cloud.retail_v2.types.import_config import ImportMetadata -from google.cloud.retail_v2.types.import_config import ImportProductsRequest -from google.cloud.retail_v2.types.import_config import ImportProductsResponse -from google.cloud.retail_v2.types.import_config import ImportUserEventsRequest -from google.cloud.retail_v2.types.import_config import ImportUserEventsResponse -from google.cloud.retail_v2.types.import_config import ProductInlineSource -from google.cloud.retail_v2.types.import_config import ProductInputConfig -from google.cloud.retail_v2.types.import_config import UserEventImportSummary -from google.cloud.retail_v2.types.import_config import UserEventInlineSource -from google.cloud.retail_v2.types.import_config import UserEventInputConfig -from google.cloud.retail_v2.types.prediction_service import PredictRequest -from google.cloud.retail_v2.types.prediction_service import PredictResponse -from google.cloud.retail_v2.types.product import Product -from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesMetadata -from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesRequest -from google.cloud.retail_v2.types.product_service import AddFulfillmentPlacesResponse -from google.cloud.retail_v2.types.product_service import AddLocalInventoriesMetadata -from google.cloud.retail_v2.types.product_service import AddLocalInventoriesRequest -from google.cloud.retail_v2.types.product_service import AddLocalInventoriesResponse -from google.cloud.retail_v2.types.product_service import CreateProductRequest -from google.cloud.retail_v2.types.product_service import DeleteProductRequest -from google.cloud.retail_v2.types.product_service import GetProductRequest -from google.cloud.retail_v2.types.product_service import ListProductsRequest -from google.cloud.retail_v2.types.product_service import ListProductsResponse -from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesMetadata -from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesRequest -from google.cloud.retail_v2.types.product_service import RemoveFulfillmentPlacesResponse -from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesMetadata -from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesRequest -from google.cloud.retail_v2.types.product_service import RemoveLocalInventoriesResponse -from google.cloud.retail_v2.types.product_service import SetInventoryMetadata -from google.cloud.retail_v2.types.product_service import SetInventoryRequest -from google.cloud.retail_v2.types.product_service import SetInventoryResponse -from google.cloud.retail_v2.types.product_service import UpdateProductRequest -from google.cloud.retail_v2.types.promotion import Promotion -from google.cloud.retail_v2.types.purge_config import PurgeMetadata -from google.cloud.retail_v2.types.purge_config import PurgeUserEventsRequest -from google.cloud.retail_v2.types.purge_config import PurgeUserEventsResponse -from google.cloud.retail_v2.types.search_service import SearchRequest -from google.cloud.retail_v2.types.search_service import SearchResponse -from google.cloud.retail_v2.types.user_event import CompletionDetail -from google.cloud.retail_v2.types.user_event import ProductDetail -from google.cloud.retail_v2.types.user_event import PurchaseTransaction -from google.cloud.retail_v2.types.user_event import UserEvent -from google.cloud.retail_v2.types.user_event_service import CollectUserEventRequest -from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsMetadata -from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsRequest -from google.cloud.retail_v2.types.user_event_service import RejoinUserEventsResponse -from google.cloud.retail_v2.types.user_event_service import WriteUserEventRequest - -__all__ = ('CatalogServiceClient', - 'CatalogServiceAsyncClient', - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', - 'ProductServiceClient', - 'ProductServiceAsyncClient', - 'SearchServiceClient', - 'SearchServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'Catalog', - 'ProductLevelConfig', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'SetDefaultBranchRequest', - 'UpdateCatalogRequest', - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2/google/cloud/retail/py.typed b/owl-bot-staging/v2/google/cloud/retail/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2/google/cloud/retail/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py deleted file mode 100644 index c7f56a8d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/__init__.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.catalog_service import CatalogServiceClient -from .services.catalog_service import CatalogServiceAsyncClient -from .services.completion_service import CompletionServiceClient -from .services.completion_service import CompletionServiceAsyncClient -from .services.prediction_service import PredictionServiceClient -from .services.prediction_service import PredictionServiceAsyncClient -from .services.product_service import ProductServiceClient -from .services.product_service import ProductServiceAsyncClient -from .services.search_service import SearchServiceClient -from .services.search_service import SearchServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.catalog import Catalog -from .types.catalog import ProductLevelConfig -from .types.catalog_service import GetDefaultBranchRequest -from .types.catalog_service import GetDefaultBranchResponse -from .types.catalog_service import ListCatalogsRequest -from .types.catalog_service import ListCatalogsResponse -from .types.catalog_service import SetDefaultBranchRequest -from .types.catalog_service import UpdateCatalogRequest -from .types.common import Audience -from .types.common import ColorInfo -from .types.common import CustomAttribute -from .types.common import FulfillmentInfo -from .types.common import Image -from .types.common import Interval -from .types.common import LocalInventory -from .types.common import PriceInfo -from .types.common import Rating -from .types.common import UserInfo -from .types.completion_service import CompleteQueryRequest -from .types.completion_service import CompleteQueryResponse -from .types.import_config import BigQuerySource -from .types.import_config import CompletionDataInputConfig -from .types.import_config import GcsSource -from .types.import_config import ImportCompletionDataRequest -from .types.import_config import ImportCompletionDataResponse -from .types.import_config import ImportErrorsConfig -from .types.import_config import ImportMetadata -from .types.import_config import ImportProductsRequest -from .types.import_config import ImportProductsResponse -from .types.import_config import ImportUserEventsRequest -from .types.import_config import ImportUserEventsResponse -from .types.import_config import ProductInlineSource -from .types.import_config import ProductInputConfig -from .types.import_config import UserEventImportSummary -from .types.import_config import UserEventInlineSource -from .types.import_config import UserEventInputConfig -from .types.prediction_service import PredictRequest -from .types.prediction_service import PredictResponse -from .types.product import Product -from .types.product_service import AddFulfillmentPlacesMetadata -from .types.product_service import AddFulfillmentPlacesRequest -from .types.product_service import AddFulfillmentPlacesResponse -from .types.product_service import AddLocalInventoriesMetadata -from .types.product_service import AddLocalInventoriesRequest -from .types.product_service import AddLocalInventoriesResponse -from .types.product_service import CreateProductRequest -from .types.product_service import DeleteProductRequest -from .types.product_service import GetProductRequest -from .types.product_service import ListProductsRequest -from .types.product_service import ListProductsResponse -from .types.product_service import RemoveFulfillmentPlacesMetadata -from .types.product_service import RemoveFulfillmentPlacesRequest -from .types.product_service import RemoveFulfillmentPlacesResponse -from .types.product_service import RemoveLocalInventoriesMetadata -from .types.product_service import RemoveLocalInventoriesRequest -from .types.product_service import RemoveLocalInventoriesResponse -from .types.product_service import SetInventoryMetadata -from .types.product_service import SetInventoryRequest -from .types.product_service import SetInventoryResponse -from .types.product_service import UpdateProductRequest -from .types.promotion import Promotion -from .types.purge_config import PurgeMetadata -from .types.purge_config import PurgeUserEventsRequest -from .types.purge_config import PurgeUserEventsResponse -from .types.search_service import SearchRequest -from .types.search_service import SearchResponse -from .types.user_event import CompletionDetail -from .types.user_event import ProductDetail -from .types.user_event import PurchaseTransaction -from .types.user_event import UserEvent -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import RejoinUserEventsMetadata -from .types.user_event_service import RejoinUserEventsRequest -from .types.user_event_service import RejoinUserEventsResponse -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CatalogServiceAsyncClient', - 'CompletionServiceAsyncClient', - 'PredictionServiceAsyncClient', - 'ProductServiceAsyncClient', - 'SearchServiceAsyncClient', - 'UserEventServiceAsyncClient', -'AddFulfillmentPlacesMetadata', -'AddFulfillmentPlacesRequest', -'AddFulfillmentPlacesResponse', -'AddLocalInventoriesMetadata', -'AddLocalInventoriesRequest', -'AddLocalInventoriesResponse', -'Audience', -'BigQuerySource', -'Catalog', -'CatalogServiceClient', -'CollectUserEventRequest', -'ColorInfo', -'CompleteQueryRequest', -'CompleteQueryResponse', -'CompletionDataInputConfig', -'CompletionDetail', -'CompletionServiceClient', -'CreateProductRequest', -'CustomAttribute', -'DeleteProductRequest', -'FulfillmentInfo', -'GcsSource', -'GetDefaultBranchRequest', -'GetDefaultBranchResponse', -'GetProductRequest', -'Image', -'ImportCompletionDataRequest', -'ImportCompletionDataResponse', -'ImportErrorsConfig', -'ImportMetadata', -'ImportProductsRequest', -'ImportProductsResponse', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'Interval', -'ListCatalogsRequest', -'ListCatalogsResponse', -'ListProductsRequest', -'ListProductsResponse', -'LocalInventory', -'PredictRequest', -'PredictResponse', -'PredictionServiceClient', -'PriceInfo', -'Product', -'ProductDetail', -'ProductInlineSource', -'ProductInputConfig', -'ProductLevelConfig', -'ProductServiceClient', -'Promotion', -'PurchaseTransaction', -'PurgeMetadata', -'PurgeUserEventsRequest', -'PurgeUserEventsResponse', -'Rating', -'RejoinUserEventsMetadata', -'RejoinUserEventsRequest', -'RejoinUserEventsResponse', -'RemoveFulfillmentPlacesMetadata', -'RemoveFulfillmentPlacesRequest', -'RemoveFulfillmentPlacesResponse', -'RemoveLocalInventoriesMetadata', -'RemoveLocalInventoriesRequest', -'RemoveLocalInventoriesResponse', -'SearchRequest', -'SearchResponse', -'SearchServiceClient', -'SetDefaultBranchRequest', -'SetInventoryMetadata', -'SetInventoryRequest', -'SetInventoryResponse', -'UpdateCatalogRequest', -'UpdateProductRequest', -'UserEvent', -'UserEventImportSummary', -'UserEventInlineSource', -'UserEventInputConfig', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json deleted file mode 100644 index 9e04aec8..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/gapic_metadata.json +++ /dev/null @@ -1,333 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.retail_v2", - "protoPackage": "google.cloud.retail.v2", - "schema": "1.0", - "services": { - "CatalogService": { - "clients": { - "grpc": { - "libraryClient": "CatalogServiceClient", - "rpcs": { - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CatalogServiceAsyncClient", - "rpcs": { - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - } - } - } - } - }, - "CompletionService": { - "clients": { - "grpc": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CompletionServiceAsyncClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - } - } - }, - "PredictionService": { - "clients": { - "grpc": { - "libraryClient": "PredictionServiceClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PredictionServiceAsyncClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - } - } - }, - "ProductService": { - "clients": { - "grpc": { - "libraryClient": "ProductServiceClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProductServiceAsyncClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - } - } - }, - "SearchService": { - "clients": { - "grpc": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SearchServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/py.typed b/owl-bot-staging/v2/google/cloud/retail_v2/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py deleted file mode 100644 index d276b897..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CatalogServiceClient -from .async_client import CatalogServiceAsyncClient - -__all__ = ( - 'CatalogServiceClient', - 'CatalogServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py deleted file mode 100644 index b0a1b99e..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/async_client.py +++ /dev/null @@ -1,653 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.services.catalog_service import pagers -from google.cloud.retail_v2.types import catalog -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport -from .client import CatalogServiceClient - - -class CatalogServiceAsyncClient: - """Service for managing catalog configuration.""" - - _client: CatalogServiceClient - - DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(CatalogServiceClient.branch_path) - parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) - catalog_path = staticmethod(CatalogServiceClient.catalog_path) - parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) - common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CatalogServiceClient.common_project_path) - parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) - common_location_path = staticmethod(CatalogServiceClient.common_location_path) - parse_common_location_path = staticmethod(CatalogServiceClient.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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CatalogServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsAsyncPager: - r"""Lists all the [Catalog][google.cloud.retail.v2.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_list_catalogs(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - parent (:class:`str`): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2.Catalog]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.retail_v2.services.catalog_service.pagers.ListCatalogsAsyncPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.ListCatalogsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_catalogs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCatalogsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_update_catalog(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] - method. - catalog (:class:`google.cloud.retail_v2.types.Catalog`): - Required. The [Catalog][google.cloud.retail.v2.Catalog] - to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2.Catalog], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCatalogRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_catalog, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_set_default_branch(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (:class:`str`): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.SetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_get_default_branch(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (:class:`str`): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # 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_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py deleted file mode 100644 index dab9ff8c..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/client.py +++ /dev/null @@ -1,862 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.services.catalog_service import pagers -from google.cloud.retail_v2.types import catalog -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CatalogServiceGrpcTransport -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -class CatalogServiceClientMeta(type): - """Metaclass for the CatalogService 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[CatalogServiceTransport]] - _transport_registry["grpc"] = CatalogServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CatalogServiceTransport]: - """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): - """Service for managing catalog configuration.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CatalogServiceClient: 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: - CatalogServiceClient: 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) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CatalogServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CatalogServiceTransport): - # transport is a CatalogServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsPager: - r"""Lists all the [Catalog][google.cloud.retail.v2.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_list_catalogs(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2.Catalog]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.retail_v2.services.catalog_service.pagers.ListCatalogsPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ListCatalogsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ListCatalogsRequest): - request = catalog_service.ListCatalogsRequest(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_catalogs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCatalogsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_update_catalog(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] - method. - catalog (google.cloud.retail_v2.types.Catalog): - Required. The [Catalog][google.cloud.retail.v2.Catalog] - to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2.Catalog], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCatalogRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCatalogRequest): - request = catalog_service.UpdateCatalogRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - 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_catalog] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_set_default_branch(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.SetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.SetDefaultBranchRequest): - request = catalog_service.SetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_get_default_branch(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetDefaultBranchRequest): - request = catalog_service.GetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py deleted file mode 100644 index 11dd0677..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2.types import catalog -from google.cloud.retail_v2.types import catalog_service - - -class ListCatalogsPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.ListCatalogsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.ListCatalogsResponse` - 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[..., catalog_service.ListCatalogsResponse], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - for page in self.pages: - yield from page.catalogs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCatalogsAsyncPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.ListCatalogsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.ListCatalogsResponse` - 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[catalog_service.ListCatalogsResponse]], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - async def async_generator(): - async for page in self.pages: - for response in page.catalogs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py deleted file mode 100644 index 0cffa336..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CatalogServiceTransport -from .grpc import CatalogServiceGrpcTransport -from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] -_transport_registry['grpc'] = CatalogServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport - -__all__ = ( - 'CatalogServiceTransport', - 'CatalogServiceGrpcTransport', - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py deleted file mode 100644 index 661247c1..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/base.py +++ /dev/null @@ -1,198 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CatalogServiceTransport(abc.ABC): - """Abstract transport class for CatalogService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_catalogs: gapic_v1.method.wrap_method( - self.list_catalogs, - default_timeout=None, - client_info=client_info, - ), - self.update_catalog: gapic_v1.method.wrap_method( - self.update_catalog, - default_timeout=None, - client_info=client_info, - ), - self.set_default_branch: gapic_v1.method.wrap_method( - self.set_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_default_branch: gapic_v1.method.wrap_method( - self.get_default_branch, - 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Union[ - catalog_service.ListCatalogsResponse, - Awaitable[catalog_service.ListCatalogsResponse] - ]]: - raise NotImplementedError() - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Union[ - gcr_catalog.Catalog, - Awaitable[gcr_catalog.Catalog] - ]]: - raise NotImplementedError() - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Union[ - catalog_service.GetDefaultBranchResponse, - Awaitable[catalog_service.GetDefaultBranchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CatalogServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py deleted file mode 100644 index 17492b4a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc.py +++ /dev/null @@ -1,381 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO - - -class CatalogServiceGrpcTransport(CatalogServiceTransport): - """gRPC backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - catalog_service.ListCatalogsResponse]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - ~.ListCatalogsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - gcr_catalog.Catalog]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - ~.Catalog]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - empty_pb2.Empty]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - ~.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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - catalog_service.GetDefaultBranchResponse]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - ~.GetDefaultBranchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CatalogServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py deleted file mode 100644 index dfc3cd7b..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,380 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CatalogServiceGrpcTransport - - -class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): - """gRPC AsyncIO backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Awaitable[catalog_service.ListCatalogsResponse]]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - Awaitable[~.ListCatalogsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Awaitable[gcr_catalog.Catalog]]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - Awaitable[~.Catalog]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - 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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Awaitable[catalog_service.GetDefaultBranchResponse]]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - Awaitable[~.GetDefaultBranchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py deleted file mode 100644 index b8af95bd..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CompletionServiceClient -from .async_client import CompletionServiceAsyncClient - -__all__ = ( - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py deleted file mode 100644 index 9e5d6432..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/async_client.py +++ /dev/null @@ -1,391 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .client import CompletionServiceClient - - -class CompletionServiceAsyncClient: - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: CompletionServiceClient - - DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(CompletionServiceClient.catalog_path) - parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) - common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CompletionServiceClient.common_project_path) - parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) - common_location_path = staticmethod(CompletionServiceClient.common_location_path) - parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CompletionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_complete_query(): - # Create a client - client = retail_v2.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.complete_query, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_import_completion_data(): - # Create a client - client = retail_v2.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. - 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. - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_completion_data, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py deleted file mode 100644 index ca5bb55d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/client.py +++ /dev/null @@ -1,593 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CompletionServiceGrpcTransport -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -class CompletionServiceClientMeta(type): - """Metaclass for the CompletionService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] - _transport_registry["grpc"] = CompletionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CompletionServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class CompletionServiceClient(metaclass=CompletionServiceClientMeta): - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CompletionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CompletionServiceTransport): - # transport is a CompletionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_complete_query(): - # Create a client - client = retail_v2.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a completion_service.CompleteQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, completion_service.CompleteQueryRequest): - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_import_completion_data(): - # Create a client - client = retail_v2.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. - 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. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportCompletionDataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportCompletionDataRequest): - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_completion_data] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py deleted file mode 100644 index a0c9542f..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CompletionServiceTransport -from .grpc import CompletionServiceGrpcTransport -from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] -_transport_registry['grpc'] = CompletionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport - -__all__ = ( - 'CompletionServiceTransport', - 'CompletionServiceGrpcTransport', - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py deleted file mode 100644 index 7b2cb516..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/base.py +++ /dev/null @@ -1,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CompletionServiceTransport(abc.ABC): - """Abstract transport class for CompletionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.complete_query: gapic_v1.method.wrap_method( - self.complete_query, - default_timeout=None, - client_info=client_info, - ), - self.import_completion_data: gapic_v1.method.wrap_method( - self.import_completion_data, - 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Union[ - completion_service.CompleteQueryResponse, - Awaitable[completion_service.CompleteQueryResponse] - ]]: - raise NotImplementedError() - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CompletionServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py deleted file mode 100644 index 44cb929b..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc.py +++ /dev/null @@ -1,325 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO - - -class CompletionServiceGrpcTransport(CompletionServiceTransport): - """gRPC backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - ~.CompleteQueryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - operations_pb2.Operation]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CompletionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py deleted file mode 100644 index f7131541..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,324 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CompletionServiceGrpcTransport - - -class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): - """gRPC AsyncIO backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Awaitable[completion_service.CompleteQueryResponse]]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - Awaitable[~.CompleteQueryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - 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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py deleted file mode 100644 index 7c079c80..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import PredictionServiceClient -from .async_client import PredictionServiceAsyncClient - -__all__ = ( - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py deleted file mode 100644 index ae9f9c86..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/async_client.py +++ /dev/null @@ -1,279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport -from .client import PredictionServiceClient - - -class PredictionServiceAsyncClient: - """Service for making recommendation prediction.""" - - _client: PredictionServiceClient - - DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT - - product_path = staticmethod(PredictionServiceClient.product_path) - parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) - common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(PredictionServiceClient.common_project_path) - parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) - common_location_path = staticmethod(PredictionServiceClient.common_location_path) - parse_common_location_path = staticmethod(PredictionServiceClient.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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PredictionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_predict(): - # Create a client - client = retail_v2.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - request = prediction_service.PredictRequest(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.predict, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py deleted file mode 100644 index 67a94f53..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/client.py +++ /dev/null @@ -1,480 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PredictionServiceGrpcTransport -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -class PredictionServiceClientMeta(type): - """Metaclass for the PredictionService 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[PredictionServiceTransport]] - _transport_registry["grpc"] = PredictionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PredictionServiceTransport]: - """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): - """Service for making recommendation prediction.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PredictionServiceClient: 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: - PredictionServiceClient: 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) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, PredictionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, PredictionServiceTransport): - # transport is a PredictionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_predict(): - # Create a client - client = retail_v2.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a prediction_service.PredictRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_service.PredictRequest): - request = prediction_service.PredictRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.predict] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py deleted file mode 100644 index bb65c664..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PredictionServiceTransport -from .grpc import PredictionServiceGrpcTransport -from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] -_transport_registry['grpc'] = PredictionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport - -__all__ = ( - 'PredictionServiceTransport', - 'PredictionServiceGrpcTransport', - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py deleted file mode 100644 index f3b77c06..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import prediction_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PredictionServiceTransport(abc.ABC): - """Abstract transport class for PredictionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.predict: gapic_v1.method.wrap_method( - self.predict, - 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - Union[ - prediction_service.PredictResponse, - Awaitable[prediction_service.PredictResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PredictionServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py deleted file mode 100644 index 0e86800c..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc.py +++ /dev/null @@ -1,264 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO - - -class PredictionServiceGrpcTransport(PredictionServiceTransport): - """gRPC backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - prediction_service.PredictResponse]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - ~.PredictResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PredictionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py deleted file mode 100644 index 472e079a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import PredictionServiceGrpcTransport - - -class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): - """gRPC AsyncIO backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def predict(self) -> Callable[ - [prediction_service.PredictRequest], - Awaitable[prediction_service.PredictResponse]]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - Awaitable[~.PredictResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py deleted file mode 100644 index 0fa6330a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ProductServiceClient -from .async_client import ProductServiceAsyncClient - -__all__ = ( - 'ProductServiceClient', - 'ProductServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py deleted file mode 100644 index db29be72..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/async_client.py +++ /dev/null @@ -1,1701 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.services.product_service import pagers -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.cloud.retail_v2.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport -from .client import ProductServiceClient - - -class ProductServiceAsyncClient: - """Service for ingesting [Product][google.cloud.retail.v2.Product] - information of the customer's website. - """ - - _client: ProductServiceClient - - DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(ProductServiceClient.branch_path) - parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) - product_path = staticmethod(ProductServiceClient.product_path) - parse_product_path = staticmethod(ProductServiceClient.parse_product_path) - common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProductServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProductServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ProductServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) - common_location_path = staticmethod(ProductServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProductServiceClient.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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ProductServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ProductServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_create_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (:class:`str`): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (:class:`google.cloud.retail_v2.types.Product`): - Required. The [Product][google.cloud.retail.v2.Product] - to create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (:class:`str`): - Required. The ID to use for the - [Product][google.cloud.retail.v2.Product], which will - become the final component of the - [Product.name][google.cloud.retail.v2.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2.Product]s with the same - [parent][google.cloud.retail.v2.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.CreateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_get_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested - [Product][google.cloud.retail.v2.Product] 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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.GetProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsAsyncPager: - r"""Gets a list of [Product][google.cloud.retail.v2.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_list_products(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - parent (:class:`str`): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2.Product]s under this - branch, regardless of whether or not this branch exists, - a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.services.product_service.pagers.ListProductsAsyncPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.ListProductsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_products, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProductsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_update_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (:class:`google.cloud.retail_v2.types.Product`): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2.Product] to update. The - immutable and output only fields are NOT supported. If - not set, all supported fields (the fields that are - neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - The attribute key can be updated by setting the mask - path as "attributes.${key_name}". If a key name is - present in the mask but not in the patching product from - the request, this key will be deleted after the update. - - 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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.UpdateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_delete_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2.Product] to delete - can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] with more than - one - [variants][google.cloud.retail.v2.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.DeleteProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2.Product]s. - - Request processing may be synchronous. Non-existing items are - created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2.Product]s to be successfully - updated. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_import_products(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2.Product] while respecting the - last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_set_inventory(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2.Product() - inventory.title = "title_value" - - request = retail_v2.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (:class:`google.cloud.retail_v2.types.Product`): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product] named in - [Product.name][google.cloud.retail.v2.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.SetInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_inventory, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - async def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places, - while respecting the last update timestamps of each inventory - field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_add_local_inventories(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.AddLocalInventoriesResponse` Response of the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - API. Currently empty because there is no meaningful - response populated from the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places at - a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_remove_local_inventories(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py deleted file mode 100644 index dc6ce5c9..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/client.py +++ /dev/null @@ -1,1904 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.services.product_service import pagers -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.cloud.retail_v2.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProductServiceGrpcTransport -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -class ProductServiceClientMeta(type): - """Metaclass for the ProductService 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[ProductServiceTransport]] - _transport_registry["grpc"] = ProductServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ProductServiceTransport]: - """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 ProductServiceClient(metaclass=ProductServiceClientMeta): - """Service for ingesting [Product][google.cloud.retail.v2.Product] - information of the customer's website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProductServiceClient: 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: - ProductServiceClient: 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) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProductServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ProductServiceTransport): - # transport is a ProductServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_create_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (google.cloud.retail_v2.types.Product): - Required. The [Product][google.cloud.retail.v2.Product] - to create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2.Product], which will - become the final component of the - [Product.name][google.cloud.retail.v2.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2.Product]s with the same - [parent][google.cloud.retail.v2.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.CreateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.CreateProductRequest): - request = product_service.CreateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_get_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested - [Product][google.cloud.retail.v2.Product] 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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.GetProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.GetProductRequest): - request = product_service.GetProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsPager: - r"""Gets a list of [Product][google.cloud.retail.v2.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_list_products(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2.Product]s under this - branch, regardless of whether or not this branch exists, - a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.services.product_service.pagers.ListProductsPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.ListProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.ListProductsRequest): - request = product_service.ListProductsRequest(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_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProductsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_update_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (google.cloud.retail_v2.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2.Product] to update. The - immutable and output only fields are NOT supported. If - not set, all supported fields (the fields that are - neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - The attribute key can be updated by setting the mask - path as "attributes.${key_name}". If a key name is - present in the mask but not in the patching product from - the request, this key will be deleted after the update. - - 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.retail_v2.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.UpdateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.UpdateProductRequest): - request = product_service.UpdateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - 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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2.Product]. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_delete_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2.Product] to delete - can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] with more than - one - [variants][google.cloud.retail.v2.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.DeleteProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.DeleteProductRequest): - request = product_service.DeleteProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2.Product]s. - - Request processing may be synchronous. Non-existing items are - created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2.Product]s to be successfully - updated. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_import_products(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportProductsRequest): - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2.Product] while respecting the - last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_set_inventory(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2.Product() - inventory.title = "title_value" - - request = retail_v2.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (google.cloud.retail_v2.types.Product): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product] named in - [Product.name][google.cloud.retail.v2.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.SetInventoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.SetInventoryRequest): - request = product_service.SetInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_add_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddFulfillmentPlacesRequest): - request = product_service.AddFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): - request = product_service.RemoveFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places, - while respecting the last update timestamps of each inventory - field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_add_local_inventories(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.AddLocalInventoriesResponse` Response of the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - API. Currently empty because there is no meaningful - response populated from the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddLocalInventoriesRequest): - request = product_service.AddLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places at - a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_remove_local_inventories(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveLocalInventoriesRequest): - request = product_service.RemoveLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py deleted file mode 100644 index f9e49958..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product_service - - -class ListProductsPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.ListProductsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.ListProductsResponse` - 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[..., product_service.ListProductsResponse], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[product_service.ListProductsResponse]: - 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[product.Product]: - for page in self.pages: - yield from page.products - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProductsAsyncPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.ListProductsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.ListProductsResponse` - 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[product_service.ListProductsResponse]], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: - 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[product.Product]: - async def async_generator(): - async for page in self.pages: - for response in page.products: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py deleted file mode 100644 index db824dec..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ProductServiceTransport -from .grpc import ProductServiceGrpcTransport -from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] -_transport_registry['grpc'] = ProductServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport - -__all__ = ( - 'ProductServiceTransport', - 'ProductServiceGrpcTransport', - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py deleted file mode 100644 index e3de653c..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/base.py +++ /dev/null @@ -1,312 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ProductServiceTransport(abc.ABC): - """Abstract transport class for ProductService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_product: gapic_v1.method.wrap_method( - self.create_product, - default_timeout=None, - client_info=client_info, - ), - self.get_product: gapic_v1.method.wrap_method( - self.get_product, - default_timeout=None, - client_info=client_info, - ), - self.list_products: gapic_v1.method.wrap_method( - self.list_products, - default_timeout=None, - client_info=client_info, - ), - self.update_product: gapic_v1.method.wrap_method( - self.update_product, - default_timeout=None, - client_info=client_info, - ), - self.delete_product: gapic_v1.method.wrap_method( - self.delete_product, - default_timeout=None, - client_info=client_info, - ), - self.import_products: gapic_v1.method.wrap_method( - self.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.set_inventory: gapic_v1.method.wrap_method( - self.set_inventory, - default_timeout=None, - client_info=client_info, - ), - self.add_fulfillment_places: gapic_v1.method.wrap_method( - self.add_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.remove_fulfillment_places: gapic_v1.method.wrap_method( - self.remove_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.add_local_inventories: gapic_v1.method.wrap_method( - self.add_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.remove_local_inventories: gapic_v1.method.wrap_method( - self.remove_local_inventories, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Union[ - product.Product, - Awaitable[product.Product] - ]]: - raise NotImplementedError() - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Union[ - product_service.ListProductsResponse, - Awaitable[product_service.ListProductsResponse] - ]]: - raise NotImplementedError() - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ProductServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py deleted file mode 100644 index 108f3215..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc.py +++ /dev/null @@ -1,680 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO - - -class ProductServiceGrpcTransport(ProductServiceTransport): - """gRPC backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - gcr_product.Product]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.CreateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - product.Product]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.GetProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - product_service.ListProductsResponse]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - ~.ListProductsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - gcr_product.Product]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - ~.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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2.Product]s. - - Request processing may be synchronous. Non-existing items are - created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2.Product]s to be successfully - updated. - - Returns: - Callable[[~.ImportProductsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - operations_pb2.Operation]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2.Product] while respecting the - last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places, - while respecting the last update timestamps of each inventory - field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places at - a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProductServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py deleted file mode 100644 index 1d4ccc2d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,679 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ProductServiceGrpcTransport - - -class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): - """gRPC AsyncIO backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.CreateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Awaitable[product.Product]]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.GetProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Awaitable[product_service.ListProductsResponse]]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - Awaitable[~.ListProductsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - 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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2.Product]s. - - Request processing may be synchronous. Non-existing items are - created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2.Product]s to be successfully - updated. - - Returns: - Callable[[~.ImportProductsRequest], - 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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2.Product] while respecting the - last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2.ProductService.SetInventory], - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - 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 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - 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 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places, - while respecting the last update timestamps of each inventory - field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - 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 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2.Product] at a list of places at - a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2.Product] queried by - [GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - 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 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py deleted file mode 100644 index 2f63fc22..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SearchServiceClient -from .async_client import SearchServiceAsyncClient - -__all__ = ( - 'SearchServiceClient', - 'SearchServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py deleted file mode 100644 index c48710b8..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/async_client.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.services.search_service import pagers -from google.cloud.retail_v2.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .client import SearchServiceClient - - -class SearchServiceAsyncClient: - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: SearchServiceClient - - DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(SearchServiceClient.branch_path) - parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) - product_path = staticmethod(SearchServiceClient.product_path) - parse_product_path = staticmethod(SearchServiceClient.parse_product_path) - common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(SearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SearchServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAsyncPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_search(): - # Create a client - client = retail_v2.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.services.search_service.pagers.SearchAsyncPager: - Response message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py deleted file mode 100644 index 0072e3b0..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/client.py +++ /dev/null @@ -1,513 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2.services.search_service import pagers -from google.cloud.retail_v2.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SearchServiceGrpcTransport -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -class SearchServiceClientMeta(type): - """Metaclass for the SearchService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] - _transport_registry["grpc"] = SearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SearchServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SearchServiceClient(metaclass=SearchServiceClientMeta): - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SearchServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SearchServiceTransport): - # transport is a SearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_search(): - # Create a client - client = retail_v2.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.services.search_service.pagers.SearchPager: - Response message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a search_service.SearchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, search_service.SearchRequest): - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py deleted file mode 100644 index 524810e2..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2.types import search_service - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., search_service.SearchResponse], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[search_service.SearchResponse]], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py deleted file mode 100644 index 7917cd1d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SearchServiceTransport -from .grpc import SearchServiceGrpcTransport -from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] -_transport_registry['grpc'] = SearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport - -__all__ = ( - 'SearchServiceTransport', - 'SearchServiceGrpcTransport', - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py deleted file mode 100644 index 541055f5..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2.types import search_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class SearchServiceTransport(abc.ABC): - """Abstract transport class for SearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search: gapic_v1.method.wrap_method( - self.search, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Union[ - search_service.SearchResponse, - Awaitable[search_service.SearchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SearchServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py deleted file mode 100644 index ee53c769..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc.py +++ /dev/null @@ -1,270 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO - - -class SearchServiceGrpcTransport(SearchServiceTransport): - """gRPC backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py deleted file mode 100644 index 6c6e5f29..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SearchServiceGrpcTransport - - -class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): - """gRPC AsyncIO backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Awaitable[search_service.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py deleted file mode 100644 index 5f5171c1..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py deleted file mode 100644 index 99002514..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/async_client.py +++ /dev/null @@ -1,730 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on the customer - website. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(UserEventServiceClient.catalog_path) - parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) - product_path = staticmethod(UserEventServiceClient.product_path) - parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_write_user_event(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_collect_user_event(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_purge_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_import_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2 - - async def sample_rejoin_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py deleted file mode 100644 index cd1d35d8..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/client.py +++ /dev/null @@ -1,930 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[UserEventServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on the customer - website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_write_user_event(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_collect_user_event(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_purge_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeUserEventsRequest): - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_import_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportUserEventsRequest): - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2 - - def sample_rejoin_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.RejoinUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.RejoinUserEventsRequest): - request = user_event_service.RejoinUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py deleted file mode 100644 index f53ee5d7..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py deleted file mode 100644 index 661a2d50..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/base.py +++ /dev/null @@ -1,235 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_timeout=None, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_timeout=None, - client_info=client_info, - ), - self.purge_user_events: gapic_v1.method.wrap_method( - self.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.rejoin_user_events: gapic_v1.method.wrap_method( - self.rejoin_user_events, - 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 write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - user_event.UserEvent, - Awaitable[user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py deleted file mode 100644 index af50579d..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index cdc1a2f9..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - 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 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py deleted file mode 100644 index 8e0ea23a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/__init__.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .catalog import ( - Catalog, - ProductLevelConfig, -) -from .catalog_service import ( - GetDefaultBranchRequest, - GetDefaultBranchResponse, - ListCatalogsRequest, - ListCatalogsResponse, - SetDefaultBranchRequest, - UpdateCatalogRequest, -) -from .common import ( - Audience, - ColorInfo, - CustomAttribute, - FulfillmentInfo, - Image, - Interval, - LocalInventory, - PriceInfo, - Rating, - UserInfo, -) -from .completion_service import ( - CompleteQueryRequest, - CompleteQueryResponse, -) -from .import_config import ( - BigQuerySource, - CompletionDataInputConfig, - GcsSource, - ImportCompletionDataRequest, - ImportCompletionDataResponse, - ImportErrorsConfig, - ImportMetadata, - ImportProductsRequest, - ImportProductsResponse, - ImportUserEventsRequest, - ImportUserEventsResponse, - ProductInlineSource, - ProductInputConfig, - UserEventImportSummary, - UserEventInlineSource, - UserEventInputConfig, -) -from .prediction_service import ( - PredictRequest, - PredictResponse, -) -from .product import ( - Product, -) -from .product_service import ( - AddFulfillmentPlacesMetadata, - AddFulfillmentPlacesRequest, - AddFulfillmentPlacesResponse, - AddLocalInventoriesMetadata, - AddLocalInventoriesRequest, - AddLocalInventoriesResponse, - CreateProductRequest, - DeleteProductRequest, - GetProductRequest, - ListProductsRequest, - ListProductsResponse, - RemoveFulfillmentPlacesMetadata, - RemoveFulfillmentPlacesRequest, - RemoveFulfillmentPlacesResponse, - RemoveLocalInventoriesMetadata, - RemoveLocalInventoriesRequest, - RemoveLocalInventoriesResponse, - SetInventoryMetadata, - SetInventoryRequest, - SetInventoryResponse, - UpdateProductRequest, -) -from .promotion import ( - Promotion, -) -from .purge_config import ( - PurgeMetadata, - PurgeUserEventsRequest, - PurgeUserEventsResponse, -) -from .search_service import ( - SearchRequest, - SearchResponse, -) -from .user_event import ( - CompletionDetail, - ProductDetail, - PurchaseTransaction, - UserEvent, -) -from .user_event_service import ( - CollectUserEventRequest, - RejoinUserEventsMetadata, - RejoinUserEventsRequest, - RejoinUserEventsResponse, - WriteUserEventRequest, -) - -__all__ = ( - 'Catalog', - 'ProductLevelConfig', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'SetDefaultBranchRequest', - 'UpdateCatalogRequest', - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py deleted file mode 100644 index 47a372fb..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog.py +++ /dev/null @@ -1,131 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'ProductLevelConfig', - 'Catalog', - }, -) - - -class ProductLevelConfig(proto.Message): - r"""Configures what level the product should be uploaded with - regards to how users will be send events and how predictions - will be made. - - Attributes: - ingestion_product_type (str): - The type of [Product][google.cloud.retail.v2.Product]s - allowed to be ingested into the catalog. Acceptable values - are: - - - ``primary`` (default): You can ingest - [Product][google.cloud.retail.v2.Product]s of all types. - When ingesting a - [Product][google.cloud.retail.v2.Product], its type will - default to - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - if unset. - - ``variant`` (incompatible with Retail Search): You can - only ingest - [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s. This means - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] - cannot be empty. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``variant`` and - [merchant_center_product_id_field][google.cloud.retail.v2.ProductLevelConfig.merchant_center_product_id_field] - is ``itemGroupId``, an INVALID_ARGUMENT error is returned. - - See `Product - levels `__ - for more details. - merchant_center_product_id_field (str): - Which field of `Merchant Center - Product `__ - should be imported as - [Product.id][google.cloud.retail.v2.Product.id]. Acceptable - values are: - - - ``offerId`` (default): Import ``offerId`` as the product - ID. - - ``itemGroupId``: Import ``itemGroupId`` as the product - ID. Notice that Retail API will choose one item from the - ones with the same ``itemGroupId``, and use it to - represent the item group. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``itemGroupId`` and - [ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] - is ``variant``, an INVALID_ARGUMENT error is returned. - - See `Product - levels `__ - for more details. - """ - - ingestion_product_type = proto.Field( - proto.STRING, - number=1, - ) - merchant_center_product_id_field = proto.Field( - proto.STRING, - number=2, - ) - - -class Catalog(proto.Message): - r"""The catalog configuration. - - Attributes: - name (str): - Required. Immutable. The fully qualified - resource name of the catalog. - display_name (str): - Required. Immutable. The catalog display name. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - product_level_config (google.cloud.retail_v2.types.ProductLevelConfig): - Required. The product level configuration. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - product_level_config = proto.Field( - proto.MESSAGE, - number=4, - message='ProductLevelConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py deleted file mode 100644 index 721ef858..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/catalog_service.py +++ /dev/null @@ -1,248 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'UpdateCatalogRequest', - 'SetDefaultBranchRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - }, -) - - -class ListCatalogsRequest(proto.Message): - r"""Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - - Attributes: - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2.Catalog]s under this - location, regardless of whether or not this location exists, - a PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of [Catalog][google.cloud.retail.v2.Catalog]s - to return. If unspecified, defaults to 50. The maximum - allowed value is 1000. Values above 1000 will be coerced to - 1000. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [ListCatalogsResponse.next_page_token][google.cloud.retail.v2.ListCatalogsResponse.next_page_token], - received from a previous - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListCatalogsResponse(proto.Message): - r"""Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs] - method. - - Attributes: - catalogs (Sequence[google.cloud.retail_v2.types.Catalog]): - All the customer's - [Catalog][google.cloud.retail.v2.Catalog]s. - next_page_token (str): - A token that can be sent as - [ListCatalogsRequest.page_token][google.cloud.retail.v2.ListCatalogsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - catalogs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateCatalogRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] - method. - - Attributes: - catalog (google.cloud.retail_v2.types.Catalog): - Required. The [Catalog][google.cloud.retail.v2.Catalog] to - update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2.Catalog], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2.Catalog] 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 - [Catalog][google.cloud.retail.v2.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - catalog = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class SetDefaultBranchRequest(proto.Message): - r"""Request message to set a specified branch as new default_branch. - - Attributes: - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - branch_id (str): - The final component of the resource name of a branch. - - This field must be one of "0", "1" or "2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If there are no sufficient active products in the targeted - branch and - [force][google.cloud.retail.v2.SetDefaultBranchRequest.force] - is not set, a FAILED_PRECONDITION error is returned. - note (str): - Some note on this request, this can be retrieved by - [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch] - before next valid default branch set occurs. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - force (bool): - If set to true, it permits switching to a branch with - [branch_id][google.cloud.retail.v2.SetDefaultBranchRequest.branch_id] - even if it has no sufficient active products. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - force = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetDefaultBranchRequest(proto.Message): - r"""Request message to show which branch is currently the default - branch. - - Attributes: - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - - -class GetDefaultBranchResponse(proto.Message): - r"""Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2.CatalogService.GetDefaultBranch]. - - Attributes: - branch (str): - Full resource name of the branch id currently - set as default branch. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when this branch is set to default. - note (str): - This corresponds to - [SetDefaultBranchRequest.note][google.cloud.retail.v2.SetDefaultBranchRequest.note] - field, when this branch was set as default. - """ - - branch = proto.Field( - proto.STRING, - number=1, - ) - set_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py deleted file mode 100644 index fe50745a..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/common.py +++ /dev/null @@ -1,736 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'LocalInventory', - }, -) - - -class Audience(proto.Message): - r"""An intended audience of the - [Product][google.cloud.retail.v2.Product] for whom it's sold. - - Attributes: - genders (Sequence[str]): - The genders of the audience. Strongly encouraged to use the - standard values: "male", "female", "unisex". - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `gender `__. - Schema.org property - `Product.audience.suggestedGender `__. - age_groups (Sequence[str]): - The age groups of the audience. Strongly encouraged to use - the standard values: "newborn" (up to 3 months old), - "infant" (3–12 months old), "toddler" (1–5 years old), - "kids" (5–13 years old), "adult" (typically teens or older). - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `age_group `__. - Schema.org property - `Product.audience.suggestedMinAge `__ - and - `Product.audience.suggestedMaxAge `__. - """ - - genders = proto.RepeatedField( - proto.STRING, - number=1, - ) - age_groups = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class ColorInfo(proto.Message): - r"""The color information of a - [Product][google.cloud.retail.v2.Product]. - - Attributes: - color_families (Sequence[str]): - The standard color families. Strongly recommended to use the - following standard color groups: "Red", "Pink", "Orange", - "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", - "White", "Gray", "Black" and "Mixed". Normally it is - expected to have only 1 color family. May consider using - single "Mixed" instead of multiple values. - - A maximum of 5 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - colors (Sequence[str]): - The color display names, which may be different from - standard color family names, such as the color aliases used - in the website frontend. Normally it is expected to have - only 1 color. May consider using single "Mixed" instead of - multiple values. - - A maximum of 25 colors are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - """ - - color_families = proto.RepeatedField( - proto.STRING, - number=1, - ) - colors = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class CustomAttribute(proto.Message): - r"""A custom attribute that is not explicitly modeled in - [Product][google.cloud.retail.v2.Product]. - - Attributes: - text (Sequence[str]): - The textual values of this custom attribute. For example, - ``["yellow", "green"]`` when the key is "color". - - Empty string is not allowed. Otherwise, an INVALID_ARGUMENT - error is returned. - - Exactly one of - [text][google.cloud.retail.v2.CustomAttribute.text] or - [numbers][google.cloud.retail.v2.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - numbers (Sequence[float]): - The numerical values of this custom attribute. For example, - ``[2.3, 15.4]`` when the key is "lengths_cm". - - Exactly one of - [text][google.cloud.retail.v2.CustomAttribute.text] or - [numbers][google.cloud.retail.v2.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - searchable (bool): - This field is normally ignored unless - [AttributesConfig.attribute_config_level][] of the - [Catalog][google.cloud.retail.v2.Catalog] is set to the - deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For - information about product-level attribute configuration, see - `Configuration - modes `__. - If true, custom attribute values are searchable by text - queries in - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2.UserEvent]. - - Only set if type - [text][google.cloud.retail.v2.CustomAttribute.text] is set. - Otherwise, a INVALID_ARGUMENT error is returned. - - This field is a member of `oneof`_ ``_searchable``. - indexable (bool): - This field is normally ignored unless - [AttributesConfig.attribute_config_level][] of the - [Catalog][google.cloud.retail.v2.Catalog] is set to the - deprecated 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG' mode. For - information about product-level attribute configuration, see - `Configuration - modes `__. - If true, custom attribute values are indexed, so that they - can be filtered, faceted or boosted in - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2.UserEvent]. - - See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter], - [SearchRequest.facet_specs][google.cloud.retail.v2.SearchRequest.facet_specs] - and - [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] - for more details. - - This field is a member of `oneof`_ ``_indexable``. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - numbers = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - searchable = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - indexable = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - -class FulfillmentInfo(proto.Message): - r"""Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - Attributes: - type_ (str): - The fulfillment type, including commonly used types (such as - pickup in store and same day delivery), and custom types. - Customers have to map custom types to their display names - before rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - place_ids (Sequence[str]): - The IDs for this - [type][google.cloud.retail.v2.FulfillmentInfo.type], such as - the store IDs for - [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2.FulfillmentInfo.type] - or the region IDs for - [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2.FulfillmentInfo.type]. - - A maximum of 3000 values are allowed. Each value must be a - string with a length limit of 30 characters, matching the - pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". - Otherwise, an INVALID_ARGUMENT error is returned. - """ - - type_ = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class Image(proto.Message): - r"""[Product][google.cloud.retail.v2.Product] image. Recommendations AI - and Retail Search do not use product images to improve prediction - and search results. However, product images can be returned in - results, and are shown in prediction or search previews in the - console. - - Attributes: - uri (str): - Required. URI of the image. - - This field must be a valid UTF-8 encoded URI with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - height (int): - Height of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - width (int): - Width of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - height = proto.Field( - proto.INT32, - number=2, - ) - width = proto.Field( - proto.INT32, - number=3, - ) - - -class Interval(proto.Message): - r"""A floating point interval. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - minimum (float): - Inclusive lower bound. - - This field is a member of `oneof`_ ``min``. - exclusive_minimum (float): - Exclusive lower bound. - - This field is a member of `oneof`_ ``min``. - maximum (float): - Inclusive upper bound. - - This field is a member of `oneof`_ ``max``. - exclusive_maximum (float): - Exclusive upper bound. - - This field is a member of `oneof`_ ``max``. - """ - - minimum = proto.Field( - proto.DOUBLE, - number=1, - oneof='min', - ) - exclusive_minimum = proto.Field( - proto.DOUBLE, - number=2, - oneof='min', - ) - maximum = proto.Field( - proto.DOUBLE, - number=3, - oneof='max', - ) - exclusive_maximum = proto.Field( - proto.DOUBLE, - number=4, - oneof='max', - ) - - -class PriceInfo(proto.Message): - r"""The price information of a - [Product][google.cloud.retail.v2.Product]. - - Attributes: - currency_code (str): - The 3-letter currency code defined in `ISO - 4217 `__. - - If this field is an unrecognizable currency code, an - INVALID_ARGUMENT error is returned. - - The - [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s with the same - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] - must share the same - [currency_code][google.cloud.retail.v2.PriceInfo.currency_code]. - Otherwise, a FAILED_PRECONDITION error is returned. - price (float): - Price of the product. - - Google Merchant Center property - `price `__. - Schema.org property - `Offer.price `__. - original_price (float): - Price of the product without any discount. If zero, by - default set to be the - [price][google.cloud.retail.v2.PriceInfo.price]. If set, - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - should be greater than or equal to - [price][google.cloud.retail.v2.PriceInfo.price], otherwise - an INVALID_ARGUMENT error is thrown. - cost (float): - The costs associated with the sale of a particular product. - Used for gross profit reporting. - - - Profit = [price][google.cloud.retail.v2.PriceInfo.price] - - [cost][google.cloud.retail.v2.PriceInfo.cost] - - Google Merchant Center property - `cost_of_goods_sold `__. - price_effective_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2.PriceInfo.price] starts to be - effective. This can be set as a future timestamp, and the - [price][google.cloud.retail.v2.PriceInfo.price] is only used - for search after - [price_effective_time][google.cloud.retail.v2.PriceInfo.price_effective_time]. - If so, the - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - is used before - [price_effective_time][google.cloud.retail.v2.PriceInfo.price_effective_time]. - - Do not set if - [price][google.cloud.retail.v2.PriceInfo.price] is always - effective because it will cause additional latency during - search. - price_expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2.PriceInfo.price] stops to be - effective. The - [price][google.cloud.retail.v2.PriceInfo.price] is used for - search before - [price_expire_time][google.cloud.retail.v2.PriceInfo.price_expire_time]. - If this field is set, the - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2.PriceInfo.original_price] - is used after - [price_expire_time][google.cloud.retail.v2.PriceInfo.price_expire_time]. - - Do not set if - [price][google.cloud.retail.v2.PriceInfo.price] is always - effective because it will cause additional latency during - search. - price_range (google.cloud.retail_v2.types.PriceInfo.PriceRange): - Output only. The price range of all the child - [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s grouped together - on the - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]. Only populated - for - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]. - Do not set this field in API requests. - """ - - class PriceRange(proto.Message): - r"""The price range of all - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. - - Attributes: - price (google.cloud.retail_v2.types.Interval): - The inclusive - [Product.pricing_info.price][google.cloud.retail.v2.PriceInfo.price] - interval of all - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. - original_price (google.cloud.retail_v2.types.Interval): - The inclusive - [Product.pricing_info.original_price][google.cloud.retail.v2.PriceInfo.original_price] - internal of all - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id]. - """ - - price = proto.Field( - proto.MESSAGE, - number=1, - message='Interval', - ) - original_price = proto.Field( - proto.MESSAGE, - number=2, - message='Interval', - ) - - currency_code = proto.Field( - proto.STRING, - number=1, - ) - price = proto.Field( - proto.FLOAT, - number=2, - ) - original_price = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - price_effective_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - price_expire_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - price_range = proto.Field( - proto.MESSAGE, - number=7, - message=PriceRange, - ) - - -class Rating(proto.Message): - r"""The rating of a [Product][google.cloud.retail.v2.Product]. - - Attributes: - rating_count (int): - The total number of ratings. This value is independent of - the value of - [rating_histogram][google.cloud.retail.v2.Rating.rating_histogram]. - - This value must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - average_rating (float): - The average rating of the - [Product][google.cloud.retail.v2.Product]. - - The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT - error is returned. - rating_histogram (Sequence[int]): - List of rating counts per rating value (index = rating - 1). - The list is empty if there is no rating. If the list is - non-empty, its size is always 5. Otherwise, an - INVALID_ARGUMENT error is returned. - - For example, [41, 14, 13, 47, 303]. It means that the - [Product][google.cloud.retail.v2.Product] got 41 ratings - with 1 star, 14 ratings with 2 star, and so on. - """ - - rating_count = proto.Field( - proto.INT32, - number=1, - ) - average_rating = proto.Field( - proto.FLOAT, - number=2, - ) - rating_histogram = proto.RepeatedField( - proto.INT32, - number=3, - ) - - -class UserInfo(proto.Message): - r"""Information of an end user. - - Attributes: - user_id (str): - Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. Don't set for - anonymous users. - - Always use a hashed value for this ID. - - Don't set the field to the same fixed ID for different - users. This mixes the event history of those users together, - which results in degraded model quality. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - ip_address (str): - The end user's IP address. This field is used to extract - location information for personalization. - - This field must be either an IPv4 address (e.g. - "104.133.9.80") or an IPv6 address (e.g. - "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an - INVALID_ARGUMENT error is returned. - - This should not be set when: - - - setting - [SearchRequest.user_info][google.cloud.retail.v2.SearchRequest.user_info]. - - using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request] - is set. - user_agent (str): - User agent as included in the HTTP header. Required for - getting - [SearchResponse.sponsored_results][google.cloud.retail.v2.SearchResponse.sponsored_results]. - - The field must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This should not be set when using the client side event - reporting with GTM or JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request] - is set. - direct_user_request (bool): - True if the request is made directly from the end user, in - which case the - [ip_address][google.cloud.retail.v2.UserInfo.ip_address] and - [user_agent][google.cloud.retail.v2.UserInfo.user_agent] can - be populated from the HTTP request. This flag should be set - only if the API request is made directly from the end user - such as a mobile app (and not if a gateway or a server is - processing and pushing the user events). - - This should not be set when using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent]. - """ - - user_id = proto.Field( - proto.STRING, - number=1, - ) - ip_address = proto.Field( - proto.STRING, - number=2, - ) - user_agent = proto.Field( - proto.STRING, - number=3, - ) - direct_user_request = proto.Field( - proto.BOOL, - number=4, - ) - - -class LocalInventory(proto.Message): - r"""The inventory information at a place (e.g. a store) - identified by a place ID. - - Attributes: - place_id (str): - The place ID for the current set of inventory - information. - price_info (google.cloud.retail_v2.types.PriceInfo): - Product price and cost information. - - Google Merchant Center property - `price `__. - attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): - Additional local inventory attributes, for example, store - name, promotion tags, etc. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - At most 30 attributes are allowed. - - The key must be a UTF-8 encoded string with a length - limit of 32 characters. - - The key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis - or KEY_1_LIKE_THIS. - - The attribute values must be of the same type (text or - number). - - Only 1 value is allowed for each attribute. - - For text values, the length limit is 256 UTF-8 - characters. - - The attribute does not support search. The ``searchable`` - field should be unset or set to false. - - The max summed total bytes of custom attribute keys and - values per product is 5MiB. - fulfillment_types (Sequence[str]): - Input only. Supported fulfillment types. Valid fulfillment - type values include commonly used types (such as pickup in - store and same day delivery), and custom types. Customers - have to map custom types to their display names before - rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - All the elements must be distinct. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - place_id = proto.Field( - proto.STRING, - number=1, - ) - price_info = proto.Field( - proto.MESSAGE, - number=2, - message='PriceInfo', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='CustomAttribute', - ) - fulfillment_types = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py deleted file mode 100644 index 421cc1c0..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/completion_service.py +++ /dev/null @@ -1,229 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'CompleteQueryRequest', - 'CompleteQueryResponse', - }, -) - - -class CompleteQueryRequest(proto.Message): - r"""Auto-complete parameters. - - Attributes: - catalog (str): - Required. Catalog for which the completion is performed. - - Full resource name of catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - query (str): - Required. The query used to generate - suggestions. - The maximum number of allowed characters is 255. - visitor_id (str): - Required field. A unique identifier for tracking visitors. - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - language_codes (Sequence[str]): - The language filters applied to the output suggestions. If - set, it should contain the language of the query. If not - set, suggestions are returned without considering language - restrictions. This is the BCP-47 language code, such as - "en-US" or "sr-Latn". For more information, see `Tags for - Identifying - Languages `__. The - maximum number of language codes is 3. - device_type (str): - The device type context for completion suggestions. It is - useful to apply different suggestions on different device - types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the - suggestions are across all device types. - - Supported formats: - - - ``UNKNOWN_DEVICE_TYPE`` - - - ``DESKTOP`` - - - ``MOBILE`` - - - A customized string starts with ``OTHER_``, e.g. - ``OTHER_IPHONE``. - dataset (str): - Determines which dataset to use for fetching completion. - "user-data" will use the imported dataset through - [CompletionService.ImportCompletionData][google.cloud.retail.v2.CompletionService.ImportCompletionData]. - "cloud-retail" will use the dataset generated by cloud - retail based on user events. If leave empty, it will use the - "user-data". - - Current supported values: - - - user-data - - - cloud-retail: This option requires enabling auto-learning - function first. See - `guidelines `__. - max_suggestions (int): - Completion max suggestions. If left unset or set to 0, then - will fallback to the configured value - [CompletionConfig.max_suggestions][]. - - The maximum allowed max suggestions is 20. If it is set - higher, it will be capped by 20. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - visitor_id = proto.Field( - proto.STRING, - number=7, - ) - language_codes = proto.RepeatedField( - proto.STRING, - number=3, - ) - device_type = proto.Field( - proto.STRING, - number=4, - ) - dataset = proto.Field( - proto.STRING, - number=6, - ) - max_suggestions = proto.Field( - proto.INT32, - number=5, - ) - - -class CompleteQueryResponse(proto.Message): - r"""Response of the auto-complete query. - - Attributes: - completion_results (Sequence[google.cloud.retail_v2.types.CompleteQueryResponse.CompletionResult]): - Results of the matching suggestions. The - result list is ordered and the first result is - top suggestion. - attribution_token (str): - A unique complete token. This should be included in the - [UserEvent.completion_detail][google.cloud.retail.v2.UserEvent.completion_detail] - for search events resulting from this completion, which - enables accurate attribution of complete model performance. - recent_search_results (Sequence[google.cloud.retail_v2.types.CompleteQueryResponse.RecentSearchResult]): - Matched recent searches of this user. The maximum number of - recent searches is 10. This field is a restricted feature. - Contact Retail Search support team if you are interested in - enabling it. - - This feature is only available when - [CompleteQueryRequest.visitor_id][google.cloud.retail.v2.CompleteQueryRequest.visitor_id] - field is set and - [UserEvent][google.cloud.retail.v2.UserEvent] is imported. - The recent searches satisfy the follow rules: - - - They are ordered from latest to oldest. - - - They are matched with - [CompleteQueryRequest.query][google.cloud.retail.v2.CompleteQueryRequest.query] - case insensitively. - - - They are transformed to lower cases. - - - They are UTF-8 safe. - - Recent searches are deduplicated. More recent searches will - be reserved when duplication happens. - """ - - class CompletionResult(proto.Message): - r"""Resource that represents completion results. - - Attributes: - suggestion (str): - The suggestion for the query. - attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): - Custom attributes for the suggestion term. - - - For "user-data", the attributes are additional custom - attributes ingested through BigQuery. - - - For "cloud-retail", the attributes are product attributes - generated by Cloud Retail. This is an experimental - feature. Contact Retail Search support team if you are - interested in enabling it. - """ - - suggestion = proto.Field( - proto.STRING, - number=1, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=common.CustomAttribute, - ) - - class RecentSearchResult(proto.Message): - r"""Recent search of this user. - - Attributes: - recent_search (str): - The recent search query. - """ - - recent_search = proto.Field( - proto.STRING, - number=1, - ) - - completion_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=CompletionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - recent_search_results = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=RecentSearchResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py deleted file mode 100644 index 983e15df..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/import_config.py +++ /dev/null @@ -1,697 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import user_event -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'GcsSource', - 'BigQuerySource', - 'ProductInlineSource', - 'UserEventInlineSource', - 'ImportErrorsConfig', - 'ImportProductsRequest', - 'ImportUserEventsRequest', - 'ImportCompletionDataRequest', - 'ProductInputConfig', - 'UserEventInputConfig', - 'CompletionDataInputConfig', - 'ImportMetadata', - 'ImportProductsResponse', - 'ImportUserEventsResponse', - 'UserEventImportSummary', - 'ImportCompletionDataResponse', - }, -) - - -class GcsSource(proto.Message): - r"""Google Cloud Storage location for input content. - format. - - Attributes: - input_uris (Sequence[str]): - Required. Google Cloud Storage URIs to input files. URI can - be up to 2000 characters long. URIs can match the full - object path (for example, - ``gs://bucket/directory/object.json``) or a pattern matching - one or more files, such as ``gs://bucket/directory/*.json``. - A request can contain at most 100 files, and each file can - be up to 2 GB. See `Importing product - information `__ - for the expected file format and setup instructions. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2.Product] per line. Each - product must have a valid - [Product.id][google.cloud.retail.v2.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2.UserEvent] per line. - - ``user_event_ga360``: Using - https://support.google.com/analytics/answer/3437719. - - Supported values for control imports: - - - 'control' (default): One JSON [Control][] per line. - - Supported values for catalog attribute imports: - - - 'catalog_attribute' (default): One CSV - [CatalogAttribute][] per line. - """ - - input_uris = proto.RepeatedField( - proto.STRING, - number=1, - ) - data_schema = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""BigQuery source import data from. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - partition_date (google.type.date_pb2.Date): - BigQuery time partitioned table's \_PARTITIONDATE in - YYYY-MM-DD format. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - - This field is a member of `oneof`_ ``partition``. - project_id (str): - The project ID (can be project # or ID) that - the BigQuery source is in with a length limit of - 128 characters. If not specified, inherits the - project ID from the parent request. - dataset_id (str): - Required. The BigQuery data set to copy the - data from with a length limit of 1,024 - characters. - table_id (str): - Required. The BigQuery table to copy the data - from with a length limit of 1,024 characters. - gcs_staging_dir (str): - Intermediate Cloud Storage directory used for - the import with a length limit of 2,000 - characters. Can be specified if one wants to - have the BigQuery export to a specific Cloud - Storage directory. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2.Product] per line. Each - product must have a valid - [Product.id][google.cloud.retail.v2.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2.UserEvent] per line. - - ``user_event_ga360``: The schema is available here: - https://support.google.com/analytics/answer/3437719. - - ``user_event_ga4``: This feature is in private preview. - Please contact the support team for importing Google - Analytics 4 events. The schema is available here: - https://support.google.com/analytics/answer/7029846. - - Supported values for auto-completion imports: - - - ``suggestions`` (default): One JSON completion suggestion - per line. - - ``denylist``: One JSON deny suggestion per line. - - ``allowlist``: One JSON allow suggestion per line. - """ - - partition_date = proto.Field( - proto.MESSAGE, - number=6, - oneof='partition', - message=date_pb2.Date, - ) - project_id = proto.Field( - proto.STRING, - number=5, - ) - dataset_id = proto.Field( - proto.STRING, - number=1, - ) - table_id = proto.Field( - proto.STRING, - number=2, - ) - gcs_staging_dir = proto.Field( - proto.STRING, - number=3, - ) - data_schema = proto.Field( - proto.STRING, - number=4, - ) - - -class ProductInlineSource(proto.Message): - r"""The inline source for the input config for ImportProducts - method. - - Attributes: - products (Sequence[google.cloud.retail_v2.types.Product]): - Required. A list of products to update/create. Each product - must have a valid - [Product.id][google.cloud.retail.v2.Product.id]. Recommended - max of 100 items. - """ - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=product.Product, - ) - - -class UserEventInlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (Sequence[google.cloud.retail_v2.types.UserEvent]): - Required. A list of user events to import. - Recommended max of 10k items. - """ - - user_events = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - -class ImportErrorsConfig(proto.Message): - r"""Configuration of destination for Import related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage prefix for import errors. This must be - an empty, existing Cloud Storage directory. Import errors - will be written to sharded files in this directory, one per - line, as a JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportProductsRequest(proto.Message): - r"""Request message for Import methods. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` - - If no updateMask is specified, requires products.create - permission. If updateMask is specified, requires - products.update permission. - request_id (str): - Deprecated. This field has no effect. - input_config (google.cloud.retail_v2.types.ProductInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - imported 'products' to update. If not set, will - by default update all fields. - reconciliation_mode (google.cloud.retail_v2.types.ImportProductsRequest.ReconciliationMode): - The mode of reconciliation between existing products and the - products to be imported. Defaults to - [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. - notification_pubsub_topic (str): - Full Pub/Sub topic name for receiving notification. If this - field is set, when the import is finished, a notification - will be sent to specified Pub/Sub topic. The message data - will be JSON string of a - [Operation][google.longrunning.Operation]. - - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. It has to be within - the same project as - [ImportProductsRequest.parent][google.cloud.retail.v2.ImportProductsRequest.parent]. - Make sure that both - ``cloud-retail-customer-data-access@system.gserviceaccount.com`` - and - ``service-@gcp-sa-retail.iam.gserviceaccount.com`` - have the ``pubsub.topics.publish`` IAM permission on the - topic. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - """ - class ReconciliationMode(proto.Enum): - r"""Indicates how imported products are reconciled with the - existing products created or imported before. - """ - RECONCILIATION_MODE_UNSPECIFIED = 0 - INCREMENTAL = 1 - FULL = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - request_id = proto.Field( - proto.STRING, - number=6, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='ProductInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - reconciliation_mode = proto.Field( - proto.ENUM, - number=5, - enum=ReconciliationMode, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=7, - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog`` - input_config (google.cloud.retail_v2.types.UserEventInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. Cannot be set for inline user - event imports. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='UserEventInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - - -class ImportCompletionDataRequest(proto.Message): - r"""Request message for ImportCompletionData methods. - - Attributes: - parent (str): - Required. The catalog which the suggestions dataset belongs - to. - - Format: - ``projects/1234/locations/global/catalogs/default_catalog``. - input_config (google.cloud.retail_v2.types.CompletionDataInputConfig): - Required. The desired input location of the - data. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='CompletionDataInputConfig', - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=3, - ) - - -class ProductInputConfig(proto.Message): - r"""The input config source for products. - - 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: - product_inline_source (google.cloud.retail_v2.types.ProductInlineSource): - The Inline source for the input content for - products. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2.types.GcsSource): - Google Cloud Storage location for the input - content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - product_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='ProductInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class UserEventInputConfig(proto.Message): - r"""The input config source for user events. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - user_event_inline_source (google.cloud.retail_v2.types.UserEventInlineSource): - Required. The Inline source for the input - content for UserEvents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2.types.GcsSource): - Required. Google Cloud Storage location for - the input content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2.types.BigQuerySource): - Required. BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - user_event_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='UserEventInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class CompletionDataInputConfig(proto.Message): - r"""The input config source for completion data. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - big_query_source (google.cloud.retail_v2.types.BigQuerySource): - Required. BigQuery input source. - Add the IAM permission "BigQuery Data Viewer" - for - cloud-retail-customer-data-access@system.gserviceaccount.com - before using this feature otherwise an error is - thrown. - - This field is a member of `oneof`_ ``source``. - """ - - big_query_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='BigQuerySource', - ) - - -class ImportMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - request_id (str): - Deprecated. This field is never set. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=3, - ) - failure_count = proto.Field( - proto.INT64, - number=4, - ) - request_id = proto.Field( - proto.STRING, - number=5, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=6, - ) - - -class ImportProductsResponse(proto.Message): - r"""Response of the - [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. - If the long running operation is done, then this message is returned - by the google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2.types.ImportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - import_summary (google.cloud.retail_v2.types.UserEventImportSummary): - Aggregated statistics of user event import - status. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - import_summary = proto.Field( - proto.MESSAGE, - number=3, - message='UserEventImportSummary', - ) - - -class UserEventImportSummary(proto.Message): - r"""A summary of import result. The UserEventImportSummary - summarizes the import status for user events. - - Attributes: - joined_events_count (int): - Count of user events imported with complete - existing catalog information. - unjoined_events_count (int): - Count of user events imported, but with - catalog information not found in the imported - catalog. - """ - - joined_events_count = proto.Field( - proto.INT64, - number=1, - ) - unjoined_events_count = proto.Field( - proto.INT64, - number=2, - ) - - -class ImportCompletionDataResponse(proto.Message): - r"""Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2.ImportCompletionDataRequest]. - 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 (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py deleted file mode 100644 index 68e8c74b..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/prediction_service.py +++ /dev/null @@ -1,275 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import user_event as gcr_user_event -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'PredictRequest', - 'PredictResponse', - }, -) - - -class PredictRequest(proto.Message): - r"""Request message for Predict method. - - Attributes: - placement (str): - Required. Full resource name of the format: - {name=projects/*/locations/global/catalogs/default_catalog/placements/*} - The ID of the Recommendations AI placement. Before you can - request predictions from your model, you must create at - least one placement for it. For more information, see - `Managing - placements `__. - - The full list of available placements can be seen at - https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements - user_event (google.cloud.retail_v2.types.UserEvent): - Required. Context about the user, what they are looking at - and what action they took to trigger the predict request. - Note that this user event detail won't be ingested to - userEvent logs. Thus, a separate userEvent write request is - required for event logging. - - Don't set - [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] - or - [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] - to the same fixed ID for different users. If you are trying - to receive non-personalized recommendations (not - recommended; this can negatively impact model performance), - instead set - [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id] - to a random unique ID and leave - [UserInfo.user_id][google.cloud.retail.v2.UserInfo.user_id] - unset. - page_size (int): - Maximum number of results to return per page. - Set this property to the number of prediction - results needed. If zero, the service will choose - a reasonable default. The maximum allowed value - is 100. Values above 100 will be coerced to 100. - page_token (str): - The previous PredictResponse.next_page_token. - filter (str): - Filter for restricting prediction results with a length - limit of 5,000 characters. Accepts values for tags and the - ``filterOutOfStockItems`` flag. - - - Tag expressions. Restricts predictions to products that - match all of the specified tags. Boolean operators ``OR`` - and ``NOT`` are supported if the expression is enclosed - in parentheses, and must be separated from the tag values - by a space. ``-"tagA"`` is also supported and is - equivalent to ``NOT "tagA"``. Tag values must be double - quoted UTF-8 encoded strings with a size limit of 1,000 - characters. - - Note: "Recently viewed" models don't support tag - filtering at the moment. - - - filterOutOfStockItems. Restricts predictions to products - that do not have a stockState value of OUT_OF_STOCK. - - Examples: - - - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT - "promotional") - - filterOutOfStockItems tag=(-"promotional") - - filterOutOfStockItems - - If your filter blocks all prediction results, the API will - return generic (unfiltered) popular products. If you only - want results strictly matching the filters, set - ``strictFiltering`` to True in ``PredictRequest.params`` to - receive empty results instead. Note that the API will never - return items with storageStatus of "EXPIRED" or "DELETED" - regardless of filter choices. - validate_only (bool): - Use validate only mode for this prediction - query. If set to true, a dummy model will be - used that returns arbitrary products. Note that - the validate only mode should only be used for - testing the API, or if the model is not ready. - params (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional domain specific parameters for the predictions. - - Allowed values: - - - ``returnProduct``: Boolean. If set to true, the - associated product object will be returned in the - ``results.metadata`` field in the prediction response. - - ``returnScore``: Boolean. If set to true, the prediction - 'score' corresponding to each returned product will be - set in the ``results.metadata`` field in the prediction - response. The given 'score' indicates the probability of - an product being clicked/purchased given the user's - context and history. - - ``strictFiltering``: Boolean. True by default. If set to - false, the service will return generic (unfiltered) - popular products instead of empty if your filter blocks - all prediction results. - - ``priceRerankLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of - {'no-price-reranking', 'low-price-reranking', - 'medium-price-reranking', 'high-price-reranking'}. This - gives request-level control and adjusts prediction - results based on product price. - - ``diversityLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of {'no-diversity', - 'low-diversity', 'medium-diversity', 'high-diversity', - 'auto-diversity'}. This gives request-level control and - adjusts prediction results based on product category. - labels (Mapping[str, str]): - The labels applied to a resource must meet the following - requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - """ - - placement = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - validate_only = proto.Field( - proto.BOOL, - number=6, - ) - params = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class PredictResponse(proto.Message): - r"""Response message for predict method. - - Attributes: - results (Sequence[google.cloud.retail_v2.types.PredictResponse.PredictionResult]): - A list of recommended products. The order - represents the ranking (from the most relevant - product to the least). - attribution_token (str): - A unique attribution token. This should be included in the - [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting - from this recommendation, which enables accurate attribution - of recommendation model performance. - missing_ids (Sequence[str]): - IDs of products in the request that were - missing from the inventory. - validate_only (bool): - True if the validateOnly property was set in - the request. - """ - - class PredictionResult(proto.Message): - r"""PredictionResult represents the recommendation prediction - results. - - Attributes: - id (str): - ID of the recommended product - metadata (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional product metadata / annotations. - - Possible values: - - - ``product``: JSON representation of the product. Is set - if ``returnProduct`` is set to true in - ``PredictRequest.params``. - - ``score``: Prediction score in double value. Is set if - ``returnScore`` is set to true in - ``PredictRequest.params``. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - metadata = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=PredictionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - missing_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py deleted file mode 100644 index bff41d83..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/product.py +++ /dev/null @@ -1,701 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'Product', - }, -) - - -class Product(proto.Message): - r"""Product captures all metadata information of items to be - recommended or searched. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this product becomes unavailable for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - - If it is set, the [Product][google.cloud.retail.v2.Product] - is not available for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - after - [expire_time][google.cloud.retail.v2.Product.expire_time]. - However, the product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - [expire_time][google.cloud.retail.v2.Product.expire_time] - must be later than - [available_time][google.cloud.retail.v2.Product.available_time] - and - [publish_time][google.cloud.retail.v2.Product.publish_time], - otherwise an INVALID_ARGUMENT error is thrown. - - Corresponding properties: Google Merchant Center property - `expiration_date `__. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Input only. The TTL (time to live) of the product. - - If it is set, it must be a non-negative value, and - [expire_time][google.cloud.retail.v2.Product.expire_time] is - set as current timestamp plus - [ttl][google.cloud.retail.v2.Product.ttl]. The derived - [expire_time][google.cloud.retail.v2.Product.expire_time] is - returned in the output and - [ttl][google.cloud.retail.v2.Product.ttl] is left blank when - retrieving the [Product][google.cloud.retail.v2.Product]. - - If it is set, the product is not available for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - after current timestamp plus - [ttl][google.cloud.retail.v2.Product.ttl]. However, the - product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]. - - This field is a member of `oneof`_ ``expiration``. - name (str): - Immutable. Full resource name of the product, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. - id (str): - Immutable. [Product][google.cloud.retail.v2.Product] - identifier, which is the final component of - [name][google.cloud.retail.v2.Product.name]. For example, - this field is "id_1", if - [name][google.cloud.retail.v2.Product.name] is - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `id `__. - Schema.org property - `Product.sku `__. - type_ (google.cloud.retail_v2.types.Product.Type): - Immutable. The type of the product. Default to - [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2.ProductLevelConfig.ingestion_product_type] - if unset. - primary_product_id (str): - Variant group identifier. Must be an - [id][google.cloud.retail.v2.Product.id], with the same - parent branch with this product. Otherwise, an error is - thrown. - - For - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]s, this field can - only be empty or set to the same value as - [id][google.cloud.retail.v2.Product.id]. - - For VARIANT [Product][google.cloud.retail.v2.Product]s, this - field cannot be empty. A maximum of 2,000 products are - allowed to share the same - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `item_group_id `__. - Schema.org property - `Product.inProductGroupWithID `__. - collection_member_ids (Sequence[str]): - The [id][google.cloud.retail.v2.Product.id] of the - collection members when - [type][google.cloud.retail.v2.Product.type] is - [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]. - - Non-existent product ids are allowed. The - [type][google.cloud.retail.v2.Product.type] of the members - must be either - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - or - [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - otherwise and INVALID_ARGUMENT error is thrown. Should not - set it for other types. A maximum of 1000 values are - allowed. Otherwise, an INVALID_ARGUMENT error is return. - gtin (str): - The Global Trade Item Number (GTIN) of the product. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This field must be a Unigram. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `gtin `__. - Schema.org property - `Product.isbn `__, - `Product.gtin8 `__, - `Product.gtin12 `__, - `Product.gtin13 `__, or - `Product.gtin14 `__. - - If the value is not a valid GTIN, an INVALID_ARGUMENT error - is returned. - categories (Sequence[str]): - Product categories. This field is repeated for supporting - one product belonging to several parallel categories. - Strongly recommended using the full path for better search / - recommendation quality. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - For example, if a shoes product belongs to both ["Shoes & - Accessories" -> "Shoes"] and ["Sports & Fitness" -> - "Athletic Clothing" -> "Shoes"], it could be represented as: - - :: - - "categories": [ - "Shoes & Accessories > Shoes", - "Sports & Fitness > Athletic Clothing > Shoes" - ] - - Must be set for - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] otherwise an - INVALID_ARGUMENT error is returned. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2.Product]. Empty values are - not allowed. Each value must be a UTF-8 encoded string with - a length limit of 5,000 characters. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `google_product_category `__. - Schema.org property [Product.category] - (https://schema.org/category). - title (str): - Required. Product title. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `title `__. - Schema.org property - `Product.name `__. - brands (Sequence[str]): - The brands of the product. - - A maximum of 30 brands are allowed. Each brand must be a - UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `brand `__. - Schema.org property - `Product.brand `__. - description (str): - Product description. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `description `__. - Schema.org property - `Product.description `__. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. - - For product prediction, this field is ignored and the model - automatically detects the text language. The - [Product][google.cloud.retail.v2.Product] can include text - in different languages, but duplicating - [Product][google.cloud.retail.v2.Product]s to provide text - in multiple languages can result in degraded model - performance. - - For product search this field is in use. It defaults to - "en-US" if unset. - attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): - Highly encouraged. Extra product attributes to be included. - For example, for products, this could include the store - name, vendor, style, color, etc. These are very strong - signals for recommendation model, thus we highly recommend - providing the attributes here. - - Features that can take on one of a limited number of - possible values. Two types of features can be set are: - - Textual features. some examples would be the brand/maker of - a product, or country of a customer. Numerical features. - Some examples would be the height/weight of a product, or - age of a customer. - - For example: - ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - Max entries count: 200. - - The key must be a UTF-8 encoded string with a length - limit of 128 characters. - - For indexable attribute, the key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, - ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a - non-empty UTF-8 encoded string with a length limit of 256 - characters. - - For number attributes, at most 400 values are allowed. - tags (Sequence[str]): - Custom tags associated with the product. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2.Product]. This value must - be a UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This tag can be used for filtering recommendation results by - passing the tag as part of the - [PredictRequest.filter][google.cloud.retail.v2.PredictRequest.filter]. - - Corresponding properties: Google Merchant Center property - `custom_label_0–4 `__. - price_info (google.cloud.retail_v2.types.PriceInfo): - Product price and cost information. - - Corresponding properties: Google Merchant Center property - `price `__. - rating (google.cloud.retail_v2.types.Rating): - The rating of this product. - available_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this - [Product][google.cloud.retail.v2.Product] becomes available - for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - availability (google.cloud.retail_v2.types.Product.Availability): - The online availability of the - [Product][google.cloud.retail.v2.Product]. Default to - [Availability.IN_STOCK][google.cloud.retail.v2.Product.Availability.IN_STOCK]. - - Corresponding properties: Google Merchant Center property - `availability `__. - Schema.org property - `Offer.availability `__. - available_quantity (google.protobuf.wrappers_pb2.Int32Value): - The available quantity of the item. - fulfillment_info (Sequence[google.cloud.retail_v2.types.FulfillmentInfo]): - Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - All the elements must have distinct - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type]. - Otherwise, an INVALID_ARGUMENT error is returned. - uri (str): - Canonical URL directly linking to the product detail page. - - It is strongly recommended to provide a valid uri for the - product, otherwise the service performance could be - significantly degraded. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `link `__. - Schema.org property `Offer.url `__. - images (Sequence[google.cloud.retail_v2.types.Image]): - Product images for the product. We highly recommend putting - the main image first. - - A maximum of 300 images are allowed. - - Corresponding properties: Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - audience (google.cloud.retail_v2.types.Audience): - The target group associated with a given - audience (e.g. male, veterans, car owners, - musicians, etc.) of the product. - color_info (google.cloud.retail_v2.types.ColorInfo): - The color of the product. - - Corresponding properties: Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - sizes (Sequence[str]): - The size of the product. To represent different size systems - or size types, consider using this format: - [[[size_system:]size_type:]size_value]. - - For example, in "US:MENS:M", "US" represents size system; - "MENS" represents size type; "M" represents size value. In - "GIRLS:27", size system is empty; "GIRLS" represents size - type; "27" represents size value. In "32 inches", both size - system and size type are empty, while size value is "32 - inches". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2.Product]. Each value must - be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `size `__, - `size_type `__, - and - `size_system `__. - Schema.org property - `Product.size `__. - materials (Sequence[str]): - The material of the product. For example, "leather", - "wooden". - - A maximum of 20 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 200 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `material `__. - Schema.org property - `Product.material `__. - patterns (Sequence[str]): - The pattern or graphic print of the product. For example, - "striped", "polka dot", "paisley". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2.Product]. Each value must - be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `pattern `__. - Schema.org property - `Product.pattern `__. - conditions (Sequence[str]): - The condition of the product. Strongly encouraged to use the - standard values: "new", "refurbished", "used". - - A maximum of 1 value is allowed per - [Product][google.cloud.retail.v2.Product]. Each value must - be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `condition `__. - Schema.org property - `Offer.itemCondition `__. - promotions (Sequence[google.cloud.retail_v2.types.Promotion]): - The promotions applied to the product. A maximum of 10 - values are allowed per - [Product][google.cloud.retail.v2.Product]. Only - [Promotion.promotion_id][google.cloud.retail.v2.Promotion.promotion_id] - will be used, other fields will be ignored if set. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the product is published by the retailer - for the first time, which indicates the freshness of the - products. Note that this field is different from - [available_time][google.cloud.retail.v2.Product.available_time], - given it purely describes product freshness regardless of - when it is available on search and recommendation. - retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the - [Product][google.cloud.retail.v2.Product]s are returned in - [SearchResponse][google.cloud.retail.v2.SearchResponse]. - - Supported fields for all - [type][google.cloud.retail.v2.Product.type]s: - - - [audience][google.cloud.retail.v2.Product.audience] - - [availability][google.cloud.retail.v2.Product.availability] - - [brands][google.cloud.retail.v2.Product.brands] - - [color_info][google.cloud.retail.v2.Product.color_info] - - [conditions][google.cloud.retail.v2.Product.conditions] - - [gtin][google.cloud.retail.v2.Product.gtin] - - [materials][google.cloud.retail.v2.Product.materials] - - [name][google.cloud.retail.v2.Product.name] - - [patterns][google.cloud.retail.v2.Product.patterns] - - [price_info][google.cloud.retail.v2.Product.price_info] - - [rating][google.cloud.retail.v2.Product.rating] - - [sizes][google.cloud.retail.v2.Product.sizes] - - [title][google.cloud.retail.v2.Product.title] - - [uri][google.cloud.retail.v2.Product.uri] - - Supported fields only for - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]: - - - [categories][google.cloud.retail.v2.Product.categories] - - [description][google.cloud.retail.v2.Product.description] - - [images][google.cloud.retail.v2.Product.images] - - Supported fields only for - [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT]: - - - Only the first image in - [images][google.cloud.retail.v2.Product.images] - - To mark - [attributes][google.cloud.retail.v2.Product.attributes] as - retrievable, include paths of the form "attributes.key" - where "key" is the key of a custom attribute, as specified - in [attributes][google.cloud.retail.v2.Product.attributes]. - - For - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION], - the following fields are always returned in - [SearchResponse][google.cloud.retail.v2.SearchResponse] by - default: - - - [name][google.cloud.retail.v2.Product.name] - - For - [Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT], - the following fields are always returned in by default: - - - [name][google.cloud.retail.v2.Product.name] - - [color_info][google.cloud.retail.v2.Product.color_info] - - The maximum number of paths is 30. Otherwise, an - INVALID_ARGUMENT error is returned. - - Note: Returning more fields in - [SearchResponse][google.cloud.retail.v2.SearchResponse] can - increase response payload size and serving latency. - variants (Sequence[google.cloud.retail_v2.types.Product]): - Output only. Product variants grouped together on primary - product which share similar product attributes. It's - automatically grouped by - [primary_product_id][google.cloud.retail.v2.Product.primary_product_id] - for all the product variants. Only populated for - [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]. - Do not set this field in API requests. - """ - class Type(proto.Enum): - r"""The type of this product.""" - TYPE_UNSPECIFIED = 0 - PRIMARY = 1 - VARIANT = 2 - COLLECTION = 3 - - class Availability(proto.Enum): - r"""Product availability. If this field is unspecified, the - product is assumed to be in stock. - """ - AVAILABILITY_UNSPECIFIED = 0 - IN_STOCK = 1 - OUT_OF_STOCK = 2 - PREORDER = 3 - BACKORDER = 4 - - expire_time = proto.Field( - proto.MESSAGE, - number=16, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl = proto.Field( - proto.MESSAGE, - number=17, - oneof='expiration', - message=duration_pb2.Duration, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - type_ = proto.Field( - proto.ENUM, - number=3, - enum=Type, - ) - primary_product_id = proto.Field( - proto.STRING, - number=4, - ) - collection_member_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - gtin = proto.Field( - proto.STRING, - number=6, - ) - categories = proto.RepeatedField( - proto.STRING, - number=7, - ) - title = proto.Field( - proto.STRING, - number=8, - ) - brands = proto.RepeatedField( - proto.STRING, - number=9, - ) - description = proto.Field( - proto.STRING, - number=10, - ) - language_code = proto.Field( - proto.STRING, - number=11, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=12, - message=common.CustomAttribute, - ) - tags = proto.RepeatedField( - proto.STRING, - number=13, - ) - price_info = proto.Field( - proto.MESSAGE, - number=14, - message=common.PriceInfo, - ) - rating = proto.Field( - proto.MESSAGE, - number=15, - message=common.Rating, - ) - available_time = proto.Field( - proto.MESSAGE, - number=18, - message=timestamp_pb2.Timestamp, - ) - availability = proto.Field( - proto.ENUM, - number=19, - enum=Availability, - ) - available_quantity = proto.Field( - proto.MESSAGE, - number=20, - message=wrappers_pb2.Int32Value, - ) - fulfillment_info = proto.RepeatedField( - proto.MESSAGE, - number=21, - message=common.FulfillmentInfo, - ) - uri = proto.Field( - proto.STRING, - number=22, - ) - images = proto.RepeatedField( - proto.MESSAGE, - number=23, - message=common.Image, - ) - audience = proto.Field( - proto.MESSAGE, - number=24, - message=common.Audience, - ) - color_info = proto.Field( - proto.MESSAGE, - number=25, - message=common.ColorInfo, - ) - sizes = proto.RepeatedField( - proto.STRING, - number=26, - ) - materials = proto.RepeatedField( - proto.STRING, - number=27, - ) - patterns = proto.RepeatedField( - proto.STRING, - number=28, - ) - conditions = proto.RepeatedField( - proto.STRING, - number=29, - ) - promotions = proto.RepeatedField( - proto.MESSAGE, - number=34, - message=promotion.Promotion, - ) - publish_time = proto.Field( - proto.MESSAGE, - number=33, - message=timestamp_pb2.Timestamp, - ) - retrievable_fields = proto.Field( - proto.MESSAGE, - number=30, - message=field_mask_pb2.FieldMask, - ) - variants = proto.RepeatedField( - proto.MESSAGE, - number=31, - message='Product', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py deleted file mode 100644 index ce4d5c3e..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/product_service.py +++ /dev/null @@ -1,858 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'CreateProductRequest', - 'GetProductRequest', - 'UpdateProductRequest', - 'DeleteProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'SetInventoryRequest', - 'SetInventoryMetadata', - 'SetInventoryResponse', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesResponse', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesResponse', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesResponse', - }, -) - - -class CreateProductRequest(proto.Message): - r"""Request message for [CreateProduct][] method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - product (google.cloud.retail_v2.types.Product): - Required. The [Product][google.cloud.retail.v2.Product] to - create. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2.Product], which will become - the final component of the - [Product.name][google.cloud.retail.v2.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2.Product]s with the same - [parent][google.cloud.retail.v2.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - product_id = proto.Field( - proto.STRING, - number=3, - ) - - -class GetProductRequest(proto.Message): - r"""Request message for [GetProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested [Product][google.cloud.retail.v2.Product] - does not exist, a NOT_FOUND error is returned. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateProductRequest(proto.Message): - r"""Request message for [UpdateProduct][] method. - - Attributes: - product (google.cloud.retail_v2.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to update - does not exist and - [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Product][google.cloud.retail.v2.Product] to update. The - immutable and output only fields are NOT supported. If not - set, all supported fields (the fields that are neither - immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - The attribute key can be updated by setting the mask path as - "attributes.${key_name}". If a key name is present in the - mask but not in the patching product from the request, this - key will be deleted after the update. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, a - new [Product][google.cloud.retail.v2.Product] will be - created. In this situation, ``update_mask`` is ignored. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteProductRequest(proto.Message): - r"""Request message for [DeleteProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2.Product] to delete - does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2.Product] to delete can - neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] with more than one - [variants][google.cloud.retail.v2.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2.Product] will be deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProductsRequest(proto.Message): - r"""Request message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - - Attributes: - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list products - under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2.Product]s under this - branch, regardless of whether or not this branch exists, a - PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of [Product][google.cloud.retail.v2.Product]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 - [ListProductsResponse.next_page_token][google.cloud.retail.v2.ListProductsResponse.next_page_token], - received from a previous - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - filter (str): - A filter to apply on the list results. Supported features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2.ListProductsRequest.filter] - is unset. - - List - [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s sharing the - same - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product]. For example: - ``primary_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2.Product]s bundled - in a - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product]. For example: - ``collection_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2.Product]s with a - partibular type. For example: ``type = "PRIMARY"`` - ``type = "VARIANT"`` ``type = "COLLECTION"`` - - If the field is unrecognizable, an INVALID_ARGUMENT error is - returned. - - If the specified - [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2.Product] or - [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2.Product] does not exist, a - NOT_FOUND error is returned. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields of [Product][google.cloud.retail.v2.Product] to - return in the responses. If not set or empty, the following - fields are returned: - - - [Product.name][google.cloud.retail.v2.Product.name] - - [Product.id][google.cloud.retail.v2.Product.id] - - [Product.title][google.cloud.retail.v2.Product.title] - - [Product.uri][google.cloud.retail.v2.Product.uri] - - [Product.images][google.cloud.retail.v2.Product.images] - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.brands][google.cloud.retail.v2.Product.brands] - - If "*" is provided, all fields are returned. - [Product.name][google.cloud.retail.v2.Product.name] is - always returned no matter what mask is set. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class ListProductsResponse(proto.Message): - r"""Response message for - [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts] - method. - - Attributes: - products (Sequence[google.cloud.retail_v2.types.Product]): - The [Product][google.cloud.retail.v2.Product]s. - next_page_token (str): - A token that can be sent as - [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class SetInventoryRequest(proto.Message): - r"""Request message for [SetInventory][] method. - - Attributes: - inventory (google.cloud.retail_v2.types.Product): - Required. The inventory information to update. The allowable - fields to update are: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2.Product] named in - [Product.name][google.cloud.retail.v2.Product.name], - regardless of whether or not it exists, a PERMISSION_DENIED - error is returned. - - If the [Product][google.cloud.retail.v2.Product] to update - does not have existing inventory information, the provided - inventory information will be inserted. - - If the [Product][google.cloud.retail.v2.Product] to update - has existing inventory information, the provided inventory - information will be merged while respecting the last update - time for each inventory field, using the provided or default - value for - [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of fulfillment - types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear in - [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types have - empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following inventory - fields: - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - [Product.availability][google.cloud.retail.v2.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info] - - If a full overwrite of inventory information while ignoring - timestamps is needed, [UpdateProduct][] should be invoked - instead. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the request is issued, used to - prevent out-of-order updates on inventory fields - with the last update time recorded. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] with name - [Product.name][google.cloud.retail.v2.Product.name] is not - found, the inventory update will still be processed and - retained for at most 1 day until the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - inventory = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - set_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - set_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=4, - ) - - -class SetInventoryMetadata(proto.Message): - r"""Metadata related to the progress of the SetInventory operation. - Currently empty because there is no meaningful metadata populated - from the [SetInventory][] method. - - """ - - -class SetInventoryResponse(proto.Message): - r"""Response of the SetInventoryRequest. Currently empty because there - is no meaningful response populated from the [SetInventory][] - method. - - """ - - -class AddFulfillmentPlacesRequest(proto.Message): - r"""Request message for - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery" to be added for this - [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type]. - Duplicate IDs will be automatically ignored. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If the total number of place IDs exceeds 2000 for this - [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type] - after adding, then the update will be rejected. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, the - fulfillment information will still be processed and retained - for at most 1 day and processed once the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - add_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class AddFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the AddFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - """ - - -class AddFulfillmentPlacesResponse(proto.Message): - r"""Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces] - method. - - """ - - -class AddLocalInventoriesRequest(proto.Message): - r"""Request message for - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - local_inventories (Sequence[google.cloud.retail_v2.types.LocalInventory]): - Required. A list of inventory information at - difference places. Each place is identified by - its place ID. At most 3000 inventories are - allowed per request. - add_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided list of - [LocalInventory][google.cloud.retail.v2.LocalInventory] to - update. The field is updated to the provided value. - - If a field is set while the place does not have a previous - local inventory, the local inventory at that store is - created. - - If a field is set while the value of that field is not - provided, the original field value, if it exists, is - deleted. - - If the mask is not set or set with empty paths, all - inventory fields will be updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory updates are - issued. Used to prevent out-of-order updates on - local inventory fields. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, the - local inventory will still be processed and retained for at - most 1 day and processed once the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - local_inventories = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.LocalInventory, - ) - add_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - add_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=6, - ) - - -class AddLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the AddLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - """ - - -class AddLocalInventoriesResponse(proto.Message): - r"""Response of the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - API. Currently empty because there is no meaningful response - populated from the - [ProductService.AddLocalInventories][google.cloud.retail.v2.ProductService.AddLocalInventories] - method. - - """ - - -class RemoveLocalInventoriesRequest(proto.Message): - r"""Request message for [RemoveLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - place_ids (Sequence[str]): - Required. A list of place IDs to have their - inventory deleted. At most 3000 place IDs are - allowed per request. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory deletions are - issued. Used to prevent out-of-order updates and - deletions on local inventory fields. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, the - local inventory removal request will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class RemoveLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesResponse(proto.Message): - r"""Response of the [RemoveLocalInventories][] API. Currently empty - because there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - - -class RemoveFulfillmentPlacesRequest(proto.Message): - r"""Request message for [RemoveFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][google.cloud.retail.v2.FulfillmentInfo.type]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery", to be removed for this - [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type]. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2.Product] is not found, the - fulfillment information will still be processed and retained - for at most 1 day and processed once the - [Product][google.cloud.retail.v2.Product] is created. If set - to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class RemoveFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveFulfillmentPlaces][] method. - - """ - - -class RemoveFulfillmentPlacesResponse(proto.Message): - r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty - because there is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py deleted file mode 100644 index e8d80a4e..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/promotion.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'Promotion', - }, -) - - -class Promotion(proto.Message): - r"""Promotion information. - - Attributes: - promotion_id (str): - ID of the promotion. For example, "free gift". - - The value must be a UTF-8 encoded string with a length limit - of 128 characters, and match the pattern: - ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or - ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is - returned. - - Google Merchant Center property - `promotion `__. - """ - - promotion_id = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py deleted file mode 100644 index b8159aa6..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/purge_config.py +++ /dev/null @@ -1,107 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - }, -) - - -class PurgeMetadata(proto.Message): - r"""Metadata related to the progress of the Purge operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - """ - - -class PurgeUserEventsRequest(proto.Message): - r"""Request message for PurgeUserEvents method. - - Attributes: - parent (str): - Required. The resource name of the catalog under which the - events are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}`` - filter (str): - Required. The filter string to specify the events to be - deleted with a length limit of 5,000 characters. Empty - string filter is not allowed. The eligible fields for - filtering are: - - - ``eventType``: Double quoted - [UserEvent.event_type][google.cloud.retail.v2.UserEvent.event_type] - string. - - ``eventTime``: in ISO 8601 "zulu" format. - - ``visitorId``: Double quoted string. Specifying this will - delete all events associated with a visitor. - - ``userId``: Double quoted string. Specifying this will - delete all events associated with a user. - - Examples: - - - Deleting all events in a time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - - Deleting specific eventType in time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` - - Deleting all events for a specific visitor: - ``visitorId = "visitor1024"`` - - The filtering fields are assumed to have an implicit AND. - force (bool): - Actually perform the purge. If ``force`` is set to false, - the method will return the expected purge count without - deleting any user events. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeUserEventsResponse(proto.Message): - r"""Response of the PurgeUserEventsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purged_events_count (int): - The total count of events purged as a result - of the operation. - """ - - purged_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py deleted file mode 100644 index e6274278..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/search_service.py +++ /dev/null @@ -1,1150 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'SearchRequest', - 'SearchResponse', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - - Attributes: - placement (str): - Required. The resource name of the search engine placement, - such as - ``projects/*/locations/global/catalogs/default_catalog/placements/default_search``. - This field is used to identify the serving configuration - name and the set of models that will be used to make the - search. - branch (str): - The branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - - Use "default_branch" as the branch ID or leave this field - empty, to search products under the default branch. - query (str): - Raw search query. - - If this field is empty, the request is considered a category - browsing request and returned results are based on - [filter][google.cloud.retail.v2.SearchRequest.filter] and - [page_categories][google.cloud.retail.v2.SearchRequest.page_categories]. - visitor_id (str): - Required. A unique identifier for tracking visitors. For - example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - This should be the same identifier as - [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id]. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2.types.UserInfo): - User information. - page_size (int): - Maximum number of [Product][google.cloud.retail.v2.Product]s - to return. If unspecified, defaults to a reasonable value. - The maximum allowed value is 120. Values above 120 will be - coerced to 120. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [SearchResponse.next_page_token][google.cloud.retail.v2.SearchResponse.next_page_token], - received from a previous - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - offset (int): - A 0-indexed integer that specifies the current offset (that - is, starting result location, amongst the - [Product][google.cloud.retail.v2.Product]s deemed by the API - as relevant) in search results. This field is only - considered if - [page_token][google.cloud.retail.v2.SearchRequest.page_token] - is unset. - - If this field is negative, an INVALID_ARGUMENT is returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. Filter expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - canonical_filter (str): - The default filter that is applied when a user performs a - search without checking any filters on the search page. - - The filter applied to every search request when quality - improvement such as query expansion is needed. For example, - if a query does not have enough results, an expanded query - with - [SearchRequest.canonical_filter][google.cloud.retail.v2.SearchRequest.canonical_filter] - will be returned as a supplement of the original query. This - field is strongly recommended to achieve high search - quality. - - See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] - for more details about filter syntax. - order_by (str): - The order in which products are returned. Products can be - ordered by a field in an - [Product][google.cloud.retail.v2.Product] object. Leave it - unset if ordered by relevance. OrderBy expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - facet_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.FacetSpec]): - Facet specifications for faceted search. If empty, no facets - are returned. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - dynamic_facet_spec (google.cloud.retail_v2.types.SearchRequest.DynamicFacetSpec): - Deprecated. Refer to - https://cloud.google.com/retail/docs/configs#dynamic - to enable dynamic facets. Do not set this field. - The specification for dynamically generated - facets. Notice that only textual facets can be - dynamically generated. - boost_spec (google.cloud.retail_v2.types.SearchRequest.BoostSpec): - Boost specification to boost certain products. See more - details at this `user - guide `__. - - Notice that if both [ServingConfig.boost_control_ids][] and - [SearchRequest.boost_spec][google.cloud.retail.v2.SearchRequest.boost_spec] - are set, the boost conditions from both places are - evaluated. If a search request matches multiple boost - conditions, the final boost score is equal to the sum of the - boost scores from all matched boost conditions. - query_expansion_spec (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec): - The query expansion specification that specifies the - conditions under which query expansion will occur. See more - details at this `user - guide `__. - variant_rollup_keys (Sequence[str]): - The keys to fetch and rollup the matching - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s attributes, - [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo] or - [LocalInventory][google.cloud.retail.v2.LocalInventory]s - attributes. The attributes from all the matching - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s or - [LocalInventory][google.cloud.retail.v2.LocalInventory]s are - merged and de-duplicated. Notice that rollup attributes will - lead to extra query latency. Maximum number of keys is 30. - - For - [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], a - fulfillment type and a fulfillment ID must be provided in - the format of "fulfillmentType.fulfillmentId". E.g., in - "pickupInStore.store123", "pickupInStore" is fulfillment - type and "store123" is the store ID. - - Supported keys are: - - - colorFamilies - - price - - originalPrice - - discount - - variantId - - inventory(place_id,price) - - inventory(place_id,original_price) - - inventory(place_id,attributes.key), where key is any key - in the - [Product.local_inventories.attributes][google.cloud.retail.v2.LocalInventory.attributes] - map. - - attributes.key, where key is any key in the - [Product.attributes][google.cloud.retail.v2.Product.attributes] - map. - - pickupInStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "pickup-in-store". - - shipToStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "ship-to-store". - - sameDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "same-day-delivery". - - nextDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "next-day-delivery". - - customFulfillment1.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-1". - - customFulfillment2.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-2". - - customFulfillment3.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-3". - - customFulfillment4.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-4". - - customFulfillment5.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - "custom-type-5". - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. Required for - category navigation queries to achieve good search quality. - The format should be the same as - [UserEvent.page_categories][google.cloud.retail.v2.UserEvent.page_categories]; - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - search_mode (google.cloud.retail_v2.types.SearchRequest.SearchMode): - The search mode of the search request. If not - specified, a single search request triggers both - product search and faceted search. - personalization_spec (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec): - The specification for personalization. - labels (Mapping[str, str]): - The labels applied to a resource must meet the following - requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - spell_correction_spec (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec): - The spell correction specification that - specifies the mode under which spell correction - will take effect. - - This field is a member of `oneof`_ ``_spell_correction_spec``. - """ - class SearchMode(proto.Enum): - r"""The search mode of each search request.""" - SEARCH_MODE_UNSPECIFIED = 0 - PRODUCT_SEARCH_ONLY = 1 - FACETED_SEARCH_ONLY = 2 - - class FacetSpec(proto.Message): - r"""A facet specification to perform faceted search. - - Attributes: - facet_key (google.cloud.retail_v2.types.SearchRequest.FacetSpec.FacetKey): - Required. The facet key specification. - limit (int): - Maximum of facet values that should be returned for this - facet. If unspecified, defaults to 20. The maximum allowed - value is 300. Values above 300 will be coerced to 300. - - If this field is negative, an INVALID_ARGUMENT is returned. - excluded_filter_keys (Sequence[str]): - List of keys to exclude when faceting. - - By default, - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - is not excluded from the filter unless it is listed in this - field. - - Listing a facet key in this field allows its values to - appear as facet results, even when they are filtered out of - search results. Using this field does not affect what search - results are returned. - - For example, suppose there are 100 products with the color - facet "Red" and 200 products with the color facet "Blue". A - query containing the filter "colorFamilies:ANY("Red")" and - having "colorFamilies" as - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - would by default return only "Red" products in the search - results, and also return "Red" with count 100 as the only - color facet. Although there are also blue products - available, "Blue" would not be shown as an available facet - value. - - If "colorFamilies" is listed in "excludedFilterKeys", then - the query returns the facet values "Red" with count 100 and - "Blue" with count 200, because the "colorFamilies" key is - now excluded from the filter. Because this field doesn't - affect search results, the search results are still - correctly filtered to return only "Red" products. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - enable_dynamic_position (bool): - Enables dynamic position for this facet. If set to true, the - position of this facet among all facets in the response is - determined by Google Retail Search. It will be ordered - together with dynamic facets if dynamic facets is enabled. - If set to false, the position of this facet in the response - will be the same as in the request, and it will be ranked - before the facets with dynamic position enable and all - dynamic facets. - - For example, you may always want to have rating facet - returned in the response, but it's not necessarily to always - display the rating facet at the top. In that case, you can - set enable_dynamic_position to true so that the position of - rating facet in response will be determined by Google Retail - Search. - - Another example, assuming you have the following facets in - the request: - - - "rating", enable_dynamic_position = true - - - "price", enable_dynamic_position = false - - - "brands", enable_dynamic_position = false - - And also you have a dynamic facets enable, which will - generate a facet 'gender'. Then the final order of the - facets in the response can be ("price", "brands", "rating", - "gender") or ("price", "brands", "gender", "rating") depends - on how Google Retail Search orders "gender" and "rating" - facets. However, notice that "price" and "brands" will - always be ranked at 1st and 2nd position since their - enable_dynamic_position are false. - """ - - class FacetKey(proto.Message): - r"""Specifies how a facet is computed. - - Attributes: - key (str): - Required. Supported textual and numerical facet keys in - [Product][google.cloud.retail.v2.Product] object, over which - the facet values are computed. Facet key is case-sensitive. - - Allowed facet keys when - [FacetKey.query][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.query] - is not specified: - - - textual_field = - - - "brands" - - "categories" - - "genders" - - "ageGroups" - - "availability" - - "colorFamilies" - - "colors" - - "sizes" - - "materials" - - "patterns" - - "conditions" - - "attributes.key" - - "pickupInStore" - - "shipToStore" - - "sameDayDelivery" - - "nextDayDelivery" - - "customFulfillment1" - - "customFulfillment2" - - "customFulfillment3" - - "customFulfillment4" - - "customFulfillment5" - - "inventory(place_id,attributes.key)" - - - numerical_field = - - - "price" - - "discount" - - "rating" - - "ratingCount" - - "attributes.key" - - "inventory(place_id,price)" - - "inventory(place_id,original_price)" - - "inventory(place_id,attributes.key)". - intervals (Sequence[google.cloud.retail_v2.types.Interval]): - Set only if values should be bucketized into - intervals. Must be set for facets with numerical - values. Must not be set for facet with text - values. Maximum number of intervals is 30. - restricted_values (Sequence[str]): - Only get facet for the given restricted values. For example, - when using "pickupInStore" as key and set restricted values - to ["store123", "store456"], only facets for "store123" and - "store456" are returned. Only supported on predefined - textual fields, custom textual attributes and fulfillments. - Maximum is 20. - - Must be set for the fulfillment facet keys: - - - pickupInStore - - - shipToStore - - - sameDayDelivery - - - nextDayDelivery - - - customFulfillment1 - - - customFulfillment2 - - - customFulfillment3 - - - customFulfillment4 - - - customFulfillment5 - prefixes (Sequence[str]): - Only get facet values that start with the - given string prefix. For example, suppose - "categories" has three values "Women > Shoe", - "Women > Dress" and "Men > Shoe". If set - "prefixes" to "Women", the "categories" facet - will give only "Women > Shoe" and "Women > - Dress". Only supported on textual fields. - Maximum is 10. - contains (Sequence[str]): - Only get facet values that contains the given - strings. For example, suppose "categories" has - three values "Women > Shoe", "Women > Dress" and - "Men > Shoe". If set "contains" to "Shoe", the - "categories" facet will give only "Women > Shoe" - and "Men > Shoe". Only supported on textual - fields. Maximum is 10. - order_by (str): - The order in which [Facet.values][] are returned. - - Allowed values are: - - - "count desc", which means order by - [Facet.FacetValue.count][] descending. - - - "value desc", which means order by - [Facet.FacetValue.value][] descending. Only applies to - textual facets. - - If not set, textual values are sorted in `natural - order `__; - numerical intervals are sorted in the order given by - [FacetSpec.FacetKey.intervals][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.intervals]; - [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] - are sorted in the order given by - [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.restricted_values]. - query (str): - The query that is used to compute facet for the given facet - key. When provided, it will override the default behavior of - facet computation. The query syntax is the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] - for detail syntax and limitations. Notice that there is no - limitation on - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - when query is specified. - - In the response, [FacetValue.value][] will be always "1" and - [FacetValue.count][] will be the number of results that - matches the query. - - For example, you can set a customized facet for - "shipToStore", where - [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] - is "customizedShipToStore", and - [FacetKey.query][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.query] - is "availability: ANY("IN_STOCK") AND shipToStore: - ANY("123")". Then the facet will count the products that are - both in stock and ship to store "123". - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - intervals = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Interval, - ) - restricted_values = proto.RepeatedField( - proto.STRING, - number=3, - ) - prefixes = proto.RepeatedField( - proto.STRING, - number=8, - ) - contains = proto.RepeatedField( - proto.STRING, - number=9, - ) - order_by = proto.Field( - proto.STRING, - number=4, - ) - query = proto.Field( - proto.STRING, - number=5, - ) - - facet_key = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.FacetSpec.FacetKey', - ) - limit = proto.Field( - proto.INT32, - number=2, - ) - excluded_filter_keys = proto.RepeatedField( - proto.STRING, - number=3, - ) - enable_dynamic_position = proto.Field( - proto.BOOL, - number=4, - ) - - class DynamicFacetSpec(proto.Message): - r"""The specifications of dynamically generated facets. - - Attributes: - mode (google.cloud.retail_v2.types.SearchRequest.DynamicFacetSpec.Mode): - Mode of the DynamicFacet feature. Defaults to - [Mode.DISABLED][google.cloud.retail.v2.SearchRequest.DynamicFacetSpec.Mode.DISABLED] - if it's unset. - """ - class Mode(proto.Enum): - r"""Enum to control DynamicFacet mode""" - MODE_UNSPECIFIED = 0 - DISABLED = 1 - ENABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.DynamicFacetSpec.Mode', - ) - - class BoostSpec(proto.Message): - r"""Boost specification to boost certain items. - - Attributes: - condition_boost_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - Condition boost specifications. If a product - matches multiple conditions in the - specifictions, boost scores from these - specifications are all applied and combined in a - non-linear way. Maximum number of specifications - is 20. - skip_boost_spec_validation (bool): - Whether to skip boostspec validation. If this field is set - to true, invalid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] - will be ignored and valid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] - will still be applied. - - This field is a member of `oneof`_ ``_skip_boost_spec_validation``. - """ - - class ConditionBoostSpec(proto.Message): - r"""Boost applies to products which match a condition. - - Attributes: - condition (str): - An expression which specifies a boost condition. The syntax - and supported fields are the same as a filter expression. - See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": - - - (id: ANY("product_1", "product_2")) AND - (colorFamilies: ANY("Red","Blue")) - boost (float): - Strength of the condition boost, which should be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - """ - - condition = proto.Field( - proto.STRING, - number=1, - ) - boost = proto.Field( - proto.FLOAT, - number=2, - ) - - condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - skip_boost_spec_validation = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - - class QueryExpansionSpec(proto.Message): - r"""Specification to determine under which conditions query - expansion should occur. - - Attributes: - condition (google.cloud.retail_v2.types.SearchRequest.QueryExpansionSpec.Condition): - The condition under which query expansion should occur. - Default to - [Condition.DISABLED][google.cloud.retail.v2.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - pin_unexpanded_results (bool): - Whether to pin unexpanded results. If this - field is set to true, unexpanded products are - always at the top of the search results, - followed by the expanded results. - """ - class Condition(proto.Enum): - r"""Enum describing under which condition query expansion should - occur. - """ - CONDITION_UNSPECIFIED = 0 - DISABLED = 1 - AUTO = 3 - - condition = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.QueryExpansionSpec.Condition', - ) - pin_unexpanded_results = proto.Field( - proto.BOOL, - number=2, - ) - - class PersonalizationSpec(proto.Message): - r"""The specification for personalization. - - Attributes: - mode (google.cloud.retail_v2.types.SearchRequest.PersonalizationSpec.Mode): - Defaults to - [Mode.AUTO][google.cloud.retail.v2.SearchRequest.PersonalizationSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""The personalization mode of each search request.""" - MODE_UNSPECIFIED = 0 - AUTO = 1 - DISABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.PersonalizationSpec.Mode', - ) - - class SpellCorrectionSpec(proto.Message): - r"""The specification for query spell correction. - - Attributes: - mode (google.cloud.retail_v2.types.SearchRequest.SpellCorrectionSpec.Mode): - The mode under which spell correction should take effect to - replace the original search query. Default to - [Mode.AUTO][google.cloud.retail.v2.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""Enum describing under which mode spell correction should - occur. - """ - MODE_UNSPECIFIED = 0 - SUGGESTION_ONLY = 1 - AUTO = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.SpellCorrectionSpec.Mode', - ) - - placement = proto.Field( - proto.STRING, - number=1, - ) - branch = proto.Field( - proto.STRING, - number=2, - ) - query = proto.Field( - proto.STRING, - number=3, - ) - visitor_id = proto.Field( - proto.STRING, - number=4, - ) - user_info = proto.Field( - proto.MESSAGE, - number=5, - message=common.UserInfo, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - offset = proto.Field( - proto.INT32, - number=9, - ) - filter = proto.Field( - proto.STRING, - number=10, - ) - canonical_filter = proto.Field( - proto.STRING, - number=28, - ) - order_by = proto.Field( - proto.STRING, - number=11, - ) - facet_specs = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=FacetSpec, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=21, - message=DynamicFacetSpec, - ) - boost_spec = proto.Field( - proto.MESSAGE, - number=13, - message=BoostSpec, - ) - query_expansion_spec = proto.Field( - proto.MESSAGE, - number=14, - message=QueryExpansionSpec, - ) - variant_rollup_keys = proto.RepeatedField( - proto.STRING, - number=17, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=23, - ) - search_mode = proto.Field( - proto.ENUM, - number=31, - enum=SearchMode, - ) - personalization_spec = proto.Field( - proto.MESSAGE, - number=32, - message=PersonalizationSpec, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=34, - ) - spell_correction_spec = proto.Field( - proto.MESSAGE, - number=35, - optional=True, - message=SpellCorrectionSpec, - ) - - -class SearchResponse(proto.Message): - r"""Response message for - [SearchService.Search][google.cloud.retail.v2.SearchService.Search] - method. - - Attributes: - results (Sequence[google.cloud.retail_v2.types.SearchResponse.SearchResult]): - A list of matched items. The order represents - the ranking. - facets (Sequence[google.cloud.retail_v2.types.SearchResponse.Facet]): - Results of facets requested by user. - total_size (int): - The estimated total count of matched items irrespective of - pagination. The count of - [results][google.cloud.retail.v2.SearchResponse.results] - returned by pagination may be less than the - [total_size][google.cloud.retail.v2.SearchResponse.total_size] - that matches. - corrected_query (str): - Contains the spell corrected query, if found. If the spell - correction type is AUTOMATIC, then the search results are - based on corrected_query. Otherwise the original query will - be used for search. - attribution_token (str): - A unique search token. This should be included in the - [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting - from this search, which enables accurate attribution of - search model performance. - next_page_token (str): - A token that can be sent as - [SearchRequest.page_token][google.cloud.retail.v2.SearchRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - query_expansion_info (google.cloud.retail_v2.types.SearchResponse.QueryExpansionInfo): - Query expansion information for the returned - results. - redirect_uri (str): - The URI of a customer-defined redirect page. If redirect - action is triggered, no search is performed, and only - [redirect_uri][google.cloud.retail.v2.SearchResponse.redirect_uri] - and - [attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] - are set in the response. - applied_controls (Sequence[str]): - The fully qualified resource name of applied - `controls `__. - invalid_condition_boost_specs (Sequence[google.cloud.retail_v2.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - The invalid - [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2.SearchRequest.BoostSpec.condition_boost_specs] - that are not applied during serving. - """ - - class SearchResult(proto.Message): - r"""Represents the search results. - - Attributes: - id (str): - [Product.id][google.cloud.retail.v2.Product.id] of the - searched [Product][google.cloud.retail.v2.Product]. - product (google.cloud.retail_v2.types.Product): - The product data snippet in the search response. Only - [Product.name][google.cloud.retail.v2.Product.name] is - guaranteed to be populated. - - [Product.variants][google.cloud.retail.v2.Product.variants] - contains the product variants that match the search query. - If there are multiple product variants matching the query, - top 5 most relevant product variants are returned and - ordered by relevancy. - - If relevancy can be deternmined, use - [matching_variant_fields][google.cloud.retail.v2.SearchResponse.SearchResult.matching_variant_fields] - to look up matched product variants fields. If relevancy - cannot be determined, e.g. when searching "shoe" all - products in a shoe product can be a match, 5 product - variants are returned but order is meaningless. - matching_variant_count (int): - The count of matched - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product]s. - matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): - If a [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] matches the search - query, this map indicates which - [Product][google.cloud.retail.v2.Product] fields are - matched. The key is the - [Product.name][google.cloud.retail.v2.Product.name], the - value is a field mask of the matched - [Product][google.cloud.retail.v2.Product] fields. If matched - attributes cannot be determined, this map will be empty. - - For example, a key "sku1" with field mask - "products.color_info" indicates there is a match between - "sku1" [ColorInfo][google.cloud.retail.v2.ColorInfo] and the - query. - variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): - The rollup matching - [variant][google.cloud.retail.v2.Product.Type.VARIANT] - [Product][google.cloud.retail.v2.Product] attributes. The - key is one of the - [SearchRequest.variant_rollup_keys][google.cloud.retail.v2.SearchRequest.variant_rollup_keys]. - The values are the merged and de-duplicated - [Product][google.cloud.retail.v2.Product] attributes. Notice - that the rollup values are respect filter. For example, when - filtering by "colorFamilies:ANY("red")" and rollup - "colorFamilies", only "red" is returned. - - For textual and numerical attributes, the rollup values is a - list of string or double values with type - [google.protobuf.ListValue][google.protobuf.ListValue]. For - example, if there are two variants with colors "red" and - "blue", the rollup values are - - :: - - { key: "colorFamilies" - value { - list_value { - values { string_value: "red" } - values { string_value: "blue" } - } - } - } - - For - [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], - the rollup values is a double value with type - [google.protobuf.Value][google.protobuf.Value]. For example, - ``{key: "pickupInStore.store1" value { number_value: 10 }}`` - means a there are 10 variants in this product are available - in the store "store1". - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - matching_variant_count = proto.Field( - proto.INT32, - number=3, - ) - matching_variant_fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - variant_rollup_values = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - - class Facet(proto.Message): - r"""A facet result. - - Attributes: - key (str): - The key for this facet. E.g., "colorFamilies" - or "price" or "attributes.attr1". - values (Sequence[google.cloud.retail_v2.types.SearchResponse.Facet.FacetValue]): - The facet values for this field. - dynamic_facet (bool): - Whether the facet is dynamically generated. - """ - - class FacetValue(proto.Message): - r"""A facet value which contains value names and their count. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Text value of a facet, such as "Black" for - facet "colorFamilies". - - This field is a member of `oneof`_ ``facet_value``. - interval (google.cloud.retail_v2.types.Interval): - Interval value for a facet, such as [10, 20) for facet - "price". - - This field is a member of `oneof`_ ``facet_value``. - count (int): - Number of items that have this facet value. - """ - - value = proto.Field( - proto.STRING, - number=1, - oneof='facet_value', - ) - interval = proto.Field( - proto.MESSAGE, - number=2, - oneof='facet_value', - message=common.Interval, - ) - count = proto.Field( - proto.INT64, - number=3, - ) - - key = proto.Field( - proto.STRING, - number=1, - ) - values = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SearchResponse.Facet.FacetValue', - ) - dynamic_facet = proto.Field( - proto.BOOL, - number=3, - ) - - class QueryExpansionInfo(proto.Message): - r"""Information describing query expansion including whether - expansion has occurred. - - Attributes: - expanded_query (bool): - Bool describing whether query expansion has - occurred. - pinned_result_count (int): - Number of pinned results. This field will only be set when - expansion happens and - [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] - is set to true. - """ - - expanded_query = proto.Field( - proto.BOOL, - number=1, - ) - pinned_result_count = proto.Field( - proto.INT64, - number=2, - ) - - @property - def raw_page(self): - return self - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=SearchResult, - ) - facets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Facet, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - corrected_query = proto.Field( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - next_page_token = proto.Field( - proto.STRING, - number=6, - ) - query_expansion_info = proto.Field( - proto.MESSAGE, - number=7, - message=QueryExpansionInfo, - ) - redirect_uri = proto.Field( - proto.STRING, - number=10, - ) - applied_controls = proto.RepeatedField( - proto.STRING, - number=12, - ) - invalid_condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py deleted file mode 100644 index 0d6b6823..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event.py +++ /dev/null @@ -1,508 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import product as gcr_product -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'UserEvent', - 'ProductDetail', - 'CompletionDetail', - 'PurchaseTransaction', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information Retail API needs - to know about how end users interact with customers' website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - - ``add-to-cart``: Products being added to cart. - - ``category-page-view``: Special pages such as sale or - promotion pages viewed. - - ``detail-page-view``: Products detail page viewed. - - ``home-page-view``: Homepage viewed. - - ``promotion-offered``: Promotion is offered to a user. - - ``promotion-not-offered``: Promotion is not offered to a - user. - - ``purchase-complete``: User finishing a purchase. - - ``search``: Product search. - - ``shopping-cart-page-view``: User viewing a shopping - cart. - visitor_id (str): - Required. A unique identifier for tracking visitors. - - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor log in/out of the website. - - Don't set the field to the same fixed ID for different - users. This mixes the event history of those users together, - which results in degraded model quality. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - The field should not contain PII or user-data. We recommend - to use Google Analytics `Client - ID `__ - for this field. - session_id (str): - A unique identifier for tracking a visitor session with a - length limit of 128 bytes. A session is an aggregation of an - end user behavior in a time span. - - A general guideline to populate the sesion_id: - - 1. If user has no activity for 30 min, a new session_id - should be assigned. - 2. The session_id should be unique across users, suggest use - uuid or add visitor_id as prefix. - event_time (google.protobuf.timestamp_pb2.Timestamp): - Only required for - [UserEventService.ImportUserEvents][google.cloud.retail.v2.UserEventService.ImportUserEvents] - method. Timestamp of when the user event happened. - experiment_ids (Sequence[str]): - A list of identifiers for the independent - experiment groups this user event belongs to. - This is used to distinguish between user events - associated with different experiment setups - (e.g. using Retail API, using different - recommendation models). - attribution_token (str): - Highly recommended for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]. - This field enables accurate attribution of recommendation - model performance. - - The value must be a valid - [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] - for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]. - The value must be a valid - [SearchResponse.attribution_token][google.cloud.retail.v2.SearchResponse.attribution_token] - for user events that are the result of - [SearchService.Search][google.cloud.retail.v2.SearchService.Search]. - - This token enables us to accurately attribute page view or - purchase back to the event and the particular predict - response containing this clicked/purchased product. If user - clicks on product K in the recommendation results, pass - [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] - as a URL parameter to product K's page. When recording - events on product K's page, log the - [PredictResponse.attribution_token][google.cloud.retail.v2.PredictResponse.attribution_token] - to this field. - product_details (Sequence[google.cloud.retail_v2.types.ProductDetail]): - The main product details related to the event. - - This field is optional except for the following event types: - - - ``add-to-cart`` - - ``detail-page-view`` - - ``purchase-complete`` - - In a ``search`` event, this field represents the products - returned to the end user on the current page (the end user - may have not finished browsing the whole page yet). When a - new page is returned to the end user, after - pagination/filtering/ordering even for the same query, a new - ``search`` event with different - [product_details][google.cloud.retail.v2.UserEvent.product_details] - is desired. The end user may have not finished browsing the - whole page yet. - completion_detail (google.cloud.retail_v2.types.CompletionDetail): - The main auto-completion details related to the event. - - This field should be set for ``search`` event when - autocomplete function is enabled and the user clicks a - suggestion for search. - attributes (Mapping[str, google.cloud.retail_v2.types.CustomAttribute]): - Extra user event features to include in the recommendation - model. - - If you provide custom attributes for ingested user events, - also include them in the user events that you associate with - prediction requests. Custom attribute formatting must be - consistent between imported events and events provided with - prediction requests. This lets the Retail API use those - custom attributes when training models and serving - predictions, which helps improve recommendation quality. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - The key must be a UTF-8 encoded string with a length - limit of 5,000 characters. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a UTF-8 - encoded string with a length limit of 256 characters. - - For number attributes, at most 400 values are allowed. - - For product recommendations, an example of extra user - information is traffic_channel, which is how a user arrives - at the site. Users can arrive at the site by coming to the - site directly, coming through Google search, or in other - ways. - cart_id (str): - The ID or name of the associated shopping cart. This ID is - used to associate multiple items added or present in the - cart before purchase. - - This can only be set for ``add-to-cart``, - ``purchase-complete``, or ``shopping-cart-page-view`` - events. - purchase_transaction (google.cloud.retail_v2.types.PurchaseTransaction): - A transaction represents the entire purchase transaction. - - Required for ``purchase-complete`` events. Other event types - should not set this field. Otherwise, an INVALID_ARGUMENT - error is returned. - search_query (str): - The user's search query. - - See - [SearchRequest.query][google.cloud.retail.v2.SearchRequest.query] - for definition. - - The value must be a UTF-8 encoded string with a length limit - of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - At least one of - [search_query][google.cloud.retail.v2.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. - - See - [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - order_by (str): - The order in which products are returned. - - See - [SearchRequest.order_by][google.cloud.retail.v2.SearchRequest.order_by] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - offset (int): - An integer that specifies the current offset for pagination - (the 0-indexed starting location, amongst the products - deemed by the API as relevant). - - See - [SearchRequest.offset][google.cloud.retail.v2.SearchRequest.offset] - for definition. - - If this field is negative, an INVALID_ARGUMENT is returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - - Required for ``category-page-view`` events. At least one of - [search_query][google.cloud.retail.v2.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2.types.UserInfo): - User information. - uri (str): - Complete URL (window.location.href) of the - user's current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. Maximum length - 5,000 characters. - referrer_uri (str): - The referrer URL of the current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. - page_view_id (str): - A unique ID of a web page view. - - This should be kept the same for all user events triggered - from the same pageview. For example, an item detail page - view could trigger multiple events as the user is browsing - the page. The ``pageViewId`` property should be kept the - same for all these events so that they can be grouped - together properly. - - When using the client side event reporting with JavaScript - pixel and Google Tag Manager, this value is filled in - automatically. - """ - - event_type = proto.Field( - proto.STRING, - number=1, - ) - visitor_id = proto.Field( - proto.STRING, - number=2, - ) - session_id = proto.Field( - proto.STRING, - number=21, - ) - event_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - experiment_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - product_details = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='ProductDetail', - ) - completion_detail = proto.Field( - proto.MESSAGE, - number=22, - message='CompletionDetail', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=common.CustomAttribute, - ) - cart_id = proto.Field( - proto.STRING, - number=8, - ) - purchase_transaction = proto.Field( - proto.MESSAGE, - number=9, - message='PurchaseTransaction', - ) - search_query = proto.Field( - proto.STRING, - number=10, - ) - filter = proto.Field( - proto.STRING, - number=16, - ) - order_by = proto.Field( - proto.STRING, - number=17, - ) - offset = proto.Field( - proto.INT32, - number=18, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=11, - ) - user_info = proto.Field( - proto.MESSAGE, - number=12, - message=common.UserInfo, - ) - uri = proto.Field( - proto.STRING, - number=13, - ) - referrer_uri = proto.Field( - proto.STRING, - number=14, - ) - page_view_id = proto.Field( - proto.STRING, - number=15, - ) - - -class ProductDetail(proto.Message): - r"""Detailed product information associated with a user event. - - Attributes: - product (google.cloud.retail_v2.types.Product): - Required. [Product][google.cloud.retail.v2.Product] - information. - - Required field(s): - - - [Product.id][google.cloud.retail.v2.Product.id] - - Optional override field(s): - - - [Product.price_info][google.cloud.retail.v2.Product.price_info] - - If any supported optional fields are provided, we will treat - them as a full override when looking up product information - from the catalog. Thus, it is important to ensure that the - overriding fields are accurate and complete. - - All other product fields are ignored and instead populated - via catalog lookup after event ingestion. - quantity (google.protobuf.wrappers_pb2.Int32Value): - Quantity of the product associated with the user event. - - For example, this field will be 2 if two products are added - to the shopping cart for ``purchase-complete`` event. - Required for ``add-to-cart`` and ``purchase-complete`` event - types. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - quantity = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -class CompletionDetail(proto.Message): - r"""Detailed completion information including completion - attribution token and clicked completion info. - - Attributes: - completion_attribution_token (str): - Completion attribution token in - [CompleteQueryResponse.attribution_token][google.cloud.retail.v2.CompleteQueryResponse.attribution_token]. - selected_suggestion (str): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2.CompleteQueryResponse.CompletionResult.suggestion]. - selected_position (int): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2.CompleteQueryResponse.CompletionResult.suggestion] - position, starting from 0. - """ - - completion_attribution_token = proto.Field( - proto.STRING, - number=1, - ) - selected_suggestion = proto.Field( - proto.STRING, - number=2, - ) - selected_position = proto.Field( - proto.INT32, - number=3, - ) - - -class PurchaseTransaction(proto.Message): - r"""A transaction represents the entire purchase transaction. - - Attributes: - id (str): - The transaction ID with a length limit of 128 - characters. - revenue (float): - Required. Total non-zero revenue or grand - total associated with the transaction. This - value include shipping, tax, or other - adjustments to total revenue that you want to - include as part of your revenue calculations. - tax (float): - All the taxes associated with the - transaction. - cost (float): - All the costs associated with the products. These can be - manufacturing costs, shipping expenses not borne by the end - user, or any other costs, such that: - - - Profit = - [revenue][google.cloud.retail.v2.PurchaseTransaction.revenue] - - [tax][google.cloud.retail.v2.PurchaseTransaction.tax] - - [cost][google.cloud.retail.v2.PurchaseTransaction.cost] - currency_code (str): - Required. Currency code. Use three-character - ISO-4217 code. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - revenue = proto.Field( - proto.FLOAT, - number=2, - ) - tax = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - currency_code = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py b/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py deleted file mode 100644 index fcfc46d7..00000000 --- a/owl-bot-staging/v2/google/cloud/retail_v2/types/user_event_service.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2.types import user_event as gcr_user_event - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2', - manifest={ - 'WriteUserEventRequest', - 'CollectUserEventRequest', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'RejoinUserEventsMetadata', - }, -) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (google.cloud.retail_v2.types.UserEvent): - Required. User event to write. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (str): - Required. URL encoded UserEvent proto with a - length limit of 2,000,000 characters. - uri (str): - The URL including cgi-parameters but - excluding the hash fragment with a length limit - of 5,000 characters. This is often more useful - than the referer URL, because many browsers only - send the domain for 3rd party requests. - ets (int): - The event timestamp in milliseconds. This - prevents browser caching of otherwise identical - get requests. The name is abbreviated to reduce - the payload bytes. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.STRING, - number=2, - ) - uri = proto.Field( - proto.STRING, - number=3, - ) - ets = proto.Field( - proto.INT64, - number=4, - ) - - -class RejoinUserEventsRequest(proto.Message): - r"""Request message for RejoinUserEvents method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event_rejoin_scope (google.cloud.retail_v2.types.RejoinUserEventsRequest.UserEventRejoinScope): - The type of the user event rejoin to define the scope and - range of the user events to be rejoined with the latest - product catalog. Defaults to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not - set, or set to an invalid integer value. - """ - class UserEventRejoinScope(proto.Enum): - r"""The scope of user events to be rejoined with the latest product - catalog. If the rejoining aims at reducing number of unjoined - events, set UserEventRejoinScope to UNJOINED_EVENTS. If the - rejoining aims at correcting product catalog information in joined - events, set UserEventRejoinScope to JOINED_EVENTS. If all events - needs to be rejoined, set UserEventRejoinScope to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. - """ - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 - JOINED_EVENTS = 1 - UNJOINED_EVENTS = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event_rejoin_scope = proto.Field( - proto.ENUM, - number=2, - enum=UserEventRejoinScope, - ) - - -class RejoinUserEventsResponse(proto.Message): - r"""Response message for RejoinUserEvents method. - - Attributes: - rejoined_user_events_count (int): - Number of user events that were joined with - latest product catalog. - """ - - rejoined_user_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -class RejoinUserEventsMetadata(proto.Message): - r"""Metadata for RejoinUserEvents method. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py deleted file mode 100644 index e7ab4118..00000000 --- a/owl-bot-staging/v2/noxfile.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.6", - "3.7", - "3.8", - "3.9", - "3.10", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==19.10b0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.9" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/retail_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py deleted file mode 100644 index fb30eae6..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_async.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_GetDefaultBranch_async] -from google.cloud import retail_v2 - - -async def sample_get_default_branch(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py deleted file mode 100644 index 0af0ece9..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_get_default_branch_sync.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_GetDefaultBranch_sync] -from google.cloud import retail_v2 - - -def sample_get_default_branch(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py deleted file mode 100644 index 2a0930de..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_ListCatalogs_async] -from google.cloud import retail_v2 - - -async def sample_list_catalogs(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py deleted file mode 100644 index 2671a121..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_list_catalogs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_ListCatalogs_sync] -from google.cloud import retail_v2 - - -def sample_list_catalogs(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py deleted file mode 100644 index f85e3ed8..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_async.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_SetDefaultBranch_async] -from google.cloud import retail_v2 - - -async def sample_set_default_branch(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - -# [END retail_v2_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py deleted file mode 100644 index 34371062..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_set_default_branch_sync.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_SetDefaultBranch_sync] -from google.cloud import retail_v2 - - -def sample_set_default_branch(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - -# [END retail_v2_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py deleted file mode 100644 index 2a2b3dde..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_UpdateCatalog_async] -from google.cloud import retail_v2 - - -async def sample_update_catalog(): - # Create a client - client = retail_v2.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py deleted file mode 100644 index bf721cba..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_catalog_service_update_catalog_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CatalogService_UpdateCatalog_sync] -from google.cloud import retail_v2 - - -def sample_update_catalog(): - # Create a client - client = retail_v2.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py deleted file mode 100644 index c72ecfdf..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CompletionService_CompleteQuery_async] -from google.cloud import retail_v2 - - -async def sample_complete_query(): - # Create a client - client = retail_v2.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py deleted file mode 100644 index 30b10016..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_complete_query_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CompletionService_CompleteQuery_sync] -from google.cloud import retail_v2 - - -def sample_complete_query(): - # Create a client - client = retail_v2.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py deleted file mode 100644 index 75f45f91..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CompletionService_ImportCompletionData_async] -from google.cloud import retail_v2 - - -async def sample_import_completion_data(): - # Create a client - client = retail_v2.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py deleted file mode 100644 index cc31057e..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_completion_service_import_completion_data_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_CompletionService_ImportCompletionData_sync] -from google.cloud import retail_v2 - - -def sample_import_completion_data(): - # Create a client - client = retail_v2.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py deleted file mode 100644 index f46819c5..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_PredictionService_Predict_async] -from google.cloud import retail_v2 - - -async def sample_predict(): - # Create a client - client = retail_v2.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py deleted file mode 100644 index ad37063f..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_prediction_service_predict_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_PredictionService_Predict_sync] -from google.cloud import retail_v2 - - -def sample_predict(): - # Create a client - client = retail_v2.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py deleted file mode 100644 index ceea2869..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_AddFulfillmentPlaces_async] -from google.cloud import retail_v2 - - -async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py deleted file mode 100644 index 1739ec91..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_AddFulfillmentPlaces_sync] -from google.cloud import retail_v2 - - -def sample_add_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py deleted file mode 100644 index 6155d5ce..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_AddLocalInventories_async] -from google.cloud import retail_v2 - - -async def sample_add_local_inventories(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py deleted file mode 100644 index b57dce2f..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_add_local_inventories_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_AddLocalInventories_sync] -from google.cloud import retail_v2 - - -def sample_add_local_inventories(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py deleted file mode 100644 index fe1cb991..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_CreateProduct_async] -from google.cloud import retail_v2 - - -async def sample_create_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py deleted file mode 100644 index 9cc154d9..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_create_product_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_CreateProduct_sync] -from google.cloud import retail_v2 - - -def sample_create_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py deleted file mode 100644 index 33318da7..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_DeleteProduct_async] -from google.cloud import retail_v2 - - -async def sample_delete_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - -# [END retail_v2_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py deleted file mode 100644 index 797690c6..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_delete_product_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_DeleteProduct_sync] -from google.cloud import retail_v2 - - -def sample_delete_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - -# [END retail_v2_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py deleted file mode 100644 index 32ba279d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_GetProduct_async] -from google.cloud import retail_v2 - - -async def sample_get_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py deleted file mode 100644 index 62805768..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_get_product_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_GetProduct_sync] -from google.cloud import retail_v2 - - -def sample_get_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py deleted file mode 100644 index 390f0977..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_ImportProducts_async] -from google.cloud import retail_v2 - - -async def sample_import_products(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py deleted file mode 100644 index fcd8c82f..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_import_products_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_ImportProducts_sync] -from google.cloud import retail_v2 - - -def sample_import_products(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py deleted file mode 100644 index 5e85f948..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_ListProducts_async] -from google.cloud import retail_v2 - - -async def sample_list_products(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py deleted file mode 100644 index 30f7fd1f..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_list_products_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_ListProducts_sync] -from google.cloud import retail_v2 - - -def sample_list_products(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py deleted file mode 100644 index 08172bf4..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async] -from google.cloud import retail_v2 - - -async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py deleted file mode 100644 index 37f86ba9..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync] -from google.cloud import retail_v2 - - -def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py deleted file mode 100644 index 762dab6d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_RemoveLocalInventories_async] -from google.cloud import retail_v2 - - -async def sample_remove_local_inventories(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py deleted file mode 100644 index 7aa52d5d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_remove_local_inventories_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_RemoveLocalInventories_sync] -from google.cloud import retail_v2 - - -def sample_remove_local_inventories(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py deleted file mode 100644 index 62a24100..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_SetInventory_async] -from google.cloud import retail_v2 - - -async def sample_set_inventory(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2.Product() - inventory.title = "title_value" - - request = retail_v2.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py deleted file mode 100644 index aa5a0539..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_set_inventory_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_SetInventory_sync] -from google.cloud import retail_v2 - - -def sample_set_inventory(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2.Product() - inventory.title = "title_value" - - request = retail_v2.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py deleted file mode 100644 index 9ea76295..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_UpdateProduct_async] -from google.cloud import retail_v2 - - -async def sample_update_product(): - # Create a client - client = retail_v2.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py deleted file mode 100644 index 866c7e7c..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_product_service_update_product_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_ProductService_UpdateProduct_sync] -from google.cloud import retail_v2 - - -def sample_update_product(): - # Create a client - client = retail_v2.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2.Product() - product.title = "title_value" - - request = retail_v2.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py deleted file mode 100644 index ddebd9e8..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_async.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_SearchService_Search_async] -from google.cloud import retail_v2 - - -async def sample_search(): - # Create a client - client = retail_v2.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py deleted file mode 100644 index fc20bb3d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_search_service_search_sync.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_SearchService_Search_sync] -from google.cloud import retail_v2 - - -def sample_search(): - # Create a client - client = retail_v2.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py deleted file mode 100644 index b8bb6a81..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_CollectUserEvent_async] -from google.cloud import retail_v2 - - -async def sample_collect_user_event(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py deleted file mode 100644 index 10b302e3..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_collect_user_event_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_CollectUserEvent_sync] -from google.cloud import retail_v2 - - -def sample_collect_user_event(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py deleted file mode 100644 index 55ad399a..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_ImportUserEvents_async] -from google.cloud import retail_v2 - - -async def sample_import_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py deleted file mode 100644 index 835edec6..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_import_user_events_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_ImportUserEvents_sync] -from google.cloud import retail_v2 - - -def sample_import_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py deleted file mode 100644 index 1da1d39d..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_PurgeUserEvents_async] -from google.cloud import retail_v2 - - -async def sample_purge_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py deleted file mode 100644 index 48814171..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_purge_user_events_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_PurgeUserEvents_sync] -from google.cloud import retail_v2 - - -def sample_purge_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py deleted file mode 100644 index a2617cfe..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_RejoinUserEvents_async] -from google.cloud import retail_v2 - - -async def sample_rejoin_user_events(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py deleted file mode 100644 index eb8ed62c..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_rejoin_user_events_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_RejoinUserEvents_sync] -from google.cloud import retail_v2 - - -def sample_rejoin_user_events(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py deleted file mode 100644 index 82afc25a..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_WriteUserEvent_async] -from google.cloud import retail_v2 - - -async def sample_write_user_event(): - # Create a client - client = retail_v2.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py deleted file mode 100644 index 62336b25..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/retail_v2_generated_user_event_service_write_user_event_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2_generated_UserEventService_WriteUserEvent_sync] -from google.cloud import retail_v2 - - -def sample_write_user_event(): - # Create a client - client = retail_v2.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json deleted file mode 100644 index c6a55bd4..00000000 --- a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_retail_v2.json +++ /dev/null @@ -1,3826 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.retail.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-cloud-retail" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2_generated_catalog_service_get_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_GetDefaultBranch_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_get_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2_generated_catalog_service_get_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_GetDefaultBranch_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_get_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ListCatalogsRequest" - }, - { - "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.retail_v2.services.catalog_service.pagers.ListCatalogsAsyncPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2_generated_catalog_service_list_catalogs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_ListCatalogs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_list_catalogs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ListCatalogsRequest" - }, - { - "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.retail_v2.services.catalog_service.pagers.ListCatalogsPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2_generated_catalog_service_list_catalogs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_ListCatalogs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_list_catalogs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2_generated_catalog_service_set_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_SetDefaultBranch_async", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_set_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2_generated_catalog_service_set_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_SetDefaultBranch_sync", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_set_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceAsyncClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2.types.Catalog" - }, - { - "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.retail_v2.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2_generated_catalog_service_update_catalog_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_UpdateCatalog_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_update_catalog_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2.CatalogServiceClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2.types.Catalog" - }, - { - "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.retail_v2.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2_generated_catalog_service_update_catalog_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CatalogService_UpdateCatalog_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_catalog_service_update_catalog_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2_generated_completion_service_complete_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CompletionService_CompleteQuery_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_completion_service_complete_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2.CompletionServiceClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2_generated_completion_service_complete_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CompletionService_CompleteQuery_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_completion_service_complete_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.CompletionServiceAsyncClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2_generated_completion_service_import_completion_data_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CompletionService_ImportCompletionData_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_completion_service_import_completion_data_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2.CompletionServiceClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2_generated_completion_service_import_completion_data_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_CompletionService_ImportCompletionData_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_completion_service_import_completion_data_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.PredictionServiceAsyncClient", - "shortName": "PredictionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.PredictionServiceAsyncClient.predict", - "method": { - "fullName": "google.cloud.retail.v2.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2_generated_prediction_service_predict_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_PredictionService_Predict_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_prediction_service_predict_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.PredictionServiceClient", - "shortName": "PredictionServiceClient" - }, - "fullName": "google.cloud.retail_v2.PredictionServiceClient.predict", - "method": { - "fullName": "google.cloud.retail.v2.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2_generated_prediction_service_predict_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_PredictionService_Predict_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_prediction_service_predict_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2_generated_product_service_add_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_AddFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_add_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2_generated_product_service_add_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_AddFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_add_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2_generated_product_service_add_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_AddLocalInventories_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_add_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2_generated_product_service_add_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_AddLocalInventories_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_add_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "name": "product_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.retail_v2.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2_generated_product_service_create_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_CreateProduct_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_create_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "name": "product_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.retail_v2.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2_generated_product_service_create_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_CreateProduct_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_create_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2_generated_product_service_delete_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_DeleteProduct_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_delete_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2_generated_product_service_delete_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_DeleteProduct_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_delete_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.GetProductRequest" - }, - { - "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.retail_v2.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2_generated_product_service_get_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_GetProduct_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_get_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.GetProductRequest" - }, - { - "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.retail_v2.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2_generated_product_service_get_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_GetProduct_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_get_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2_generated_product_service_import_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_ImportProducts_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_import_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2_generated_product_service_import_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_ImportProducts_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_import_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ListProductsRequest" - }, - { - "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.retail_v2.services.product_service.pagers.ListProductsAsyncPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2_generated_product_service_list_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_ListProducts_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_list_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ListProductsRequest" - }, - { - "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.retail_v2.services.product_service.pagers.ListProductsPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2_generated_product_service_list_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_ListProducts_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_list_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2_generated_product_service_remove_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_RemoveFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_remove_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2_generated_product_service_remove_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_RemoveFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_remove_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2_generated_product_service_remove_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_RemoveLocalInventories_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_remove_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2_generated_product_service_remove_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_RemoveLocalInventories_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_remove_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2_generated_product_service_set_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_SetInventory_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_set_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2_generated_product_service_set_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_SetInventory_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_set_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceAsyncClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "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.retail_v2.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2_generated_product_service_update_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_UpdateProduct_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_update_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2.ProductServiceClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2.types.Product" - }, - { - "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.retail_v2.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2_generated_product_service_update_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_ProductService_UpdateProduct_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_product_service_update_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.SearchServiceAsyncClient.search", - "method": { - "fullName": "google.cloud.retail.v2.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2_generated_search_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_SearchService_Search_async", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_search_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.SearchServiceClient", - "shortName": "SearchServiceClient" - }, - "fullName": "google.cloud.retail_v2.SearchServiceClient.search", - "method": { - "fullName": "google.cloud.retail.v2.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.services.search_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2_generated_search_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_SearchService_Search_sync", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_search_service_search_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2_generated_user_event_service_collect_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_CollectUserEvent_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_collect_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2_generated_user_event_service_collect_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_CollectUserEvent_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_collect_user_event_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2_generated_user_event_service_import_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_ImportUserEvents_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_import_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2_generated_user_event_service_import_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_ImportUserEvents_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_import_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2_generated_user_event_service_purge_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_PurgeUserEvents_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_purge_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2_generated_user_event_service_purge_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_PurgeUserEvents_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_purge_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2_generated_user_event_service_rejoin_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_RejoinUserEvents_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_rejoin_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2_generated_user_event_service_rejoin_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_RejoinUserEvents_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_rejoin_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceAsyncClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2_generated_user_event_service_write_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_WriteUserEvent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_write_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2.UserEventServiceClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2_generated_user_event_service_write_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2_generated_UserEventService_WriteUserEvent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2_generated_user_event_service_write_user_event_sync.py" - } - ] -} diff --git a/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py deleted file mode 100644 index 9ed9d278..00000000 --- a/owl-bot-staging/v2/scripts/fixup_retail_v2_keywords.py +++ /dev/null @@ -1,199 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class retailCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), - 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), - 'create_product': ('parent', 'product', 'product_id', ), - 'delete_product': ('name', ), - 'get_default_branch': ('catalog', ), - 'get_product': ('name', ), - 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), - 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), - 'import_user_events': ('parent', 'input_config', 'errors_config', ), - 'list_catalogs': ('parent', 'page_size', 'page_token', ), - 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', ), - 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), - 'purge_user_events': ('parent', 'filter', 'force', ), - 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), - 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), - 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), - 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', 'labels', 'spell_correction_spec', ), - 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), - 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), - 'update_catalog': ('catalog', 'update_mask', ), - 'update_product': ('product', 'update_mask', 'allow_missing', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=retailCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the retail client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2/setup.py b/owl-bot-staging/v2/setup.py deleted file mode 100644 index 1103510b..00000000 --- a/owl-bot-staging/v2/setup.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-retail', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-retail", - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 2.8.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'googleapis-common-protos >= 1.55.0, <2.0.0dev', - 'proto-plus >= 1.19.7', - ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py deleted file mode 100644 index ad47935c..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_catalog_service.py +++ /dev/null @@ -1,2317 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.catalog_service import CatalogServiceAsyncClient -from google.cloud.retail_v2.services.catalog_service import CatalogServiceClient -from google.cloud.retail_v2.services.catalog_service import pagers -from google.cloud.retail_v2.services.catalog_service import transports -from google.cloud.retail_v2.types import catalog -from google.cloud.retail_v2.types import catalog as gcr_catalog -from google.cloud.retail_v2.types import catalog_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CatalogServiceClient._get_default_mtls_endpoint(None) is None - assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CatalogServiceGrpcTransport, "grpc"), - (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_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", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_catalog_service_client_get_transport_class(): - transport = CatalogServiceClient.get_transport_class() - available_transports = [ - transports.CatalogServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CatalogServiceClient.get_transport_class("grpc") - assert transport == transports.CatalogServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CatalogServiceClient, CatalogServiceAsyncClient -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_catalog_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ListCatalogsRequest, - dict, -]) -def test_list_catalogs(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalogs), - '__call__') as call: - client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - -@pytest.mark.asyncio -async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_catalogs_async_from_dict(): - await test_list_catalogs_async(request_type=dict) - - -def test_list_catalogs_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = catalog_service.ListCatalogsResponse() - client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_catalogs( - 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_catalogs_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_catalogs_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_catalogs( - 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_catalogs_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - - -def test_list_catalogs_pager(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_catalogs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, catalog.Catalog) - for i in results) -def test_list_catalogs_pages(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = list(client.list_catalogs(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_catalogs_async_pager(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_catalogs(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, catalog.Catalog) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_catalogs_async_pages(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCatalogRequest, - dict, -]) -def test_update_catalog(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - ) - response = client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_catalog_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalog), - '__call__') as call: - client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - -@pytest.mark.asyncio -async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_catalog_async_from_dict(): - await test_update_catalog_async(request_type=dict) - - -def test_update_catalog_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = gcr_catalog.Catalog() - client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_catalog_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -def test_update_catalog_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_catalog_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.SetDefaultBranchRequest, - dict, -]) -def test_set_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_set_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_set_default_branch_async_from_dict(): - await test_set_default_branch_async(request_type=dict) - - -def test_set_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = None - client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_set_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_set_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetDefaultBranchRequest, - dict, -]) -def test_get_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - ) - response = client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -def test_get_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_default_branch), - '__call__') as call: - client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - )) - response = await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -@pytest.mark.asyncio -async def test_get_default_branch_async_from_dict(): - await test_get_default_branch_async(request_type=dict) - - -def test_get_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = catalog_service.GetDefaultBranchResponse() - client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_get_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_get_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CatalogServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.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 = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CatalogServiceGrpcTransport, - ) - -def test_catalog_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_catalog_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_catalogs', - 'update_catalog', - 'set_default_branch', - 'get_default_branch', - ) - 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_catalog_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.retail_v2.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport( - 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_catalog_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.retail_v2.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport() - adc.assert_called_once() - - -def test_catalog_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) - CatalogServiceClient() - 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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -def test_catalog_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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -def test_catalog_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.CatalogServiceGrpcTransport, grpc_helpers), - (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_catalog_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_no_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_with_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_catalog_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcTransport( - 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_catalog_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcAsyncIOTransport( - 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_branch_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = CatalogServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = CatalogServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_branch_path(path) - assert expected == actual - -def test_catalog_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - } - path = CatalogServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CatalogServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = CatalogServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = CatalogServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = CatalogServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CatalogServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = CatalogServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = CatalogServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = CatalogServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = CatalogServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CatalogServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py deleted file mode 100644 index daf312fe..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_completion_service.py +++ /dev/null @@ -1,1501 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.completion_service import CompletionServiceAsyncClient -from google.cloud.retail_v2.services.completion_service import CompletionServiceClient -from google.cloud.retail_v2.services.completion_service import transports -from google.cloud.retail_v2.types import completion_service -from google.cloud.retail_v2.types import import_config -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CompletionServiceClient._get_default_mtls_endpoint(None) is None - assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CompletionServiceGrpcTransport, "grpc"), - (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_completion_service_client_get_transport_class(): - transport = CompletionServiceClient.get_transport_class() - available_transports = [ - transports.CompletionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CompletionServiceClient.get_transport_class("grpc") - assert transport == transports.CompletionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CompletionServiceClient, CompletionServiceAsyncClient -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_completion_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CompletionServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - ) - response = client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - -@pytest.mark.asyncio -async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - )) - response = await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -@pytest.mark.asyncio -async def test_complete_query_async_from_dict(): - await test_complete_query_async(request_type=dict) - - -def test_complete_query_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = completion_service.CompleteQueryResponse() - client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_complete_query_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) - await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportCompletionDataRequest, - dict, -]) -def test_import_completion_data(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_completion_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - -@pytest.mark.asyncio -async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_completion_data_async_from_dict(): - await test_import_completion_data_async(request_type=dict) - - -def test_import_completion_data_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # 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_completion_data_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CompletionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CompletionServiceGrpcTransport, - ) - -def test_completion_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_completion_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'complete_query', - 'import_completion_data', - ) - 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_completion_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_completion_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport() - adc.assert_called_once() - - -def test_completion_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CompletionServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionServiceGrpcTransport, grpc_helpers), - (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_completion_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_no_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_with_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_completion_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_completion_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_completion_service_grpc_lro_client(): - client = CompletionServiceClient( - 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_completion_service_grpc_lro_async_client(): - client = CompletionServiceAsyncClient( - 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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CompletionServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CompletionServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CompletionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CompletionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = CompletionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CompletionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CompletionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CompletionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = CompletionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CompletionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CompletionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CompletionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CompletionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py deleted file mode 100644 index 08628b2d..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_prediction_service.py +++ /dev/null @@ -1,1329 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.prediction_service import PredictionServiceAsyncClient -from google.cloud.retail_v2.services.prediction_service import PredictionServiceClient -from google.cloud.retail_v2.services.prediction_service import transports -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import prediction_service -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import promotion -from google.cloud.retail_v2.types import user_event -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PredictionServiceClient._get_default_mtls_endpoint(None) is None - assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PredictionServiceGrpcTransport, "grpc"), - (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_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", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_prediction_service_client_get_transport_class(): - transport = PredictionServiceClient.get_transport_class() - available_transports = [ - transports.PredictionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = PredictionServiceClient.get_transport_class("grpc") - assert transport == transports.PredictionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - PredictionServiceClient, PredictionServiceAsyncClient -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_prediction_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - prediction_service.PredictRequest, - dict, -]) -def test_predict(request_type, transport: str = 'grpc'): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - response = client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - -@pytest.mark.asyncio -async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - )) - response = await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -@pytest.mark.asyncio -async def test_predict_async_from_dict(): - await test_predict_async(request_type=dict) - - -def test_predict_field_headers(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = prediction_service.PredictResponse() - client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_predict_field_headers_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) - await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PredictionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PredictionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.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 = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, - ) - -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'predict', - ) - 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport( - 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport() - adc.assert_called_once() - - -def test_prediction_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) - PredictionServiceClient() - 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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -def test_prediction_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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -def test_prediction_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.PredictionServiceGrpcTransport, grpc_helpers), - (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_prediction_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_no_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_with_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_prediction_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcTransport( - 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_prediction_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcAsyncIOTransport( - 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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_product_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - product = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - "branch": "winkle", - "product": "nautilus", - } - path = PredictionServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PredictionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = PredictionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = PredictionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = PredictionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PredictionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = PredictionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = PredictionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = PredictionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = PredictionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PredictionServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py deleted file mode 100644 index 6bd5f4bf..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_product_service.py +++ /dev/null @@ -1,4135 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.product_service import ProductServiceAsyncClient -from google.cloud.retail_v2.services.product_service import ProductServiceClient -from google.cloud.retail_v2.services.product_service import pagers -from google.cloud.retail_v2.services.product_service import transports -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import product as gcr_product -from google.cloud.retail_v2.types import product_service -from google.cloud.retail_v2.types import promotion -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ProductServiceClient._get_default_mtls_endpoint(None) is None - assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ProductServiceGrpcTransport, "grpc"), - (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_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", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_product_service_client_get_transport_class(): - transport = ProductServiceClient.get_transport_class() - available_transports = [ - transports.ProductServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ProductServiceClient.get_transport_class("grpc") - assert transport == transports.ProductServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_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(ProductServiceClient, '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(ProductServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ProductServiceClient, ProductServiceAsyncClient -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_product_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.CreateProductRequest, - dict, -]) -def test_create_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_create_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - -@pytest.mark.asyncio -async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_create_product_async_from_dict(): - await test_create_product_async(request_type=dict) - - -def test_create_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - - -def test_create_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - -@pytest.mark.asyncio -async def test_create_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.GetProductRequest, - dict, -]) -def test_get_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_get_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - -@pytest.mark.asyncio -async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_get_product_async_from_dict(): - await test_get_product_async(request_type=dict) - - -def test_get_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = product.Product() - client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.GetProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.GetProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.ListProductsRequest, - dict, -]) -def test_list_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - -@pytest.mark.asyncio -async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_products_async_from_dict(): - await test_list_products_async(request_type=dict) - - -def test_list_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = product_service.ListProductsResponse() - client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_products( - 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_products_flattened_error(): - client = ProductServiceClient( - credentials=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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_products_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_products( - 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_products_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - - -def test_list_products_pager(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_products(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, product.Product) - for i in results) -def test_list_products_pages(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = list(client.list_products(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_products_async_pager(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_products(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, product.Product) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_products_async_pages(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_products(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - product_service.UpdateProductRequest, - dict, -]) -def test_update_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_update_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - -@pytest.mark.asyncio -async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_update_product_async_from_dict(): - await test_update_product_async(request_type=dict) - - -def test_update_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -def test_update_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.DeleteProductRequest, - dict, -]) -def test_delete_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - -@pytest.mark.asyncio -async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_product_async_from_dict(): - await test_delete_product_async(request_type=dict) - - -def test_delete_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = None - client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportProductsRequest, - dict, -]) -def test_import_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - -@pytest.mark.asyncio -async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__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_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_products_async_from_dict(): - await test_import_products_async(request_type=dict) - - -def test_import_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - product_service.SetInventoryRequest, - dict, -]) -def test_set_inventory(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_inventory_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - -@pytest.mark.asyncio -async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_inventory_async_from_dict(): - await test_set_inventory_async(request_type=dict) - - -def test_set_inventory_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_inventory_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -def test_set_inventory_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_set_inventory_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_set_inventory_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_inventory_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddFulfillmentPlacesRequest, - dict, -]) -def test_add_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async_from_dict(): - await test_add_fulfillment_places_async(request_type=dict) - - -def test_add_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveFulfillmentPlacesRequest, - dict, -]) -def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async_from_dict(): - await test_remove_fulfillment_places_async(request_type=dict) - - -def test_remove_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddLocalInventoriesRequest, - dict, -]) -def test_add_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_local_inventories_async_from_dict(): - await test_add_local_inventories_async(request_type=dict) - - -def test_add_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveLocalInventoriesRequest, - dict, -]) -def test_remove_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_local_inventories_async_from_dict(): - await test_remove_local_inventories_async(request_type=dict) - - -def test_remove_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProductServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ProductServiceClient.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 = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProductServiceGrpcTransport, - ) - -def test_product_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_product_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.product_service.transports.ProductServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_product', - 'get_product', - 'list_products', - 'update_product', - 'delete_product', - 'import_products', - 'set_inventory', - 'add_fulfillment_places', - 'remove_fulfillment_places', - 'add_local_inventories', - 'remove_local_inventories', - ) - 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_product_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.retail_v2.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport( - 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_product_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.retail_v2.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport() - adc.assert_called_once() - - -def test_product_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) - ProductServiceClient() - 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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - ], -) -def test_product_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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - ], -) -def test_product_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.ProductServiceGrpcTransport, grpc_helpers), - (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_product_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_no_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_with_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_product_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcTransport( - 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_product_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcAsyncIOTransport( - 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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_product_service_grpc_lro_client(): - client = ProductServiceClient( - 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_product_service_grpc_lro_async_client(): - client = ProductServiceAsyncClient( - 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" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = ProductServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = ProductServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = ProductServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = ProductServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProductServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ProductServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProductServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ProductServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProductServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ProductServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ProductServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ProductServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ProductServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ProductServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ProductServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py deleted file mode 100644 index dd102323..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_search_service.py +++ /dev/null @@ -1,1546 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.search_service import SearchServiceAsyncClient -from google.cloud.retail_v2.services.search_service import SearchServiceClient -from google.cloud.retail_v2.services.search_service import pagers -from google.cloud.retail_v2.services.search_service import transports -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import search_service -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SearchServiceClient._get_default_mtls_endpoint(None) is None - assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SearchServiceGrpcTransport, "grpc"), - (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_search_service_client_get_transport_class(): - transport = SearchServiceClient.get_transport_class() - available_transports = [ - transports.SearchServiceGrpcTransport, - ] - assert transport in available_transports - - transport = SearchServiceClient.get_transport_class("grpc") - assert transport == transports.SearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SearchServiceClient, SearchServiceAsyncClient -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SearchServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - search_service.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - - -def test_search_field_headers(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = search_service.SearchResponse() - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_field_headers_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_search_pager(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('placement', ''), - )), - ) - pager = client.search(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_async_pager(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, - ) - -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_search_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_search_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport() - adc.assert_called_once() - - -def test_search_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SearchServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SearchServiceGrpcTransport, grpc_helpers), - (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_search_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_no_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_with_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_branch_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = SearchServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = SearchServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = SearchServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = SearchServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py b/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py deleted file mode 100644 index e6c54dee..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/retail_v2/test_user_event_service.py +++ /dev/null @@ -1,2038 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.retail_v2.services.user_event_service import UserEventServiceClient -from google.cloud.retail_v2.services.user_event_service import transports -from google.cloud.retail_v2.types import common -from google.cloud.retail_v2.types import import_config -from google.cloud.retail_v2.types import product -from google.cloud.retail_v2.types import promotion -from google.cloud.retail_v2.types import purge_config -from google.cloud.retail_v2.types import user_event -from google.cloud.retail_v2.types import user_event_service -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, UserEventServiceAsyncClient -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - ) - response = client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = user_event.UserEvent() - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) - await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeUserEventsRequest, - dict, -]) -def test_purge_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - -@pytest.mark.asyncio -async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_user_events_async_from_dict(): - await test_purge_user_events_async(request_type=dict) - - -def test_purge_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_purge_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.RejoinUserEventsRequest, - dict, -]) -def test_rejoin_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_rejoin_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - -@pytest.mark.asyncio -async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_rejoin_user_events_async_from_dict(): - await test_rejoin_user_events_async(request_type=dict) - - -def test_rejoin_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_rejoin_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'purge_user_events', - 'import_user_events', - 'rejoin_user_events', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_user_event_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_user_event_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -def test_user_event_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - UserEventServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_no_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_with_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = UserEventServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = UserEventServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_product_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - product = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - "branch": "whelk", - "product": "octopus", - } - path = UserEventServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/.coveragerc b/owl-bot-staging/v2alpha/.coveragerc deleted file mode 100644 index a8b114f0..00000000 --- a/owl-bot-staging/v2alpha/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/retail/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2alpha/.flake8 b/owl-bot-staging/v2alpha/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v2alpha/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2alpha/MANIFEST.in b/owl-bot-staging/v2alpha/MANIFEST.in deleted file mode 100644 index 3ee710cc..00000000 --- a/owl-bot-staging/v2alpha/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/retail *.py -recursive-include google/cloud/retail_v2alpha *.py diff --git a/owl-bot-staging/v2alpha/README.rst b/owl-bot-staging/v2alpha/README.rst deleted file mode 100644 index cb039760..00000000 --- a/owl-bot-staging/v2alpha/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Retail API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Retail API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2alpha/docs/conf.py b/owl-bot-staging/v2alpha/docs/conf.py deleted file mode 100644 index 5be9eb4b..00000000 --- a/owl-bot-staging/v2alpha/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-retail documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-retail" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-retail-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-retail.tex", - u"google-cloud-retail Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-retail", - u"Google Cloud Retail Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-retail", - u"google-cloud-retail Documentation", - author, - "google-cloud-retail", - "GAPIC library for Google Cloud Retail API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2alpha/docs/index.rst b/owl-bot-staging/v2alpha/docs/index.rst deleted file mode 100644 index dc0a2096..00000000 --- a/owl-bot-staging/v2alpha/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - retail_v2alpha/services - retail_v2alpha/types diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst deleted file mode 100644 index 745d0cf4..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/catalog_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CatalogService --------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.catalog_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.catalog_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst deleted file mode 100644 index 3a276433..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/completion_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CompletionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2alpha.services.completion_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst deleted file mode 100644 index 36aaf9b6..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/control_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ControlService --------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.control_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.control_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst deleted file mode 100644 index b659cf98..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/prediction_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -PredictionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2alpha.services.prediction_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst deleted file mode 100644 index acbb336e..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/product_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ProductService --------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.product_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.product_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst deleted file mode 100644 index ad4c486d..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SearchService -------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst deleted file mode 100644 index edeb8cfc..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/services.rst +++ /dev/null @@ -1,13 +0,0 @@ -Services for Google Cloud Retail v2alpha API -============================================ -.. toctree:: - :maxdepth: 2 - - catalog_service - completion_service - control_service - prediction_service - product_service - search_service - serving_config_service - user_event_service diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst deleted file mode 100644 index c1516860..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/serving_config_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ServingConfigService --------------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.serving_config_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2alpha.services.serving_config_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst deleted file mode 100644 index c1445ad6..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Retail v2alpha API -========================================= - -.. automodule:: google.cloud.retail_v2alpha.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst b/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst deleted file mode 100644 index 8c56485c..00000000 --- a/owl-bot-staging/v2alpha/docs/retail_v2alpha/user_event_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.retail_v2alpha.services.user_event_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py deleted file mode 100644 index a17a283b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail/__init__.py +++ /dev/null @@ -1,281 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.retail_v2alpha.services.catalog_service.client import CatalogServiceClient -from google.cloud.retail_v2alpha.services.catalog_service.async_client import CatalogServiceAsyncClient -from google.cloud.retail_v2alpha.services.completion_service.client import CompletionServiceClient -from google.cloud.retail_v2alpha.services.completion_service.async_client import CompletionServiceAsyncClient -from google.cloud.retail_v2alpha.services.control_service.client import ControlServiceClient -from google.cloud.retail_v2alpha.services.control_service.async_client import ControlServiceAsyncClient -from google.cloud.retail_v2alpha.services.prediction_service.client import PredictionServiceClient -from google.cloud.retail_v2alpha.services.prediction_service.async_client import PredictionServiceAsyncClient -from google.cloud.retail_v2alpha.services.product_service.client import ProductServiceClient -from google.cloud.retail_v2alpha.services.product_service.async_client import ProductServiceAsyncClient -from google.cloud.retail_v2alpha.services.search_service.client import SearchServiceClient -from google.cloud.retail_v2alpha.services.search_service.async_client import SearchServiceAsyncClient -from google.cloud.retail_v2alpha.services.serving_config_service.client import ServingConfigServiceClient -from google.cloud.retail_v2alpha.services.serving_config_service.async_client import ServingConfigServiceAsyncClient -from google.cloud.retail_v2alpha.services.user_event_service.client import UserEventServiceClient -from google.cloud.retail_v2alpha.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.retail_v2alpha.types.catalog import AttributesConfig -from google.cloud.retail_v2alpha.types.catalog import Catalog -from google.cloud.retail_v2alpha.types.catalog import CatalogAttribute -from google.cloud.retail_v2alpha.types.catalog import CompletionConfig -from google.cloud.retail_v2alpha.types.catalog import MerchantCenterLink -from google.cloud.retail_v2alpha.types.catalog import MerchantCenterLinkingConfig -from google.cloud.retail_v2alpha.types.catalog import ProductLevelConfig -from google.cloud.retail_v2alpha.types.catalog_service import AddCatalogAttributeRequest -from google.cloud.retail_v2alpha.types.catalog_service import GetAttributesConfigRequest -from google.cloud.retail_v2alpha.types.catalog_service import GetCompletionConfigRequest -from google.cloud.retail_v2alpha.types.catalog_service import GetDefaultBranchRequest -from google.cloud.retail_v2alpha.types.catalog_service import GetDefaultBranchResponse -from google.cloud.retail_v2alpha.types.catalog_service import ListCatalogsRequest -from google.cloud.retail_v2alpha.types.catalog_service import ListCatalogsResponse -from google.cloud.retail_v2alpha.types.catalog_service import RemoveCatalogAttributeRequest -from google.cloud.retail_v2alpha.types.catalog_service import ReplaceCatalogAttributeRequest -from google.cloud.retail_v2alpha.types.catalog_service import SetDefaultBranchRequest -from google.cloud.retail_v2alpha.types.catalog_service import UpdateAttributesConfigRequest -from google.cloud.retail_v2alpha.types.catalog_service import UpdateCatalogRequest -from google.cloud.retail_v2alpha.types.catalog_service import UpdateCompletionConfigRequest -from google.cloud.retail_v2alpha.types.common import Audience -from google.cloud.retail_v2alpha.types.common import ColorInfo -from google.cloud.retail_v2alpha.types.common import Condition -from google.cloud.retail_v2alpha.types.common import CustomAttribute -from google.cloud.retail_v2alpha.types.common import FulfillmentInfo -from google.cloud.retail_v2alpha.types.common import Image -from google.cloud.retail_v2alpha.types.common import Interval -from google.cloud.retail_v2alpha.types.common import LocalInventory -from google.cloud.retail_v2alpha.types.common import PriceInfo -from google.cloud.retail_v2alpha.types.common import Rating -from google.cloud.retail_v2alpha.types.common import Rule -from google.cloud.retail_v2alpha.types.common import UserInfo -from google.cloud.retail_v2alpha.types.common import AttributeConfigLevel -from google.cloud.retail_v2alpha.types.common import SearchSolutionUseCase -from google.cloud.retail_v2alpha.types.common import SolutionType -from google.cloud.retail_v2alpha.types.completion_service import CompleteQueryRequest -from google.cloud.retail_v2alpha.types.completion_service import CompleteQueryResponse -from google.cloud.retail_v2alpha.types.control import Control -from google.cloud.retail_v2alpha.types.control_service import CreateControlRequest -from google.cloud.retail_v2alpha.types.control_service import DeleteControlRequest -from google.cloud.retail_v2alpha.types.control_service import GetControlRequest -from google.cloud.retail_v2alpha.types.control_service import ListControlsRequest -from google.cloud.retail_v2alpha.types.control_service import ListControlsResponse -from google.cloud.retail_v2alpha.types.control_service import UpdateControlRequest -from google.cloud.retail_v2alpha.types.export_config import ExportErrorsConfig -from google.cloud.retail_v2alpha.types.export_config import ExportMetadata -from google.cloud.retail_v2alpha.types.export_config import ExportProductsResponse -from google.cloud.retail_v2alpha.types.export_config import ExportUserEventsResponse -from google.cloud.retail_v2alpha.types.import_config import BigQuerySource -from google.cloud.retail_v2alpha.types.import_config import CompletionDataInputConfig -from google.cloud.retail_v2alpha.types.import_config import GcsSource -from google.cloud.retail_v2alpha.types.import_config import ImportCompletionDataRequest -from google.cloud.retail_v2alpha.types.import_config import ImportCompletionDataResponse -from google.cloud.retail_v2alpha.types.import_config import ImportErrorsConfig -from google.cloud.retail_v2alpha.types.import_config import ImportMetadata -from google.cloud.retail_v2alpha.types.import_config import ImportProductsRequest -from google.cloud.retail_v2alpha.types.import_config import ImportProductsResponse -from google.cloud.retail_v2alpha.types.import_config import ImportUserEventsRequest -from google.cloud.retail_v2alpha.types.import_config import ImportUserEventsResponse -from google.cloud.retail_v2alpha.types.import_config import ProductInlineSource -from google.cloud.retail_v2alpha.types.import_config import ProductInputConfig -from google.cloud.retail_v2alpha.types.import_config import UserEventImportSummary -from google.cloud.retail_v2alpha.types.import_config import UserEventInlineSource -from google.cloud.retail_v2alpha.types.import_config import UserEventInputConfig -from google.cloud.retail_v2alpha.types.prediction_service import PredictRequest -from google.cloud.retail_v2alpha.types.prediction_service import PredictResponse -from google.cloud.retail_v2alpha.types.product import Product -from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesMetadata -from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesRequest -from google.cloud.retail_v2alpha.types.product_service import AddFulfillmentPlacesResponse -from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesMetadata -from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesRequest -from google.cloud.retail_v2alpha.types.product_service import AddLocalInventoriesResponse -from google.cloud.retail_v2alpha.types.product_service import CreateProductRequest -from google.cloud.retail_v2alpha.types.product_service import DeleteProductRequest -from google.cloud.retail_v2alpha.types.product_service import GetProductRequest -from google.cloud.retail_v2alpha.types.product_service import ListProductsRequest -from google.cloud.retail_v2alpha.types.product_service import ListProductsResponse -from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesMetadata -from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesRequest -from google.cloud.retail_v2alpha.types.product_service import RemoveFulfillmentPlacesResponse -from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesMetadata -from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesRequest -from google.cloud.retail_v2alpha.types.product_service import RemoveLocalInventoriesResponse -from google.cloud.retail_v2alpha.types.product_service import SetInventoryMetadata -from google.cloud.retail_v2alpha.types.product_service import SetInventoryRequest -from google.cloud.retail_v2alpha.types.product_service import SetInventoryResponse -from google.cloud.retail_v2alpha.types.product_service import UpdateProductRequest -from google.cloud.retail_v2alpha.types.promotion import Promotion -from google.cloud.retail_v2alpha.types.purge_config import PurgeMetadata -from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsMetadata -from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsRequest -from google.cloud.retail_v2alpha.types.purge_config import PurgeProductsResponse -from google.cloud.retail_v2alpha.types.purge_config import PurgeUserEventsRequest -from google.cloud.retail_v2alpha.types.purge_config import PurgeUserEventsResponse -from google.cloud.retail_v2alpha.types.search_service import SearchRequest -from google.cloud.retail_v2alpha.types.search_service import SearchResponse -from google.cloud.retail_v2alpha.types.serving_config import ServingConfig -from google.cloud.retail_v2alpha.types.serving_config_service import AddControlRequest -from google.cloud.retail_v2alpha.types.serving_config_service import CreateServingConfigRequest -from google.cloud.retail_v2alpha.types.serving_config_service import DeleteServingConfigRequest -from google.cloud.retail_v2alpha.types.serving_config_service import GetServingConfigRequest -from google.cloud.retail_v2alpha.types.serving_config_service import ListServingConfigsRequest -from google.cloud.retail_v2alpha.types.serving_config_service import ListServingConfigsResponse -from google.cloud.retail_v2alpha.types.serving_config_service import RemoveControlRequest -from google.cloud.retail_v2alpha.types.serving_config_service import UpdateServingConfigRequest -from google.cloud.retail_v2alpha.types.user_event import CompletionDetail -from google.cloud.retail_v2alpha.types.user_event import ProductDetail -from google.cloud.retail_v2alpha.types.user_event import PurchaseTransaction -from google.cloud.retail_v2alpha.types.user_event import UserEvent -from google.cloud.retail_v2alpha.types.user_event_service import CollectUserEventRequest -from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsMetadata -from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsRequest -from google.cloud.retail_v2alpha.types.user_event_service import RejoinUserEventsResponse -from google.cloud.retail_v2alpha.types.user_event_service import WriteUserEventRequest - -__all__ = ('CatalogServiceClient', - 'CatalogServiceAsyncClient', - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', - 'ControlServiceClient', - 'ControlServiceAsyncClient', - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', - 'ProductServiceClient', - 'ProductServiceAsyncClient', - 'SearchServiceClient', - 'SearchServiceAsyncClient', - 'ServingConfigServiceClient', - 'ServingConfigServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'AttributesConfig', - 'Catalog', - 'CatalogAttribute', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'ProductLevelConfig', - 'AddCatalogAttributeRequest', - 'GetAttributesConfigRequest', - 'GetCompletionConfigRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - 'SetDefaultBranchRequest', - 'UpdateAttributesConfigRequest', - 'UpdateCatalogRequest', - 'UpdateCompletionConfigRequest', - 'Audience', - 'ColorInfo', - 'Condition', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'Rule', - 'UserInfo', - 'AttributeConfigLevel', - 'SearchSolutionUseCase', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Control', - 'CreateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - 'UpdateControlRequest', - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeProductsMetadata', - 'PurgeProductsRequest', - 'PurgeProductsResponse', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'ServingConfig', - 'AddControlRequest', - 'CreateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'RemoveControlRequest', - 'UpdateServingConfigRequest', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail/py.typed b/owl-bot-staging/v2alpha/google/cloud/retail/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py deleted file mode 100644 index e515a173..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/__init__.py +++ /dev/null @@ -1,282 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.catalog_service import CatalogServiceClient -from .services.catalog_service import CatalogServiceAsyncClient -from .services.completion_service import CompletionServiceClient -from .services.completion_service import CompletionServiceAsyncClient -from .services.control_service import ControlServiceClient -from .services.control_service import ControlServiceAsyncClient -from .services.prediction_service import PredictionServiceClient -from .services.prediction_service import PredictionServiceAsyncClient -from .services.product_service import ProductServiceClient -from .services.product_service import ProductServiceAsyncClient -from .services.search_service import SearchServiceClient -from .services.search_service import SearchServiceAsyncClient -from .services.serving_config_service import ServingConfigServiceClient -from .services.serving_config_service import ServingConfigServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.catalog import AttributesConfig -from .types.catalog import Catalog -from .types.catalog import CatalogAttribute -from .types.catalog import CompletionConfig -from .types.catalog import MerchantCenterLink -from .types.catalog import MerchantCenterLinkingConfig -from .types.catalog import ProductLevelConfig -from .types.catalog_service import AddCatalogAttributeRequest -from .types.catalog_service import GetAttributesConfigRequest -from .types.catalog_service import GetCompletionConfigRequest -from .types.catalog_service import GetDefaultBranchRequest -from .types.catalog_service import GetDefaultBranchResponse -from .types.catalog_service import ListCatalogsRequest -from .types.catalog_service import ListCatalogsResponse -from .types.catalog_service import RemoveCatalogAttributeRequest -from .types.catalog_service import ReplaceCatalogAttributeRequest -from .types.catalog_service import SetDefaultBranchRequest -from .types.catalog_service import UpdateAttributesConfigRequest -from .types.catalog_service import UpdateCatalogRequest -from .types.catalog_service import UpdateCompletionConfigRequest -from .types.common import Audience -from .types.common import ColorInfo -from .types.common import Condition -from .types.common import CustomAttribute -from .types.common import FulfillmentInfo -from .types.common import Image -from .types.common import Interval -from .types.common import LocalInventory -from .types.common import PriceInfo -from .types.common import Rating -from .types.common import Rule -from .types.common import UserInfo -from .types.common import AttributeConfigLevel -from .types.common import SearchSolutionUseCase -from .types.common import SolutionType -from .types.completion_service import CompleteQueryRequest -from .types.completion_service import CompleteQueryResponse -from .types.control import Control -from .types.control_service import CreateControlRequest -from .types.control_service import DeleteControlRequest -from .types.control_service import GetControlRequest -from .types.control_service import ListControlsRequest -from .types.control_service import ListControlsResponse -from .types.control_service import UpdateControlRequest -from .types.export_config import ExportErrorsConfig -from .types.export_config import ExportMetadata -from .types.export_config import ExportProductsResponse -from .types.export_config import ExportUserEventsResponse -from .types.import_config import BigQuerySource -from .types.import_config import CompletionDataInputConfig -from .types.import_config import GcsSource -from .types.import_config import ImportCompletionDataRequest -from .types.import_config import ImportCompletionDataResponse -from .types.import_config import ImportErrorsConfig -from .types.import_config import ImportMetadata -from .types.import_config import ImportProductsRequest -from .types.import_config import ImportProductsResponse -from .types.import_config import ImportUserEventsRequest -from .types.import_config import ImportUserEventsResponse -from .types.import_config import ProductInlineSource -from .types.import_config import ProductInputConfig -from .types.import_config import UserEventImportSummary -from .types.import_config import UserEventInlineSource -from .types.import_config import UserEventInputConfig -from .types.prediction_service import PredictRequest -from .types.prediction_service import PredictResponse -from .types.product import Product -from .types.product_service import AddFulfillmentPlacesMetadata -from .types.product_service import AddFulfillmentPlacesRequest -from .types.product_service import AddFulfillmentPlacesResponse -from .types.product_service import AddLocalInventoriesMetadata -from .types.product_service import AddLocalInventoriesRequest -from .types.product_service import AddLocalInventoriesResponse -from .types.product_service import CreateProductRequest -from .types.product_service import DeleteProductRequest -from .types.product_service import GetProductRequest -from .types.product_service import ListProductsRequest -from .types.product_service import ListProductsResponse -from .types.product_service import RemoveFulfillmentPlacesMetadata -from .types.product_service import RemoveFulfillmentPlacesRequest -from .types.product_service import RemoveFulfillmentPlacesResponse -from .types.product_service import RemoveLocalInventoriesMetadata -from .types.product_service import RemoveLocalInventoriesRequest -from .types.product_service import RemoveLocalInventoriesResponse -from .types.product_service import SetInventoryMetadata -from .types.product_service import SetInventoryRequest -from .types.product_service import SetInventoryResponse -from .types.product_service import UpdateProductRequest -from .types.promotion import Promotion -from .types.purge_config import PurgeMetadata -from .types.purge_config import PurgeProductsMetadata -from .types.purge_config import PurgeProductsRequest -from .types.purge_config import PurgeProductsResponse -from .types.purge_config import PurgeUserEventsRequest -from .types.purge_config import PurgeUserEventsResponse -from .types.search_service import SearchRequest -from .types.search_service import SearchResponse -from .types.serving_config import ServingConfig -from .types.serving_config_service import AddControlRequest -from .types.serving_config_service import CreateServingConfigRequest -from .types.serving_config_service import DeleteServingConfigRequest -from .types.serving_config_service import GetServingConfigRequest -from .types.serving_config_service import ListServingConfigsRequest -from .types.serving_config_service import ListServingConfigsResponse -from .types.serving_config_service import RemoveControlRequest -from .types.serving_config_service import UpdateServingConfigRequest -from .types.user_event import CompletionDetail -from .types.user_event import ProductDetail -from .types.user_event import PurchaseTransaction -from .types.user_event import UserEvent -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import RejoinUserEventsMetadata -from .types.user_event_service import RejoinUserEventsRequest -from .types.user_event_service import RejoinUserEventsResponse -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CatalogServiceAsyncClient', - 'CompletionServiceAsyncClient', - 'ControlServiceAsyncClient', - 'PredictionServiceAsyncClient', - 'ProductServiceAsyncClient', - 'SearchServiceAsyncClient', - 'ServingConfigServiceAsyncClient', - 'UserEventServiceAsyncClient', -'AddCatalogAttributeRequest', -'AddControlRequest', -'AddFulfillmentPlacesMetadata', -'AddFulfillmentPlacesRequest', -'AddFulfillmentPlacesResponse', -'AddLocalInventoriesMetadata', -'AddLocalInventoriesRequest', -'AddLocalInventoriesResponse', -'AttributeConfigLevel', -'AttributesConfig', -'Audience', -'BigQuerySource', -'Catalog', -'CatalogAttribute', -'CatalogServiceClient', -'CollectUserEventRequest', -'ColorInfo', -'CompleteQueryRequest', -'CompleteQueryResponse', -'CompletionConfig', -'CompletionDataInputConfig', -'CompletionDetail', -'CompletionServiceClient', -'Condition', -'Control', -'ControlServiceClient', -'CreateControlRequest', -'CreateProductRequest', -'CreateServingConfigRequest', -'CustomAttribute', -'DeleteControlRequest', -'DeleteProductRequest', -'DeleteServingConfigRequest', -'ExportErrorsConfig', -'ExportMetadata', -'ExportProductsResponse', -'ExportUserEventsResponse', -'FulfillmentInfo', -'GcsSource', -'GetAttributesConfigRequest', -'GetCompletionConfigRequest', -'GetControlRequest', -'GetDefaultBranchRequest', -'GetDefaultBranchResponse', -'GetProductRequest', -'GetServingConfigRequest', -'Image', -'ImportCompletionDataRequest', -'ImportCompletionDataResponse', -'ImportErrorsConfig', -'ImportMetadata', -'ImportProductsRequest', -'ImportProductsResponse', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'Interval', -'ListCatalogsRequest', -'ListCatalogsResponse', -'ListControlsRequest', -'ListControlsResponse', -'ListProductsRequest', -'ListProductsResponse', -'ListServingConfigsRequest', -'ListServingConfigsResponse', -'LocalInventory', -'MerchantCenterLink', -'MerchantCenterLinkingConfig', -'PredictRequest', -'PredictResponse', -'PredictionServiceClient', -'PriceInfo', -'Product', -'ProductDetail', -'ProductInlineSource', -'ProductInputConfig', -'ProductLevelConfig', -'ProductServiceClient', -'Promotion', -'PurchaseTransaction', -'PurgeMetadata', -'PurgeProductsMetadata', -'PurgeProductsRequest', -'PurgeProductsResponse', -'PurgeUserEventsRequest', -'PurgeUserEventsResponse', -'Rating', -'RejoinUserEventsMetadata', -'RejoinUserEventsRequest', -'RejoinUserEventsResponse', -'RemoveCatalogAttributeRequest', -'RemoveControlRequest', -'RemoveFulfillmentPlacesMetadata', -'RemoveFulfillmentPlacesRequest', -'RemoveFulfillmentPlacesResponse', -'RemoveLocalInventoriesMetadata', -'RemoveLocalInventoriesRequest', -'RemoveLocalInventoriesResponse', -'ReplaceCatalogAttributeRequest', -'Rule', -'SearchRequest', -'SearchResponse', -'SearchServiceClient', -'SearchSolutionUseCase', -'ServingConfig', -'ServingConfigServiceClient', -'SetDefaultBranchRequest', -'SetInventoryMetadata', -'SetInventoryRequest', -'SetInventoryResponse', -'SolutionType', -'UpdateAttributesConfigRequest', -'UpdateCatalogRequest', -'UpdateCompletionConfigRequest', -'UpdateControlRequest', -'UpdateProductRequest', -'UpdateServingConfigRequest', -'UserEvent', -'UserEventImportSummary', -'UserEventInlineSource', -'UserEventInputConfig', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json deleted file mode 100644 index 543e36d6..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/gapic_metadata.json +++ /dev/null @@ -1,561 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.retail_v2alpha", - "protoPackage": "google.cloud.retail.v2alpha", - "schema": "1.0", - "services": { - "CatalogService": { - "clients": { - "grpc": { - "libraryClient": "CatalogServiceClient", - "rpcs": { - "AddCatalogAttribute": { - "methods": [ - "add_catalog_attribute" - ] - }, - "GetAttributesConfig": { - "methods": [ - "get_attributes_config" - ] - }, - "GetCompletionConfig": { - "methods": [ - "get_completion_config" - ] - }, - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "RemoveCatalogAttribute": { - "methods": [ - "remove_catalog_attribute" - ] - }, - "ReplaceCatalogAttribute": { - "methods": [ - "replace_catalog_attribute" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateAttributesConfig": { - "methods": [ - "update_attributes_config" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - }, - "UpdateCompletionConfig": { - "methods": [ - "update_completion_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CatalogServiceAsyncClient", - "rpcs": { - "AddCatalogAttribute": { - "methods": [ - "add_catalog_attribute" - ] - }, - "GetAttributesConfig": { - "methods": [ - "get_attributes_config" - ] - }, - "GetCompletionConfig": { - "methods": [ - "get_completion_config" - ] - }, - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "RemoveCatalogAttribute": { - "methods": [ - "remove_catalog_attribute" - ] - }, - "ReplaceCatalogAttribute": { - "methods": [ - "replace_catalog_attribute" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateAttributesConfig": { - "methods": [ - "update_attributes_config" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - }, - "UpdateCompletionConfig": { - "methods": [ - "update_completion_config" - ] - } - } - } - } - }, - "CompletionService": { - "clients": { - "grpc": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CompletionServiceAsyncClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - } - } - }, - "ControlService": { - "clients": { - "grpc": { - "libraryClient": "ControlServiceClient", - "rpcs": { - "CreateControl": { - "methods": [ - "create_control" - ] - }, - "DeleteControl": { - "methods": [ - "delete_control" - ] - }, - "GetControl": { - "methods": [ - "get_control" - ] - }, - "ListControls": { - "methods": [ - "list_controls" - ] - }, - "UpdateControl": { - "methods": [ - "update_control" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ControlServiceAsyncClient", - "rpcs": { - "CreateControl": { - "methods": [ - "create_control" - ] - }, - "DeleteControl": { - "methods": [ - "delete_control" - ] - }, - "GetControl": { - "methods": [ - "get_control" - ] - }, - "ListControls": { - "methods": [ - "list_controls" - ] - }, - "UpdateControl": { - "methods": [ - "update_control" - ] - } - } - } - } - }, - "PredictionService": { - "clients": { - "grpc": { - "libraryClient": "PredictionServiceClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PredictionServiceAsyncClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - } - } - }, - "ProductService": { - "clients": { - "grpc": { - "libraryClient": "ProductServiceClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "PurgeProducts": { - "methods": [ - "purge_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProductServiceAsyncClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "PurgeProducts": { - "methods": [ - "purge_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - } - } - }, - "SearchService": { - "clients": { - "grpc": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SearchServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - }, - "ServingConfigService": { - "clients": { - "grpc": { - "libraryClient": "ServingConfigServiceClient", - "rpcs": { - "AddControl": { - "methods": [ - "add_control" - ] - }, - "CreateServingConfig": { - "methods": [ - "create_serving_config" - ] - }, - "DeleteServingConfig": { - "methods": [ - "delete_serving_config" - ] - }, - "GetServingConfig": { - "methods": [ - "get_serving_config" - ] - }, - "ListServingConfigs": { - "methods": [ - "list_serving_configs" - ] - }, - "RemoveControl": { - "methods": [ - "remove_control" - ] - }, - "UpdateServingConfig": { - "methods": [ - "update_serving_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ServingConfigServiceAsyncClient", - "rpcs": { - "AddControl": { - "methods": [ - "add_control" - ] - }, - "CreateServingConfig": { - "methods": [ - "create_serving_config" - ] - }, - "DeleteServingConfig": { - "methods": [ - "delete_serving_config" - ] - }, - "GetServingConfig": { - "methods": [ - "get_serving_config" - ] - }, - "ListServingConfigs": { - "methods": [ - "list_serving_configs" - ] - }, - "RemoveControl": { - "methods": [ - "remove_control" - ] - }, - "UpdateServingConfig": { - "methods": [ - "update_serving_config" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py deleted file mode 100644 index d276b897..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CatalogServiceClient -from .async_client import CatalogServiceAsyncClient - -__all__ = ( - 'CatalogServiceClient', - 'CatalogServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py deleted file mode 100644 index e828ae6f..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/async_client.py +++ /dev/null @@ -1,1352 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.catalog_service import pagers -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport -from .client import CatalogServiceClient - - -class CatalogServiceAsyncClient: - """Service for managing catalog configuration.""" - - _client: CatalogServiceClient - - DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT - - attributes_config_path = staticmethod(CatalogServiceClient.attributes_config_path) - parse_attributes_config_path = staticmethod(CatalogServiceClient.parse_attributes_config_path) - branch_path = staticmethod(CatalogServiceClient.branch_path) - parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) - catalog_path = staticmethod(CatalogServiceClient.catalog_path) - parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) - completion_config_path = staticmethod(CatalogServiceClient.completion_config_path) - parse_completion_config_path = staticmethod(CatalogServiceClient.parse_completion_config_path) - common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CatalogServiceClient.common_project_path) - parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) - common_location_path = staticmethod(CatalogServiceClient.common_location_path) - parse_common_location_path = staticmethod(CatalogServiceClient.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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CatalogServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsAsyncPager: - r"""Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_list_catalogs(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - parent (:class:`str`): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2alpha.Catalog]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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsAsyncPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.ListCatalogsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_catalogs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCatalogsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_catalog(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2alpha.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2alpha.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] - method. - catalog (:class:`google.cloud.retail_v2alpha.types.Catalog`): - Required. The - [Catalog][google.cloud.retail.v2alpha.Catalog] to - update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2alpha.Catalog], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Catalog][google.cloud.retail.v2alpha.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2alpha.Catalog] to - update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCatalogRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_catalog, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_set_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (:class:`str`): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.SetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (:class:`str`): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # 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_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_completion_config(self, - request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Gets a - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] - method. - name (:class:`str`): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - - 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.retail_v2alpha.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetCompletionConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_completion_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_completion_config(self, - request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, - *, - completion_config: catalog.CompletionConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Updates the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - completion_config = retail_v2alpha.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2alpha.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = await client.update_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] - method. - completion_config (:class:`google.cloud.retail_v2alpha.types.CompletionConfig`): - Required. The - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``completion_config`` 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 - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([completion_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCompletionConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if completion_config is not None: - request.completion_config = completion_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_completion_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("completion_config.name", request.completion_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_attributes_config(self, - request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Gets an - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] - method. - name (:class:`str`): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - - 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.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetAttributesConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_attributes_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_attributes_config(self, - request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, - *, - attributes_config: catalog.AttributesConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Updates the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - attributes_config = retail_v2alpha.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2alpha.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = await client.update_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] - method. - attributes_config (:class:`google.cloud.retail_v2alpha.types.AttributesConfig`): - Required. The - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. - - This corresponds to the ``attributes_config`` 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 - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([attributes_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateAttributesConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attributes_config is not None: - request.attributes_config = attributes_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_attributes_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config.name", request.attributes_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def add_catalog_attribute(self, - request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Adds the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_add_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.AddCatalogAttributeRequest(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.add_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def remove_catalog_attribute(self, - request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Removes the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = await client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.RemoveCatalogAttributeRequest(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.remove_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def replace_catalog_attribute(self, - request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Replaces the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.ReplaceCatalogAttributeRequest(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.replace_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py deleted file mode 100644 index 85a7d228..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/client.py +++ /dev/null @@ -1,1582 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.catalog_service import pagers -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CatalogServiceGrpcTransport -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -class CatalogServiceClientMeta(type): - """Metaclass for the CatalogService 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[CatalogServiceTransport]] - _transport_registry["grpc"] = CatalogServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CatalogServiceTransport]: - """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): - """Service for managing catalog configuration.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CatalogServiceClient: 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: - CatalogServiceClient: 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) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def attributes_config_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified attributes_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_attributes_config_path(path: str) -> Dict[str,str]: - """Parses a attributes_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/attributesConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def completion_config_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified completion_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_completion_config_path(path: str) -> Dict[str,str]: - """Parses a completion_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/completionConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CatalogServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CatalogServiceTransport): - # transport is a CatalogServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsPager: - r"""Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_list_catalogs(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2alpha.Catalog]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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ListCatalogsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ListCatalogsRequest): - request = catalog_service.ListCatalogsRequest(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_catalogs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCatalogsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_catalog(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2alpha.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2alpha.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] - method. - catalog (google.cloud.retail_v2alpha.types.Catalog): - Required. The - [Catalog][google.cloud.retail.v2alpha.Catalog] to - update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2alpha.Catalog], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Catalog][google.cloud.retail.v2alpha.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2alpha.Catalog] to - update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCatalogRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCatalogRequest): - request = catalog_service.UpdateCatalogRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - 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_catalog] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_set_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.SetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.SetDefaultBranchRequest): - request = catalog_service.SetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetDefaultBranchRequest): - request = catalog_service.GetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_completion_config(self, - request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Gets a - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] - method. - name (str): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - - 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.retail_v2alpha.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetCompletionConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetCompletionConfigRequest): - request = catalog_service.GetCompletionConfigRequest(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_completion_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_completion_config(self, - request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, - *, - completion_config: catalog.CompletionConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Updates the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - completion_config = retail_v2alpha.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2alpha.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = client.update_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] - method. - completion_config (google.cloud.retail_v2alpha.types.CompletionConfig): - Required. The - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``completion_config`` 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 - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([completion_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCompletionConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCompletionConfigRequest): - request = catalog_service.UpdateCompletionConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if completion_config is not None: - request.completion_config = completion_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_completion_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("completion_config.name", request.completion_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_attributes_config(self, - request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Gets an - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] - method. - name (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - - 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.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetAttributesConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetAttributesConfigRequest): - request = catalog_service.GetAttributesConfigRequest(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_attributes_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_attributes_config(self, - request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, - *, - attributes_config: catalog.AttributesConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Updates the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - attributes_config = retail_v2alpha.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2alpha.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = client.update_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] - method. - attributes_config (google.cloud.retail_v2alpha.types.AttributesConfig): - Required. The - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. - - This corresponds to the ``attributes_config`` 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 - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([attributes_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateAttributesConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateAttributesConfigRequest): - request = catalog_service.UpdateAttributesConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attributes_config is not None: - request.attributes_config = attributes_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_attributes_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config.name", request.attributes_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def add_catalog_attribute(self, - request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Adds the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_add_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.AddCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.AddCatalogAttributeRequest): - request = catalog_service.AddCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def remove_catalog_attribute(self, - request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Removes the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.RemoveCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.RemoveCatalogAttributeRequest): - request = catalog_service.RemoveCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def replace_catalog_attribute(self, - request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Replaces the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ReplaceCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ReplaceCatalogAttributeRequest): - request = catalog_service.ReplaceCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.replace_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py deleted file mode 100644 index f78d4bfa..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog_service - - -class ListCatalogsPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` - 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[..., catalog_service.ListCatalogsResponse], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2alpha.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - for page in self.pages: - yield from page.catalogs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCatalogsAsyncPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListCatalogsResponse` - 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[catalog_service.ListCatalogsResponse]], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2alpha.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - async def async_generator(): - async for page in self.pages: - for response in page.catalogs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py deleted file mode 100644 index 0cffa336..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CatalogServiceTransport -from .grpc import CatalogServiceGrpcTransport -from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] -_transport_registry['grpc'] = CatalogServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport - -__all__ = ( - 'CatalogServiceTransport', - 'CatalogServiceGrpcTransport', - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py deleted file mode 100644 index 8a244fb4..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py +++ /dev/null @@ -1,297 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CatalogServiceTransport(abc.ABC): - """Abstract transport class for CatalogService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_catalogs: gapic_v1.method.wrap_method( - self.list_catalogs, - default_timeout=None, - client_info=client_info, - ), - self.update_catalog: gapic_v1.method.wrap_method( - self.update_catalog, - default_timeout=None, - client_info=client_info, - ), - self.set_default_branch: gapic_v1.method.wrap_method( - self.set_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_default_branch: gapic_v1.method.wrap_method( - self.get_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_completion_config: gapic_v1.method.wrap_method( - self.get_completion_config, - default_timeout=None, - client_info=client_info, - ), - self.update_completion_config: gapic_v1.method.wrap_method( - self.update_completion_config, - default_timeout=None, - client_info=client_info, - ), - self.get_attributes_config: gapic_v1.method.wrap_method( - self.get_attributes_config, - default_timeout=None, - client_info=client_info, - ), - self.update_attributes_config: gapic_v1.method.wrap_method( - self.update_attributes_config, - default_timeout=None, - client_info=client_info, - ), - self.add_catalog_attribute: gapic_v1.method.wrap_method( - self.add_catalog_attribute, - default_timeout=None, - client_info=client_info, - ), - self.remove_catalog_attribute: gapic_v1.method.wrap_method( - self.remove_catalog_attribute, - default_timeout=None, - client_info=client_info, - ), - self.replace_catalog_attribute: gapic_v1.method.wrap_method( - self.replace_catalog_attribute, - 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Union[ - catalog_service.ListCatalogsResponse, - Awaitable[catalog_service.ListCatalogsResponse] - ]]: - raise NotImplementedError() - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Union[ - gcr_catalog.Catalog, - Awaitable[gcr_catalog.Catalog] - ]]: - raise NotImplementedError() - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Union[ - catalog_service.GetDefaultBranchResponse, - Awaitable[catalog_service.GetDefaultBranchResponse] - ]]: - raise NotImplementedError() - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - Union[ - catalog.CompletionConfig, - Awaitable[catalog.CompletionConfig] - ]]: - raise NotImplementedError() - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - Union[ - catalog.CompletionConfig, - Awaitable[catalog.CompletionConfig] - ]]: - raise NotImplementedError() - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CatalogServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py deleted file mode 100644 index 4ebe0ff0..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc.py +++ /dev/null @@ -1,600 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO - - -class CatalogServiceGrpcTransport(CatalogServiceTransport): - """gRPC backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - catalog_service.ListCatalogsResponse]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - ~.ListCatalogsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - gcr_catalog.Catalog]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - ~.Catalog]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - empty_pb2.Empty]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - ~.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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - catalog_service.GetDefaultBranchResponse]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - ~.GetDefaultBranchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - catalog.CompletionConfig]: - r"""Return a callable for the get completion config method over gRPC. - - Gets a - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. - - Returns: - Callable[[~.GetCompletionConfigRequest], - ~.CompletionConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetCompletionConfig', - request_serializer=catalog_service.GetCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['get_completion_config'] - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - catalog.CompletionConfig]: - r"""Return a callable for the update completion config method over gRPC. - - Updates the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. - - Returns: - Callable[[~.UpdateCompletionConfigRequest], - ~.CompletionConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateCompletionConfig', - request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['update_completion_config'] - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - catalog.AttributesConfig]: - r"""Return a callable for the get attributes config method over gRPC. - - Gets an - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - Returns: - Callable[[~.GetAttributesConfigRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetAttributesConfig', - request_serializer=catalog_service.GetAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['get_attributes_config'] - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - catalog.AttributesConfig]: - r"""Return a callable for the update attributes config method over gRPC. - - Updates the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - Returns: - Callable[[~.UpdateAttributesConfigRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateAttributesConfig', - request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['update_attributes_config'] - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the add catalog attribute method over gRPC. - - Adds the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.AddCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_catalog_attribute' not in self._stubs: - self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/AddCatalogAttribute', - request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['add_catalog_attribute'] - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the remove catalog attribute method over gRPC. - - Removes the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.RemoveCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_catalog_attribute' not in self._stubs: - self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/RemoveCatalogAttribute', - request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['remove_catalog_attribute'] - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the replace catalog attribute method over gRPC. - - Replaces the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.ReplaceCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_catalog_attribute' not in self._stubs: - self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/ReplaceCatalogAttribute', - request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['replace_catalog_attribute'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CatalogServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py deleted file mode 100644 index 15eacf16..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,599 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CatalogServiceGrpcTransport - - -class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): - """gRPC AsyncIO backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Awaitable[catalog_service.ListCatalogsResponse]]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2alpha.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - Awaitable[~.ListCatalogsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Awaitable[gcr_catalog.Catalog]]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2alpha.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - Awaitable[~.Catalog]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2alpha.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - 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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Awaitable[catalog_service.GetDefaultBranchResponse]]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - Awaitable[~.GetDefaultBranchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - Awaitable[catalog.CompletionConfig]]: - r"""Return a callable for the get completion config method over gRPC. - - Gets a - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]. - - Returns: - Callable[[~.GetCompletionConfigRequest], - Awaitable[~.CompletionConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetCompletionConfig', - request_serializer=catalog_service.GetCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['get_completion_config'] - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - Awaitable[catalog.CompletionConfig]]: - r"""Return a callable for the update completion config method over gRPC. - - Updates the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig]s. - - Returns: - Callable[[~.UpdateCompletionConfigRequest], - Awaitable[~.CompletionConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateCompletionConfig', - request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['update_completion_config'] - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the get attributes config method over gRPC. - - Gets an - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - Returns: - Callable[[~.GetAttributesConfigRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/GetAttributesConfig', - request_serializer=catalog_service.GetAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['get_attributes_config'] - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the update attributes config method over gRPC. - - Updates the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - Returns: - Callable[[~.UpdateAttributesConfigRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/UpdateAttributesConfig', - request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['update_attributes_config'] - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the add catalog attribute method over gRPC. - - Adds the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.AddCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_catalog_attribute' not in self._stubs: - self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/AddCatalogAttribute', - request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['add_catalog_attribute'] - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the remove catalog attribute method over gRPC. - - Removes the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.RemoveCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_catalog_attribute' not in self._stubs: - self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/RemoveCatalogAttribute', - request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['remove_catalog_attribute'] - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the replace catalog attribute method over gRPC. - - Replaces the specified - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.ReplaceCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_catalog_attribute' not in self._stubs: - self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CatalogService/ReplaceCatalogAttribute', - request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['replace_catalog_attribute'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py deleted file mode 100644 index b8af95bd..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CompletionServiceClient -from .async_client import CompletionServiceAsyncClient - -__all__ = ( - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py deleted file mode 100644 index 74888568..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/async_client.py +++ /dev/null @@ -1,391 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .client import CompletionServiceClient - - -class CompletionServiceAsyncClient: - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: CompletionServiceClient - - DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(CompletionServiceClient.catalog_path) - parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) - common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CompletionServiceClient.common_project_path) - parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) - common_location_path = staticmethod(CompletionServiceClient.common_location_path) - parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CompletionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_complete_query(): - # Create a client - client = retail_v2alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.complete_query, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_import_completion_data(): - # Create a client - client = retail_v2alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2alpha.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. - 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. - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_completion_data, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py deleted file mode 100644 index 6e783e95..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/client.py +++ /dev/null @@ -1,593 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CompletionServiceGrpcTransport -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -class CompletionServiceClientMeta(type): - """Metaclass for the CompletionService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] - _transport_registry["grpc"] = CompletionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CompletionServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class CompletionServiceClient(metaclass=CompletionServiceClientMeta): - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CompletionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CompletionServiceTransport): - # transport is a CompletionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_complete_query(): - # Create a client - client = retail_v2alpha.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a completion_service.CompleteQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, completion_service.CompleteQueryRequest): - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_import_completion_data(): - # Create a client - client = retail_v2alpha.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2alpha.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. - 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. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportCompletionDataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportCompletionDataRequest): - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_completion_data] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py deleted file mode 100644 index a0c9542f..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CompletionServiceTransport -from .grpc import CompletionServiceGrpcTransport -from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] -_transport_registry['grpc'] = CompletionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport - -__all__ = ( - 'CompletionServiceTransport', - 'CompletionServiceGrpcTransport', - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py deleted file mode 100644 index 2e16e808..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/base.py +++ /dev/null @@ -1,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CompletionServiceTransport(abc.ABC): - """Abstract transport class for CompletionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.complete_query: gapic_v1.method.wrap_method( - self.complete_query, - default_timeout=None, - client_info=client_info, - ), - self.import_completion_data: gapic_v1.method.wrap_method( - self.import_completion_data, - 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Union[ - completion_service.CompleteQueryResponse, - Awaitable[completion_service.CompleteQueryResponse] - ]]: - raise NotImplementedError() - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CompletionServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py deleted file mode 100644 index dd953c63..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc.py +++ /dev/null @@ -1,325 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO - - -class CompletionServiceGrpcTransport(CompletionServiceTransport): - """gRPC backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - ~.CompleteQueryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - operations_pb2.Operation]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CompletionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py deleted file mode 100644 index 726b0e6e..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,324 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CompletionServiceGrpcTransport - - -class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): - """gRPC AsyncIO backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Awaitable[completion_service.CompleteQueryResponse]]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - Awaitable[~.CompleteQueryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - 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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py deleted file mode 100644 index e9a7be2f..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ControlServiceClient -from .async_client import ControlServiceAsyncClient - -__all__ = ( - 'ControlServiceClient', - 'ControlServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py deleted file mode 100644 index e32d838b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/async_client.py +++ /dev/null @@ -1,744 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.control_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.cloud.retail_v2alpha.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport -from .client import ControlServiceClient - - -class ControlServiceAsyncClient: - """Service for modifying Control.""" - - _client: ControlServiceClient - - DEFAULT_ENDPOINT = ControlServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ControlServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(ControlServiceClient.catalog_path) - parse_catalog_path = staticmethod(ControlServiceClient.parse_catalog_path) - control_path = staticmethod(ControlServiceClient.control_path) - parse_control_path = staticmethod(ControlServiceClient.parse_control_path) - common_billing_account_path = staticmethod(ControlServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ControlServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ControlServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ControlServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ControlServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ControlServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ControlServiceClient.common_project_path) - parse_common_project_path = staticmethod(ControlServiceClient.parse_common_project_path) - common_location_path = staticmethod(ControlServiceClient.common_location_path) - parse_common_location_path = staticmethod(ControlServiceClient.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: - ControlServiceAsyncClient: The constructed client. - """ - return ControlServiceClient.from_service_account_info.__func__(ControlServiceAsyncClient, 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: - ControlServiceAsyncClient: The constructed client. - """ - return ControlServiceClient.from_service_account_file.__func__(ControlServiceAsyncClient, 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 variabel 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 ControlServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ControlServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ControlServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ControlServiceClient).get_transport_class, type(ControlServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ControlServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the control service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ControlServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ControlServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_control(self, - request: Union[control_service.CreateControlRequest, dict] = None, - *, - parent: str = None, - control: gcr_control.Control = None, - control_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Creates a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_create_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = await client.create_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateControlRequest, dict]): - The request object. Request for CreateControl method. - parent (:class:`str`): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control (:class:`google.cloud.retail_v2alpha.types.Control`): - Required. The Control to create. - This corresponds to the ``control`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control_id (:class:`str`): - Required. The ID to use for the Control, which will - become the final component of the Control's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``control_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.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, control, control_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.CreateControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if control is not None: - request.control = control - if control_id is not None: - request.control_id = control_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_control(self, - request: Union[control_service.DeleteControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_delete_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteControlRequest( - name="name_value", - ) - - # Make the request - await client.delete_control(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteControlRequest, dict]): - The request object. Request for DeleteControl method. - name (:class:`str`): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.DeleteControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_control(self, - request: Union[control_service.UpdateControlRequest, dict] = None, - *, - control: gcr_control.Control = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Updates a Control. - - [Control][google.cloud.retail.v2alpha.Control] cannot be set to - a different oneof field, if so an INVALID_ARGUMENT is returned. - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.UpdateControlRequest( - control=control, - ) - - # Make the request - response = await client.update_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateControlRequest, dict]): - The request object. Request for UpdateControl method. - control (:class:`google.cloud.retail_v2alpha.types.Control`): - Required. The Control to update. - This corresponds to the ``control`` 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 - [Control][google.cloud.retail.v2alpha.Control] to - update. The following are NOT supported: - - - [Control.name][google.cloud.retail.v2alpha.Control.name] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([control, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.UpdateControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if control is not None: - request.control = control - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("control.name", request.control.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_control(self, - request: Union[control_service.GetControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> control.Control: - r"""Gets a Control. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetControlRequest( - name="name_value", - ) - - # Make the request - response = await client.get_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetControlRequest, dict]): - The request object. Request for GetControl method. - name (:class:`str`): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.GetControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_controls(self, - request: Union[control_service.ListControlsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListControlsAsyncPager: - r"""Lists all Controls linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_list_controls(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListControlsRequest, dict]): - The request object. Request for ListControls method. - parent (:class:`str`): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.control_service.pagers.ListControlsAsyncPager: - Response for ListControls method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.ListControlsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_controls, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListControlsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ControlServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py deleted file mode 100644 index 0981fa86..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/client.py +++ /dev/null @@ -1,953 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.control_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.cloud.retail_v2alpha.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ControlServiceGrpcTransport -from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport - - -class ControlServiceClientMeta(type): - """Metaclass for the ControlService 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[ControlServiceTransport]] - _transport_registry["grpc"] = ControlServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ControlServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ControlServiceTransport]: - """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 ControlServiceClient(metaclass=ControlServiceClientMeta): - """Service for modifying Control.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ControlServiceClient: 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: - ControlServiceClient: 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) -> ControlServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ControlServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def control_path(project: str,location: str,catalog: str,control: str,) -> str: - """Returns a fully-qualified control string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) - - @staticmethod - def parse_control_path(path: str) -> Dict[str,str]: - """Parses a control path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/controls/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ControlServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the control service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ControlServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ControlServiceTransport): - # transport is a ControlServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_control(self, - request: Union[control_service.CreateControlRequest, dict] = None, - *, - parent: str = None, - control: gcr_control.Control = None, - control_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Creates a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_create_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = client.create_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateControlRequest, dict]): - The request object. Request for CreateControl method. - parent (str): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control (google.cloud.retail_v2alpha.types.Control): - Required. The Control to create. - This corresponds to the ``control`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control_id (str): - Required. The ID to use for the Control, which will - become the final component of the Control's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``control_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.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, control, control_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.CreateControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.CreateControlRequest): - request = control_service.CreateControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if control is not None: - request.control = control - if control_id is not None: - request.control_id = control_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_control(self, - request: Union[control_service.DeleteControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_delete_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteControlRequest( - name="name_value", - ) - - # Make the request - client.delete_control(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteControlRequest, dict]): - The request object. Request for DeleteControl method. - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.DeleteControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.DeleteControlRequest): - request = control_service.DeleteControlRequest(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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_control(self, - request: Union[control_service.UpdateControlRequest, dict] = None, - *, - control: gcr_control.Control = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Updates a Control. - - [Control][google.cloud.retail.v2alpha.Control] cannot be set to - a different oneof field, if so an INVALID_ARGUMENT is returned. - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.UpdateControlRequest( - control=control, - ) - - # Make the request - response = client.update_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateControlRequest, dict]): - The request object. Request for UpdateControl method. - control (google.cloud.retail_v2alpha.types.Control): - Required. The Control to update. - This corresponds to the ``control`` 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 - [Control][google.cloud.retail.v2alpha.Control] to - update. The following are NOT supported: - - - [Control.name][google.cloud.retail.v2alpha.Control.name] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([control, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.UpdateControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.UpdateControlRequest): - request = control_service.UpdateControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if control is not None: - request.control = control - 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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("control.name", request.control.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_control(self, - request: Union[control_service.GetControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> control.Control: - r"""Gets a Control. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetControlRequest( - name="name_value", - ) - - # Make the request - response = client.get_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetControlRequest, dict]): - The request object. Request for GetControl method. - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.GetControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.GetControlRequest): - request = control_service.GetControlRequest(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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_controls(self, - request: Union[control_service.ListControlsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListControlsPager: - r"""Lists all Controls linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_list_controls(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListControlsRequest, dict]): - The request object. Request for ListControls method. - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.control_service.pagers.ListControlsPager: - Response for ListControls method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.ListControlsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.ListControlsRequest): - request = control_service.ListControlsRequest(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_controls] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListControlsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ControlServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py deleted file mode 100644 index d1c28748..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control_service - - -class ListControlsPager: - """A pager for iterating through ``list_controls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``controls`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListControls`` requests and continue to iterate - through the ``controls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` - 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[..., control_service.ListControlsResponse], - request: control_service.ListControlsRequest, - response: control_service.ListControlsResponse, - *, - 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.retail_v2alpha.types.ListControlsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListControlsResponse): - 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 = control_service.ListControlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[control_service.ListControlsResponse]: - 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[control.Control]: - for page in self.pages: - yield from page.controls - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListControlsAsyncPager: - """A pager for iterating through ``list_controls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``controls`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListControls`` requests and continue to iterate - through the ``controls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListControlsResponse` - 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[control_service.ListControlsResponse]], - request: control_service.ListControlsRequest, - response: control_service.ListControlsResponse, - *, - 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.retail_v2alpha.types.ListControlsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListControlsResponse): - 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 = control_service.ListControlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[control_service.ListControlsResponse]: - 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[control.Control]: - async def async_generator(): - async for page in self.pages: - for response in page.controls: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py deleted file mode 100644 index 3622876b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ControlServiceTransport -from .grpc import ControlServiceGrpcTransport -from .grpc_asyncio import ControlServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ControlServiceTransport]] -_transport_registry['grpc'] = ControlServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ControlServiceGrpcAsyncIOTransport - -__all__ = ( - 'ControlServiceTransport', - 'ControlServiceGrpcTransport', - 'ControlServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py deleted file mode 100644 index ef91c3df..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/base.py +++ /dev/null @@ -1,213 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ControlServiceTransport(abc.ABC): - """Abstract transport class for ControlService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_control: gapic_v1.method.wrap_method( - self.create_control, - default_timeout=None, - client_info=client_info, - ), - self.delete_control: gapic_v1.method.wrap_method( - self.delete_control, - default_timeout=None, - client_info=client_info, - ), - self.update_control: gapic_v1.method.wrap_method( - self.update_control, - default_timeout=None, - client_info=client_info, - ), - self.get_control: gapic_v1.method.wrap_method( - self.get_control, - default_timeout=None, - client_info=client_info, - ), - self.list_controls: gapic_v1.method.wrap_method( - self.list_controls, - 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 create_control(self) -> Callable[ - [control_service.CreateControlRequest], - Union[ - gcr_control.Control, - Awaitable[gcr_control.Control] - ]]: - raise NotImplementedError() - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - Union[ - gcr_control.Control, - Awaitable[gcr_control.Control] - ]]: - raise NotImplementedError() - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - Union[ - control.Control, - Awaitable[control.Control] - ]]: - raise NotImplementedError() - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - Union[ - control_service.ListControlsResponse, - Awaitable[control_service.ListControlsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ControlServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py deleted file mode 100644 index 121caf7d..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc.py +++ /dev/null @@ -1,382 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO - - -class ControlServiceGrpcTransport(ControlServiceTransport): - """gRPC backend transport for ControlService. - - Service for modifying Control. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_control(self) -> Callable[ - [control_service.CreateControlRequest], - gcr_control.Control]: - r"""Return a callable for the create control method over gRPC. - - Creates a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['create_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/CreateControl', - request_serializer=control_service.CreateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['create_control'] - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete control method over gRPC. - - Deletes a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteControlRequest], - ~.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_control' not in self._stubs: - self._stubs['delete_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/DeleteControl', - request_serializer=control_service.DeleteControlRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_control'] - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - gcr_control.Control]: - r"""Return a callable for the update control method over gRPC. - - Updates a Control. - - [Control][google.cloud.retail.v2alpha.Control] cannot be set to - a different oneof field, if so an INVALID_ARGUMENT is returned. - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.UpdateControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['update_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/UpdateControl', - request_serializer=control_service.UpdateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['update_control'] - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - control.Control]: - r"""Return a callable for the get control method over gRPC. - - Gets a Control. - - Returns: - Callable[[~.GetControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['get_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/GetControl', - request_serializer=control_service.GetControlRequest.serialize, - response_deserializer=control.Control.deserialize, - ) - return self._stubs['get_control'] - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - control_service.ListControlsResponse]: - r"""Return a callable for the list controls method over gRPC. - - Lists all Controls linked to this catalog. - - Returns: - Callable[[~.ListControlsRequest], - ~.ListControlsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_controls' not in self._stubs: - self._stubs['list_controls'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/ListControls', - request_serializer=control_service.ListControlsRequest.serialize, - response_deserializer=control_service.ListControlsResponse.deserialize, - ) - return self._stubs['list_controls'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ControlServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py deleted file mode 100644 index 9703924c..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,381 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ControlServiceGrpcTransport - - -class ControlServiceGrpcAsyncIOTransport(ControlServiceTransport): - """gRPC AsyncIO backend transport for ControlService. - - Service for modifying Control. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_control(self) -> Callable[ - [control_service.CreateControlRequest], - Awaitable[gcr_control.Control]]: - r"""Return a callable for the create control method over gRPC. - - Creates a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['create_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/CreateControl', - request_serializer=control_service.CreateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['create_control'] - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete control method over gRPC. - - Deletes a Control. - - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteControlRequest], - 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_control' not in self._stubs: - self._stubs['delete_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/DeleteControl', - request_serializer=control_service.DeleteControlRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_control'] - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - Awaitable[gcr_control.Control]]: - r"""Return a callable for the update control method over gRPC. - - Updates a Control. - - [Control][google.cloud.retail.v2alpha.Control] cannot be set to - a different oneof field, if so an INVALID_ARGUMENT is returned. - If the [Control][google.cloud.retail.v2alpha.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.UpdateControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['update_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/UpdateControl', - request_serializer=control_service.UpdateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['update_control'] - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - Awaitable[control.Control]]: - r"""Return a callable for the get control method over gRPC. - - Gets a Control. - - Returns: - Callable[[~.GetControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['get_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/GetControl', - request_serializer=control_service.GetControlRequest.serialize, - response_deserializer=control.Control.deserialize, - ) - return self._stubs['get_control'] - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - Awaitable[control_service.ListControlsResponse]]: - r"""Return a callable for the list controls method over gRPC. - - Lists all Controls linked to this catalog. - - Returns: - Callable[[~.ListControlsRequest], - Awaitable[~.ListControlsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_controls' not in self._stubs: - self._stubs['list_controls'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ControlService/ListControls', - request_serializer=control_service.ListControlsRequest.serialize, - response_deserializer=control_service.ListControlsResponse.deserialize, - ) - return self._stubs['list_controls'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ControlServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py deleted file mode 100644 index 7c079c80..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import PredictionServiceClient -from .async_client import PredictionServiceAsyncClient - -__all__ = ( - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py deleted file mode 100644 index b9255f77..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/async_client.py +++ /dev/null @@ -1,279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport -from .client import PredictionServiceClient - - -class PredictionServiceAsyncClient: - """Service for making recommendation prediction.""" - - _client: PredictionServiceClient - - DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT - - product_path = staticmethod(PredictionServiceClient.product_path) - parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) - common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(PredictionServiceClient.common_project_path) - parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) - common_location_path = staticmethod(PredictionServiceClient.common_location_path) - parse_common_location_path = staticmethod(PredictionServiceClient.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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PredictionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_predict(): - # Create a client - client = retail_v2alpha.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - request = prediction_service.PredictRequest(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.predict, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py deleted file mode 100644 index 1cb0e419..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/client.py +++ /dev/null @@ -1,480 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PredictionServiceGrpcTransport -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -class PredictionServiceClientMeta(type): - """Metaclass for the PredictionService 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[PredictionServiceTransport]] - _transport_registry["grpc"] = PredictionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PredictionServiceTransport]: - """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): - """Service for making recommendation prediction.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PredictionServiceClient: 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: - PredictionServiceClient: 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) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, PredictionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, PredictionServiceTransport): - # transport is a PredictionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_predict(): - # Create a client - client = retail_v2alpha.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a prediction_service.PredictRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_service.PredictRequest): - request = prediction_service.PredictRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.predict] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py deleted file mode 100644 index bb65c664..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PredictionServiceTransport -from .grpc import PredictionServiceGrpcTransport -from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] -_transport_registry['grpc'] = PredictionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport - -__all__ = ( - 'PredictionServiceTransport', - 'PredictionServiceGrpcTransport', - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py deleted file mode 100644 index a5424c9e..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PredictionServiceTransport(abc.ABC): - """Abstract transport class for PredictionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.predict: gapic_v1.method.wrap_method( - self.predict, - 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - Union[ - prediction_service.PredictResponse, - Awaitable[prediction_service.PredictResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PredictionServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py deleted file mode 100644 index 0e227d35..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc.py +++ /dev/null @@ -1,264 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO - - -class PredictionServiceGrpcTransport(PredictionServiceTransport): - """gRPC backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - prediction_service.PredictResponse]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - ~.PredictResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PredictionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py deleted file mode 100644 index 26a9ecfc..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import PredictionServiceGrpcTransport - - -class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): - """gRPC AsyncIO backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def predict(self) -> Callable[ - [prediction_service.PredictRequest], - Awaitable[prediction_service.PredictResponse]]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - Awaitable[~.PredictResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py deleted file mode 100644 index 0fa6330a..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ProductServiceClient -from .async_client import ProductServiceAsyncClient - -__all__ = ( - 'ProductServiceClient', - 'ProductServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py deleted file mode 100644 index 2933dcb8..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/async_client.py +++ /dev/null @@ -1,1804 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.services.product_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import purge_config -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport -from .client import ProductServiceClient - - -class ProductServiceAsyncClient: - """Service for ingesting [Product][google.cloud.retail.v2alpha.Product] - information of the customer's website. - """ - - _client: ProductServiceClient - - DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(ProductServiceClient.branch_path) - parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) - product_path = staticmethod(ProductServiceClient.product_path) - parse_product_path = staticmethod(ProductServiceClient.parse_product_path) - common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProductServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProductServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ProductServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) - common_location_path = staticmethod(ProductServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProductServiceClient.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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ProductServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ProductServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_create_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (:class:`str`): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (:class:`google.cloud.retail_v2alpha.types.Product`): - Required. The - [Product][google.cloud.retail.v2alpha.Product] to - create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (:class:`str`): - Required. The ID to use for the - [Product][google.cloud.retail.v2alpha.Product], which - will become the final component of the - [Product.name][google.cloud.retail.v2alpha.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This field must be unique among all - [Product][google.cloud.retail.v2alpha.Product]s with the - same - [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.CreateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the requested - [Product][google.cloud.retail.v2alpha.Product] 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.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.GetProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsAsyncPager: - r"""Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_list_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - parent (:class:`str`): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2alpha.Product]s under - this branch, regardless of whether or not this branch - exists, a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.product_service.pagers.ListProductsAsyncPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.ListProductsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_products, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProductsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (:class:`google.cloud.retail_v2alpha.types.Product`): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2alpha.Product] to - update. The immutable and output only fields are NOT - supported. If not set, all supported fields (the fields - that are neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.UpdateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_delete_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2alpha.Product] to - delete can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product] member - nor a - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] with more - than one - [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2alpha.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.DeleteProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def purge_products(self, - request: Union[purge_config.PurgeProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Permanently deletes all selected - [Product][google.cloud.retail.v2alpha.Product]s under a branch. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed offline. Depending on the - number of [Product][google.cloud.retail.v2alpha.Product]s, this - operation could take hours to complete. Before the operation - completes, some [Product][google.cloud.retail.v2alpha.Product]s - may still be returned by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Depending on the number of - [Product][google.cloud.retail.v2alpha.Product]s, this operation - could take hours to complete. To get a sample of - [Product][google.cloud.retail.v2alpha.Product]s that would be - deleted, set - [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] - to false. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_purge_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeProductsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PurgeProductsRequest, dict]): - The request object. Request message for PurgeProducts - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.PurgeProductsResponse` Response of the PurgeProductsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_products, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeProductsResponse, - metadata_type=purge_config.PurgeProductsMetadata, - ) - - # Done; return the response. - return response - - async def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2alpha.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2alpha.Product]s to be - successfully updated. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_import_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2alpha.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2alpha.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_set_inventory(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2alpha.Product() - inventory.title = "title_value" - - request = retail_v2alpha.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (:class:`google.cloud.retail_v2alpha.types.Product`): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product] named in - [Product.name][google.cloud.retail.v2alpha.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2alpha.Product] to - update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.SetInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_inventory, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - async def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [AddFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_add_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [AddLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_remove_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py deleted file mode 100644 index 6206989b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/client.py +++ /dev/null @@ -1,2008 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.services.product_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import purge_config -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProductServiceGrpcTransport -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -class ProductServiceClientMeta(type): - """Metaclass for the ProductService 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[ProductServiceTransport]] - _transport_registry["grpc"] = ProductServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ProductServiceTransport]: - """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 ProductServiceClient(metaclass=ProductServiceClientMeta): - """Service for ingesting [Product][google.cloud.retail.v2alpha.Product] - information of the customer's website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProductServiceClient: 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: - ProductServiceClient: 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) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProductServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ProductServiceTransport): - # transport is a ProductServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_create_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (google.cloud.retail_v2alpha.types.Product): - Required. The - [Product][google.cloud.retail.v2alpha.Product] to - create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2alpha.Product], which - will become the final component of the - [Product.name][google.cloud.retail.v2alpha.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This field must be unique among all - [Product][google.cloud.retail.v2alpha.Product]s with the - same - [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.CreateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.CreateProductRequest): - request = product_service.CreateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the requested - [Product][google.cloud.retail.v2alpha.Product] 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.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.GetProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.GetProductRequest): - request = product_service.GetProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsPager: - r"""Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_list_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2alpha.Product]s under - this branch, regardless of whether or not this branch - exists, a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.product_service.pagers.ListProductsPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.ListProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.ListProductsRequest): - request = product_service.ListProductsRequest(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_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProductsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (google.cloud.retail_v2alpha.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2alpha.Product] to - update. The immutable and output only fields are NOT - supported. If not set, all supported fields (the fields - that are neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.UpdateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.UpdateProductRequest): - request = product_service.UpdateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - 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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2alpha.Product]. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_delete_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2alpha.Product] to - delete can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product] member - nor a - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] with more - than one - [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2alpha.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.DeleteProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.DeleteProductRequest): - request = product_service.DeleteProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def purge_products(self, - request: Union[purge_config.PurgeProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Permanently deletes all selected - [Product][google.cloud.retail.v2alpha.Product]s under a branch. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed offline. Depending on the - number of [Product][google.cloud.retail.v2alpha.Product]s, this - operation could take hours to complete. Before the operation - completes, some [Product][google.cloud.retail.v2alpha.Product]s - may still be returned by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Depending on the number of - [Product][google.cloud.retail.v2alpha.Product]s, this operation - could take hours to complete. To get a sample of - [Product][google.cloud.retail.v2alpha.Product]s that would be - deleted, set - [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] - to false. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_purge_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeProductsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PurgeProductsRequest, dict]): - The request object. Request message for PurgeProducts - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.PurgeProductsResponse` Response of the PurgeProductsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeProductsRequest): - request = purge_config.PurgeProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeProductsResponse, - metadata_type=purge_config.PurgeProductsMetadata, - ) - - # Done; return the response. - return response - - def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2alpha.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2alpha.Product]s to be - successfully updated. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_import_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2alpha.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportProductsRequest): - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2alpha.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_set_inventory(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2alpha.Product() - inventory.title = "title_value" - - request = retail_v2alpha.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (google.cloud.retail_v2alpha.types.Product): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product] named in - [Product.name][google.cloud.retail.v2alpha.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2alpha.Product] to - update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.SetInventoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.SetInventoryRequest): - request = product_service.SetInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_add_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [AddFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddFulfillmentPlacesRequest): - request = product_service.AddFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): - request = product_service.RemoveFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_add_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [AddLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddLocalInventoriesRequest): - request = product_service.AddLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_remove_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveLocalInventoriesRequest): - request = product_service.RemoveLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py deleted file mode 100644 index 5e235009..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product_service - - -class ListProductsPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` - 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[..., product_service.ListProductsResponse], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2alpha.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[product_service.ListProductsResponse]: - 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[product.Product]: - for page in self.pages: - yield from page.products - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProductsAsyncPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListProductsResponse` - 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[product_service.ListProductsResponse]], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2alpha.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: - 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[product.Product]: - async def async_generator(): - async for page in self.pages: - for response in page.products: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py deleted file mode 100644 index db824dec..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ProductServiceTransport -from .grpc import ProductServiceGrpcTransport -from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] -_transport_registry['grpc'] = ProductServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport - -__all__ = ( - 'ProductServiceTransport', - 'ProductServiceGrpcTransport', - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py deleted file mode 100644 index fe69ccf2..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/base.py +++ /dev/null @@ -1,327 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import purge_config -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ProductServiceTransport(abc.ABC): - """Abstract transport class for ProductService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_product: gapic_v1.method.wrap_method( - self.create_product, - default_timeout=None, - client_info=client_info, - ), - self.get_product: gapic_v1.method.wrap_method( - self.get_product, - default_timeout=None, - client_info=client_info, - ), - self.list_products: gapic_v1.method.wrap_method( - self.list_products, - default_timeout=None, - client_info=client_info, - ), - self.update_product: gapic_v1.method.wrap_method( - self.update_product, - default_timeout=None, - client_info=client_info, - ), - self.delete_product: gapic_v1.method.wrap_method( - self.delete_product, - default_timeout=None, - client_info=client_info, - ), - self.purge_products: gapic_v1.method.wrap_method( - self.purge_products, - default_timeout=None, - client_info=client_info, - ), - self.import_products: gapic_v1.method.wrap_method( - self.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.set_inventory: gapic_v1.method.wrap_method( - self.set_inventory, - default_timeout=None, - client_info=client_info, - ), - self.add_fulfillment_places: gapic_v1.method.wrap_method( - self.add_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.remove_fulfillment_places: gapic_v1.method.wrap_method( - self.remove_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.add_local_inventories: gapic_v1.method.wrap_method( - self.add_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.remove_local_inventories: gapic_v1.method.wrap_method( - self.remove_local_inventories, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Union[ - product.Product, - Awaitable[product.Product] - ]]: - raise NotImplementedError() - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Union[ - product_service.ListProductsResponse, - Awaitable[product_service.ListProductsResponse] - ]]: - raise NotImplementedError() - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def purge_products(self) -> Callable[ - [purge_config.PurgeProductsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ProductServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py deleted file mode 100644 index 72a1777c..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc.py +++ /dev/null @@ -1,726 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import purge_config -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO - - -class ProductServiceGrpcTransport(ProductServiceTransport): - """gRPC backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2alpha.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - gcr_product.Product]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.CreateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - product.Product]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.GetProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - product_service.ListProductsResponse]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - ~.ListProductsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - gcr_product.Product]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - ~.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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def purge_products(self) -> Callable[ - [purge_config.PurgeProductsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge products method over gRPC. - - Permanently deletes all selected - [Product][google.cloud.retail.v2alpha.Product]s under a branch. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed offline. Depending on the - number of [Product][google.cloud.retail.v2alpha.Product]s, this - operation could take hours to complete. Before the operation - completes, some [Product][google.cloud.retail.v2alpha.Product]s - may still be returned by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Depending on the number of - [Product][google.cloud.retail.v2alpha.Product]s, this operation - could take hours to complete. To get a sample of - [Product][google.cloud.retail.v2alpha.Product]s that would be - deleted, set - [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] - to false. - - Returns: - Callable[[~.PurgeProductsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_products' not in self._stubs: - self._stubs['purge_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/PurgeProducts', - request_serializer=purge_config.PurgeProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_products'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2alpha.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2alpha.Product]s to be - successfully updated. - - Returns: - Callable[[~.ImportProductsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - operations_pb2.Operation]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2alpha.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProductServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py deleted file mode 100644 index f130d491..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,725 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import purge_config -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ProductServiceGrpcTransport - - -class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): - """gRPC AsyncIO backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2alpha.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.CreateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Awaitable[product.Product]]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.GetProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Awaitable[product_service.ListProductsResponse]]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2alpha.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - Awaitable[~.ListProductsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2alpha.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - 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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def purge_products(self) -> Callable[ - [purge_config.PurgeProductsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge products method over gRPC. - - Permanently deletes all selected - [Product][google.cloud.retail.v2alpha.Product]s under a branch. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed offline. Depending on the - number of [Product][google.cloud.retail.v2alpha.Product]s, this - operation could take hours to complete. Before the operation - completes, some [Product][google.cloud.retail.v2alpha.Product]s - may still be returned by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Depending on the number of - [Product][google.cloud.retail.v2alpha.Product]s, this operation - could take hours to complete. To get a sample of - [Product][google.cloud.retail.v2alpha.Product]s that would be - deleted, set - [PurgeProductsRequest.force][google.cloud.retail.v2alpha.PurgeProductsRequest.force] - to false. - - Returns: - Callable[[~.PurgeProductsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_products' not in self._stubs: - self._stubs['purge_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/PurgeProducts', - request_serializer=purge_config.PurgeProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_products'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2alpha.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2alpha.Product]s to be - successfully updated. - - Returns: - Callable[[~.ImportProductsRequest], - 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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2alpha.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2alpha.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2alpha.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - 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 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - 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 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2alpha.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - 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 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2alpha.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2alpha.Product] queried by - [GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2alpha.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2alpha.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - 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 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py deleted file mode 100644 index 2f63fc22..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SearchServiceClient -from .async_client import SearchServiceAsyncClient - -__all__ = ( - 'SearchServiceClient', - 'SearchServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py deleted file mode 100644 index d39b3203..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/async_client.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.search_service import pagers -from google.cloud.retail_v2alpha.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .client import SearchServiceClient - - -class SearchServiceAsyncClient: - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: SearchServiceClient - - DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(SearchServiceClient.branch_path) - parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) - product_path = staticmethod(SearchServiceClient.product_path) - parse_product_path = staticmethod(SearchServiceClient.parse_product_path) - common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(SearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SearchServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAsyncPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_search(): - # Create a client - client = retail_v2alpha.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.search_service.pagers.SearchAsyncPager: - Response message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py deleted file mode 100644 index 4786889b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/client.py +++ /dev/null @@ -1,513 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.search_service import pagers -from google.cloud.retail_v2alpha.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SearchServiceGrpcTransport -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -class SearchServiceClientMeta(type): - """Metaclass for the SearchService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] - _transport_registry["grpc"] = SearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SearchServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SearchServiceClient(metaclass=SearchServiceClientMeta): - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SearchServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SearchServiceTransport): - # transport is a SearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_search(): - # Create a client - client = retail_v2alpha.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.search_service.pagers.SearchPager: - Response message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a search_service.SearchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, search_service.SearchRequest): - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py deleted file mode 100644 index 7487beee..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import search_service - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., search_service.SearchResponse], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2alpha.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[search_service.SearchResponse]], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2alpha.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py deleted file mode 100644 index 7917cd1d..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SearchServiceTransport -from .grpc import SearchServiceGrpcTransport -from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] -_transport_registry['grpc'] = SearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport - -__all__ = ( - 'SearchServiceTransport', - 'SearchServiceGrpcTransport', - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py deleted file mode 100644 index f986834a..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import search_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class SearchServiceTransport(abc.ABC): - """Abstract transport class for SearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search: gapic_v1.method.wrap_method( - self.search, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Union[ - search_service.SearchResponse, - Awaitable[search_service.SearchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SearchServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py deleted file mode 100644 index 04e76b79..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc.py +++ /dev/null @@ -1,270 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO - - -class SearchServiceGrpcTransport(SearchServiceTransport): - """gRPC backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py deleted file mode 100644 index 26b52d69..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SearchServiceGrpcTransport - - -class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): - """gRPC AsyncIO backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Awaitable[search_service.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py deleted file mode 100644 index d1a0a023..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ServingConfigServiceClient -from .async_client import ServingConfigServiceAsyncClient - -__all__ = ( - 'ServingConfigServiceClient', - 'ServingConfigServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py deleted file mode 100644 index 4f047853..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py +++ /dev/null @@ -1,954 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.serving_config_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport -from .client import ServingConfigServiceClient - - -class ServingConfigServiceAsyncClient: - """Service for modifying ServingConfig.""" - - _client: ServingConfigServiceClient - - DEFAULT_ENDPOINT = ServingConfigServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ServingConfigServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(ServingConfigServiceClient.catalog_path) - parse_catalog_path = staticmethod(ServingConfigServiceClient.parse_catalog_path) - serving_config_path = staticmethod(ServingConfigServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(ServingConfigServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(ServingConfigServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ServingConfigServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ServingConfigServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ServingConfigServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ServingConfigServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ServingConfigServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ServingConfigServiceClient.common_project_path) - parse_common_project_path = staticmethod(ServingConfigServiceClient.parse_common_project_path) - common_location_path = staticmethod(ServingConfigServiceClient.common_location_path) - parse_common_location_path = staticmethod(ServingConfigServiceClient.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: - ServingConfigServiceAsyncClient: The constructed client. - """ - return ServingConfigServiceClient.from_service_account_info.__func__(ServingConfigServiceAsyncClient, 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: - ServingConfigServiceAsyncClient: The constructed client. - """ - return ServingConfigServiceClient.from_service_account_file.__func__(ServingConfigServiceAsyncClient, 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 variabel 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 ServingConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ServingConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ServingConfigServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ServingConfigServiceClient).get_transport_class, type(ServingConfigServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ServingConfigServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the serving config service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ServingConfigServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ServingConfigServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_serving_config(self, - request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, - *, - parent: str = None, - serving_config: gcr_serving_config.ServingConfig = None, - serving_config_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_create_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = await client.create_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateServingConfigRequest, dict]): - The request object. Request for CreateServingConfig - method. - parent (:class:`str`): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config (:class:`google.cloud.retail_v2alpha.types.ServingConfig`): - Required. The ServingConfig to - create. - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config_id (:class:`str`): - Required. The ID to use for the ServingConfig, which - will become the final component of the ServingConfig's - resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``serving_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, serving_config, serving_config_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.CreateServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if serving_config is not None: - request.serving_config = serving_config - if serving_config_id is not None: - request.serving_config_id = serving_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_serving_config(self, - request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_delete_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_serving_config(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteServingConfigRequest, dict]): - The request object. Request for DeleteServingConfig - method. - name (:class:`str`): - Required. The resource name of the ServingConfig to - delete. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.DeleteServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_serving_config(self, - request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, - *, - serving_config: gcr_serving_config.ServingConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Updates a ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_update_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = await client.update_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateServingConfigRequest, dict]): - The request object. Request for UpdateServingConfig - method. - serving_config (:class:`google.cloud.retail_v2alpha.types.ServingConfig`): - Required. The ServingConfig to - update. - - This corresponds to the ``serving_config`` 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 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.UpdateServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config.name", request.serving_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_serving_config(self, - request: Union[serving_config_service.GetServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> serving_config.ServingConfig: - r"""Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_get_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetServingConfigRequest, dict]): - The request object. Request for GetServingConfig method. - name (:class:`str`): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.GetServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_serving_configs(self, - request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServingConfigsAsyncPager: - r"""Lists all ServingConfigs linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_list_serving_configs(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListServingConfigsRequest, dict]): - The request object. Request for ListServingConfigs - method. - parent (:class:`str`): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsAsyncPager: - Response for ListServingConfigs - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.ListServingConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_serving_configs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListServingConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def add_control(self, - request: Union[serving_config_service.AddControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_add_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.add_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddControlRequest, dict]): - The request object. Request for AddControl method. - serving_config (:class:`str`): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.AddControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def remove_control(self, - request: Union[serving_config_service.RemoveControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_remove_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.remove_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveControlRequest, dict]): - The request object. Request for RemoveControl method. - serving_config (:class:`str`): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.RemoveControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServingConfigServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py deleted file mode 100644 index d9d8e276..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/client.py +++ /dev/null @@ -1,1163 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2alpha.services.serving_config_service import pagers -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ServingConfigServiceGrpcTransport -from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport - - -class ServingConfigServiceClientMeta(type): - """Metaclass for the ServingConfigService 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[ServingConfigServiceTransport]] - _transport_registry["grpc"] = ServingConfigServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ServingConfigServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ServingConfigServiceTransport]: - """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 ServingConfigServiceClient(metaclass=ServingConfigServiceClientMeta): - """Service for modifying ServingConfig.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServingConfigServiceClient: 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: - ServingConfigServiceClient: 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) -> ServingConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ServingConfigServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,catalog: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ServingConfigServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the serving config service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ServingConfigServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ServingConfigServiceTransport): - # transport is a ServingConfigServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_serving_config(self, - request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, - *, - parent: str = None, - serving_config: gcr_serving_config.ServingConfig = None, - serving_config_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_create_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = client.create_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CreateServingConfigRequest, dict]): - The request object. Request for CreateServingConfig - method. - parent (str): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config (google.cloud.retail_v2alpha.types.ServingConfig): - Required. The ServingConfig to - create. - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config_id (str): - Required. The ID to use for the ServingConfig, which - will become the final component of the ServingConfig's - resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``serving_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, serving_config, serving_config_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.CreateServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.CreateServingConfigRequest): - request = serving_config_service.CreateServingConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if serving_config is not None: - request.serving_config = serving_config - if serving_config_id is not None: - request.serving_config_id = serving_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_serving_config(self, - request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_delete_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_serving_config(request=request) - - Args: - request (Union[google.cloud.retail_v2alpha.types.DeleteServingConfigRequest, dict]): - The request object. Request for DeleteServingConfig - method. - name (str): - Required. The resource name of the ServingConfig to - delete. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.DeleteServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.DeleteServingConfigRequest): - request = serving_config_service.DeleteServingConfigRequest(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_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_serving_config(self, - request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, - *, - serving_config: gcr_serving_config.ServingConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Updates a ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_update_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = client.update_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.UpdateServingConfigRequest, dict]): - The request object. Request for UpdateServingConfig - method. - serving_config (google.cloud.retail_v2alpha.types.ServingConfig): - Required. The ServingConfig to - update. - - This corresponds to the ``serving_config`` 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 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.UpdateServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.UpdateServingConfigRequest): - request = serving_config_service.UpdateServingConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config.name", request.serving_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_serving_config(self, - request: Union[serving_config_service.GetServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> serving_config.ServingConfig: - r"""Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_get_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.GetServingConfigRequest, dict]): - The request object. Request for GetServingConfig method. - name (str): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.GetServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.GetServingConfigRequest): - request = serving_config_service.GetServingConfigRequest(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_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_serving_configs(self, - request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServingConfigsPager: - r"""Lists all ServingConfigs linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_list_serving_configs(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ListServingConfigsRequest, dict]): - The request object. Request for ListServingConfigs - method. - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsPager: - Response for ListServingConfigs - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.ListServingConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.ListServingConfigsRequest): - request = serving_config_service.ListServingConfigsRequest(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_serving_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListServingConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def add_control(self, - request: Union[serving_config_service.AddControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_add_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.add_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.AddControlRequest, dict]): - The request object. Request for AddControl method. - serving_config (str): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.AddControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.AddControlRequest): - request = serving_config_service.AddControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def remove_control(self, - request: Union[serving_config_service.RemoveControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_remove_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.remove_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RemoveControlRequest, dict]): - The request object. Request for RemoveControl method. - serving_config (str): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.RemoveControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.RemoveControlRequest): - request = serving_config_service.RemoveControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServingConfigServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py deleted file mode 100644 index 8c4975b7..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config_service - - -class ListServingConfigsPager: - """A pager for iterating through ``list_serving_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``serving_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServingConfigs`` requests and continue to iterate - through the ``serving_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` - 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[..., serving_config_service.ListServingConfigsResponse], - request: serving_config_service.ListServingConfigsRequest, - response: serving_config_service.ListServingConfigsResponse, - *, - 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.retail_v2alpha.types.ListServingConfigsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListServingConfigsResponse): - 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 = serving_config_service.ListServingConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[serving_config_service.ListServingConfigsResponse]: - 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[serving_config.ServingConfig]: - for page in self.pages: - yield from page.serving_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServingConfigsAsyncPager: - """A pager for iterating through ``list_serving_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``serving_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServingConfigs`` requests and continue to iterate - through the ``serving_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2alpha.types.ListServingConfigsResponse` - 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[serving_config_service.ListServingConfigsResponse]], - request: serving_config_service.ListServingConfigsRequest, - response: serving_config_service.ListServingConfigsResponse, - *, - 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.retail_v2alpha.types.ListServingConfigsRequest): - The initial request object. - response (google.cloud.retail_v2alpha.types.ListServingConfigsResponse): - 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 = serving_config_service.ListServingConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[serving_config_service.ListServingConfigsResponse]: - 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[serving_config.ServingConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.serving_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py deleted file mode 100644 index 3726ac83..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ServingConfigServiceTransport -from .grpc import ServingConfigServiceGrpcTransport -from .grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ServingConfigServiceTransport]] -_transport_registry['grpc'] = ServingConfigServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ServingConfigServiceGrpcAsyncIOTransport - -__all__ = ( - 'ServingConfigServiceTransport', - 'ServingConfigServiceGrpcTransport', - 'ServingConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py deleted file mode 100644 index 94052dd6..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ServingConfigServiceTransport(abc.ABC): - """Abstract transport class for ServingConfigService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_serving_config: gapic_v1.method.wrap_method( - self.create_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_serving_config: gapic_v1.method.wrap_method( - self.delete_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.update_serving_config: gapic_v1.method.wrap_method( - self.update_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.get_serving_config: gapic_v1.method.wrap_method( - self.get_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.list_serving_configs: gapic_v1.method.wrap_method( - self.list_serving_configs, - default_timeout=None, - client_info=client_info, - ), - self.add_control: gapic_v1.method.wrap_method( - self.add_control, - default_timeout=None, - client_info=client_info, - ), - self.remove_control: gapic_v1.method.wrap_method( - self.remove_control, - 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 create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - Union[ - serving_config.ServingConfig, - Awaitable[serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - Union[ - serving_config_service.ListServingConfigsResponse, - Awaitable[serving_config_service.ListServingConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ServingConfigServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py deleted file mode 100644 index 0acec25b..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc.py +++ /dev/null @@ -1,440 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO - - -class ServingConfigServiceGrpcTransport(ServingConfigServiceTransport): - """gRPC backend transport for ServingConfigService. - - Service for modifying ServingConfig. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the create serving config method over gRPC. - - Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - Returns: - Callable[[~.CreateServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/CreateServingConfig', - request_serializer=serving_config_service.CreateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['create_serving_config'] - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete serving config method over gRPC. - - Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.DeleteServingConfigRequest], - ~.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_serving_config' not in self._stubs: - self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/DeleteServingConfig', - request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_serving_config'] - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the update serving config method over gRPC. - - Updates a ServingConfig. - - Returns: - Callable[[~.UpdateServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/UpdateServingConfig', - request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['update_serving_config'] - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - serving_config.ServingConfig]: - r"""Return a callable for the get serving config method over gRPC. - - Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.GetServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/GetServingConfig', - request_serializer=serving_config_service.GetServingConfigRequest.serialize, - response_deserializer=serving_config.ServingConfig.deserialize, - ) - return self._stubs['get_serving_config'] - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - serving_config_service.ListServingConfigsResponse]: - r"""Return a callable for the list serving configs method over gRPC. - - Lists all ServingConfigs linked to this catalog. - - Returns: - Callable[[~.ListServingConfigsRequest], - ~.ListServingConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: - self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/ListServingConfigs', - request_serializer=serving_config_service.ListServingConfigsRequest.serialize, - response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, - ) - return self._stubs['list_serving_configs'] - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the add control method over gRPC. - - Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - Returns: - Callable[[~.AddControlRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_control' not in self._stubs: - self._stubs['add_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/AddControl', - request_serializer=serving_config_service.AddControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['add_control'] - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the remove control method over gRPC. - - Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - Returns: - Callable[[~.RemoveControlRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_control' not in self._stubs: - self._stubs['remove_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/RemoveControl', - request_serializer=serving_config_service.RemoveControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['remove_control'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ServingConfigServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py deleted file mode 100644 index e3d2ccca..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,439 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ServingConfigServiceGrpcTransport - - -class ServingConfigServiceGrpcAsyncIOTransport(ServingConfigServiceTransport): - """gRPC AsyncIO backend transport for ServingConfigService. - - Service for modifying ServingConfig. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the create serving config method over gRPC. - - Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2alpha.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - Returns: - Callable[[~.CreateServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/CreateServingConfig', - request_serializer=serving_config_service.CreateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['create_serving_config'] - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete serving config method over gRPC. - - Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.DeleteServingConfigRequest], - 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_serving_config' not in self._stubs: - self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/DeleteServingConfig', - request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_serving_config'] - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the update serving config method over gRPC. - - Updates a ServingConfig. - - Returns: - Callable[[~.UpdateServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/UpdateServingConfig', - request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['update_serving_config'] - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - Awaitable[serving_config.ServingConfig]]: - r"""Return a callable for the get serving config method over gRPC. - - Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.GetServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/GetServingConfig', - request_serializer=serving_config_service.GetServingConfigRequest.serialize, - response_deserializer=serving_config.ServingConfig.deserialize, - ) - return self._stubs['get_serving_config'] - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - Awaitable[serving_config_service.ListServingConfigsResponse]]: - r"""Return a callable for the list serving configs method over gRPC. - - Lists all ServingConfigs linked to this catalog. - - Returns: - Callable[[~.ListServingConfigsRequest], - Awaitable[~.ListServingConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: - self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/ListServingConfigs', - request_serializer=serving_config_service.ListServingConfigsRequest.serialize, - response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, - ) - return self._stubs['list_serving_configs'] - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the add control method over gRPC. - - Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - Returns: - Callable[[~.AddControlRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_control' not in self._stubs: - self._stubs['add_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/AddControl', - request_serializer=serving_config_service.AddControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['add_control'] - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the remove control method over gRPC. - - Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - Returns: - Callable[[~.RemoveControlRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_control' not in self._stubs: - self._stubs['remove_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.ServingConfigService/RemoveControl', - request_serializer=serving_config_service.RemoveControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['remove_control'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ServingConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py deleted file mode 100644 index 5f5171c1..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py deleted file mode 100644 index 1f08ee18..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/async_client.py +++ /dev/null @@ -1,730 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on the customer - website. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(UserEventServiceClient.catalog_path) - parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) - product_path = staticmethod(UserEventServiceClient.product_path) - parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_write_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_collect_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_purge_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_import_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2alpha.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - async def sample_rejoin_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py deleted file mode 100644 index 98d272ff..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/client.py +++ /dev/null @@ -1,930 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[UserEventServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on the customer - website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_write_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2alpha.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_collect_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_purge_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeUserEventsRequest): - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_import_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2alpha.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportUserEventsRequest): - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2alpha - - def sample_rejoin_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2alpha.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2alpha.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.RejoinUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.RejoinUserEventsRequest): - request = user_event_service.RejoinUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py deleted file mode 100644 index f53ee5d7..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py deleted file mode 100644 index efd2f034..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py +++ /dev/null @@ -1,235 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_timeout=None, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_timeout=None, - client_info=client_info, - ), - self.purge_user_events: gapic_v1.method.wrap_method( - self.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.rejoin_user_events: gapic_v1.method.wrap_method( - self.rejoin_user_events, - 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 write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - user_event.UserEvent, - Awaitable[user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py deleted file mode 100644 index 3ca23eca..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index 72c6083a..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - 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 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2alpha.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py deleted file mode 100644 index aa87618d..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/__init__.py +++ /dev/null @@ -1,284 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .catalog import ( - AttributesConfig, - Catalog, - CatalogAttribute, - CompletionConfig, - MerchantCenterLink, - MerchantCenterLinkingConfig, - ProductLevelConfig, -) -from .catalog_service import ( - AddCatalogAttributeRequest, - GetAttributesConfigRequest, - GetCompletionConfigRequest, - GetDefaultBranchRequest, - GetDefaultBranchResponse, - ListCatalogsRequest, - ListCatalogsResponse, - RemoveCatalogAttributeRequest, - ReplaceCatalogAttributeRequest, - SetDefaultBranchRequest, - UpdateAttributesConfigRequest, - UpdateCatalogRequest, - UpdateCompletionConfigRequest, -) -from .common import ( - Audience, - ColorInfo, - Condition, - CustomAttribute, - FulfillmentInfo, - Image, - Interval, - LocalInventory, - PriceInfo, - Rating, - Rule, - UserInfo, - AttributeConfigLevel, - SearchSolutionUseCase, - SolutionType, -) -from .completion_service import ( - CompleteQueryRequest, - CompleteQueryResponse, -) -from .control import ( - Control, -) -from .control_service import ( - CreateControlRequest, - DeleteControlRequest, - GetControlRequest, - ListControlsRequest, - ListControlsResponse, - UpdateControlRequest, -) -from .export_config import ( - ExportErrorsConfig, - ExportMetadata, - ExportProductsResponse, - ExportUserEventsResponse, -) -from .import_config import ( - BigQuerySource, - CompletionDataInputConfig, - GcsSource, - ImportCompletionDataRequest, - ImportCompletionDataResponse, - ImportErrorsConfig, - ImportMetadata, - ImportProductsRequest, - ImportProductsResponse, - ImportUserEventsRequest, - ImportUserEventsResponse, - ProductInlineSource, - ProductInputConfig, - UserEventImportSummary, - UserEventInlineSource, - UserEventInputConfig, -) -from .prediction_service import ( - PredictRequest, - PredictResponse, -) -from .product import ( - Product, -) -from .product_service import ( - AddFulfillmentPlacesMetadata, - AddFulfillmentPlacesRequest, - AddFulfillmentPlacesResponse, - AddLocalInventoriesMetadata, - AddLocalInventoriesRequest, - AddLocalInventoriesResponse, - CreateProductRequest, - DeleteProductRequest, - GetProductRequest, - ListProductsRequest, - ListProductsResponse, - RemoveFulfillmentPlacesMetadata, - RemoveFulfillmentPlacesRequest, - RemoveFulfillmentPlacesResponse, - RemoveLocalInventoriesMetadata, - RemoveLocalInventoriesRequest, - RemoveLocalInventoriesResponse, - SetInventoryMetadata, - SetInventoryRequest, - SetInventoryResponse, - UpdateProductRequest, -) -from .promotion import ( - Promotion, -) -from .purge_config import ( - PurgeMetadata, - PurgeProductsMetadata, - PurgeProductsRequest, - PurgeProductsResponse, - PurgeUserEventsRequest, - PurgeUserEventsResponse, -) -from .search_service import ( - SearchRequest, - SearchResponse, -) -from .serving_config import ( - ServingConfig, -) -from .serving_config_service import ( - AddControlRequest, - CreateServingConfigRequest, - DeleteServingConfigRequest, - GetServingConfigRequest, - ListServingConfigsRequest, - ListServingConfigsResponse, - RemoveControlRequest, - UpdateServingConfigRequest, -) -from .user_event import ( - CompletionDetail, - ProductDetail, - PurchaseTransaction, - UserEvent, -) -from .user_event_service import ( - CollectUserEventRequest, - RejoinUserEventsMetadata, - RejoinUserEventsRequest, - RejoinUserEventsResponse, - WriteUserEventRequest, -) - -__all__ = ( - 'AttributesConfig', - 'Catalog', - 'CatalogAttribute', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'ProductLevelConfig', - 'AddCatalogAttributeRequest', - 'GetAttributesConfigRequest', - 'GetCompletionConfigRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - 'SetDefaultBranchRequest', - 'UpdateAttributesConfigRequest', - 'UpdateCatalogRequest', - 'UpdateCompletionConfigRequest', - 'Audience', - 'ColorInfo', - 'Condition', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'Rule', - 'UserInfo', - 'AttributeConfigLevel', - 'SearchSolutionUseCase', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Control', - 'CreateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - 'UpdateControlRequest', - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeProductsMetadata', - 'PurgeProductsRequest', - 'PurgeProductsResponse', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'ServingConfig', - 'AddControlRequest', - 'CreateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'RemoveControlRequest', - 'UpdateServingConfigRequest', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py deleted file mode 100644 index 1e4a7ab5..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog.py +++ /dev/null @@ -1,528 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'ProductLevelConfig', - 'CatalogAttribute', - 'AttributesConfig', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'Catalog', - }, -) - - -class ProductLevelConfig(proto.Message): - r"""Configures what level the product should be uploaded with - regards to how users will be send events and how predictions - will be made. - - Attributes: - ingestion_product_type (str): - The type of [Product][google.cloud.retail.v2alpha.Product]s - allowed to be ingested into the catalog. Acceptable values - are: - - - ``primary`` (default): You can ingest - [Product][google.cloud.retail.v2alpha.Product]s of all - types. When ingesting a - [Product][google.cloud.retail.v2alpha.Product], its type - will default to - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - if unset. - - ``variant``: You can only ingest - [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s. This - means - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] - cannot be empty. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``variant`` and - [merchant_center_product_id_field][google.cloud.retail.v2alpha.ProductLevelConfig.merchant_center_product_id_field] - is ``itemGroupId``, an INVALID_ARGUMENT error is returned. - - See `Using product - levels `__ - for more details. - merchant_center_product_id_field (str): - Which field of `Merchant Center - Product `__ - should be imported as - [Product.id][google.cloud.retail.v2alpha.Product.id]. - Acceptable values are: - - - ``offerId`` (default): Import ``offerId`` as the product - ID. - - ``itemGroupId``: Import ``itemGroupId`` as the product - ID. Notice that Retail API will choose one item from the - ones with the same ``itemGroupId``, and use it to - represent the item group. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``itemGroupId`` and - [ingestion_product_type][google.cloud.retail.v2alpha.ProductLevelConfig.ingestion_product_type] - is ``variant``, an INVALID_ARGUMENT error is returned. - - See `Using product - levels `__ - for more details. - """ - - ingestion_product_type = proto.Field( - proto.STRING, - number=1, - ) - merchant_center_product_id_field = proto.Field( - proto.STRING, - number=2, - ) - - -class CatalogAttribute(proto.Message): - r"""Catalog level attribute config for an attribute. For example, - if customers want to enable/disable facet for a specific - attribute. - - Attributes: - key (str): - Required. Attribute name. For example: ``color``, - ``brands``, ``attributes.custom_attribute``, such as - ``attributes.xyz``. - in_use (bool): - Output only. Indicates whether this attribute has been used - by any products. ``True`` if at least one - [Product][google.cloud.retail.v2alpha.Product] is using this - attribute in - [Product.attributes][google.cloud.retail.v2alpha.Product.attributes]. - Otherwise, this field is ``False``. - - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - can be pre-loaded by using [AddCatalogAttribute][], - [ImportCatalogAttributes][], or [UpdateAttributesConfig][] - APIs. This field is ``False`` for pre-loaded - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s. - - Only - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s - that are not in use by products can be deleted. - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]s - that are in use by products cannot be deleted; however, - their configuration properties will reset to default values - upon removal request. - - After catalog changes, it takes about 10 minutes for this - field to update. - type_ (google.cloud.retail_v2alpha.types.CatalogAttribute.AttributeType): - Output only. The type of this attribute. This is derived - from the attribute in - [Product.attributes][google.cloud.retail.v2alpha.Product.attributes]. - indexable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.IndexableOption): - When - [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] - is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if INDEXABLE_ENABLED - attribute values are indexed so that it can be filtered, - faceted, or boosted in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - dynamic_facetable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.DynamicFacetableOption): - If DYNAMIC_FACETABLE_ENABLED, attribute values are available - for dynamic facet. Could only be DYNAMIC_FACETABLE_DISABLED - if - [CatalogAttribute.indexable_option][google.cloud.retail.v2alpha.CatalogAttribute.indexable_option] - is INDEXABLE_DISABLED. Otherwise, an INVALID_ARGUMENT error - is returned. - searchable_option (google.cloud.retail_v2alpha.types.CatalogAttribute.SearchableOption): - When - [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] - is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if SEARCHABLE_ENABLED, - attribute values are searchable by text queries in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - If SEARCHABLE_ENABLED but attribute type is numerical, - attribute values will not be searchable by text queries in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search], - as there are no text values associated to numerical - attributes. - """ - class AttributeType(proto.Enum): - r"""The type of an attribute.""" - UNKNOWN = 0 - TEXTUAL = 1 - NUMERICAL = 2 - - class IndexableOption(proto.Enum): - r"""The status of the indexable option of a catalog attribute.""" - INDEXABLE_OPTION_UNSPECIFIED = 0 - INDEXABLE_ENABLED = 1 - INDEXABLE_DISABLED = 2 - - class DynamicFacetableOption(proto.Enum): - r"""The status of the dynamic facetable option of a catalog - attribute. - """ - DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 - DYNAMIC_FACETABLE_ENABLED = 1 - DYNAMIC_FACETABLE_DISABLED = 2 - - class SearchableOption(proto.Enum): - r"""The status of the searchable option of a catalog attribute.""" - SEARCHABLE_OPTION_UNSPECIFIED = 0 - SEARCHABLE_ENABLED = 1 - SEARCHABLE_DISABLED = 2 - - key = proto.Field( - proto.STRING, - number=1, - ) - in_use = proto.Field( - proto.BOOL, - number=9, - ) - type_ = proto.Field( - proto.ENUM, - number=10, - enum=AttributeType, - ) - indexable_option = proto.Field( - proto.ENUM, - number=5, - enum=IndexableOption, - ) - dynamic_facetable_option = proto.Field( - proto.ENUM, - number=6, - enum=DynamicFacetableOption, - ) - searchable_option = proto.Field( - proto.ENUM, - number=7, - enum=SearchableOption, - ) - - -class AttributesConfig(proto.Message): - r"""Catalog level attribute config. - - Attributes: - name (str): - Required. Immutable. The fully qualified resource name of - the attribute config. Format: - ``projects/*/locations/*/catalogs/*/attributesConfig`` - catalog_attributes (Mapping[str, google.cloud.retail_v2alpha.types.CatalogAttribute]): - Enable attribute(s) config at catalog level. For example, - indexable, dynamic_facetable, or searchable for each - attribute. - - The key is catalog attribute's name. For example: ``color``, - ``brands``, ``attributes.custom_attribute``, such as - ``attributes.xyz``. - - The maximum number of catalog attributes allowed in a - request is 1000. - attribute_config_level (google.cloud.retail_v2alpha.types.AttributeConfigLevel): - Output only. The - [AttributeConfigLevel][google.cloud.retail.v2alpha.AttributeConfigLevel] - used for this catalog. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - catalog_attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='CatalogAttribute', - ) - attribute_config_level = proto.Field( - proto.ENUM, - number=3, - enum=common.AttributeConfigLevel, - ) - - -class CompletionConfig(proto.Message): - r"""Catalog level autocomplete config for customers to customize - autocomplete feature's settings. - - Attributes: - name (str): - Required. Immutable. Fully qualified name - ``projects/*/locations/*/catalogs/*/completionConfig`` - matching_order (str): - Specifies the matching order for autocomplete suggestions, - e.g., a query consisting of 'sh' with 'out-of-order' - specified would suggest "women's shoes", whereas a query of - 'red s' with 'exact-prefix' specified would suggest "red - shoes". Currently supported values: - - - 'out-of-order' - - 'exact-prefix' - - Default value: 'exact-prefix'. - max_suggestions (int): - The maximum number of autocomplete - suggestions returned per term. The maximum - allowed max suggestions is 20. Default value is - 20. If left unset or set to 0, then will - fallback to default value. - min_prefix_length (int): - The minimum number of characters needed to be - typed in order to get suggestions. Default value - is 2. If left unset or set to 0, then will - fallback to default value. - auto_learning (bool): - If set to true, the auto learning function is enabled. Auto - learning uses user data to generate suggestions using ML - techniques. Default value is false. Only after enabling auto - learning can users use ``cloud-retail`` data in - [CompleteQueryRequest][google.cloud.retail.v2alpha.CompleteQueryRequest]. - suggestions_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the - autocomplete phrases uploaded by the customer. - last_suggestions_import_operation (str): - Output only. Name of the LRO corresponding to the latest - suggestion terms list import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - denylist_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the / - autocomplete denylist phrases uploaded by the - customer. - last_denylist_import_operation (str): - Output only. LRO corresponding to the latest denylist - import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - allowlist_input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the - autocomplete allowlist phrases uploaded by the - customer. - last_allowlist_import_operation (str): - Output only. LRO corresponding to the latest allowlist - import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - matching_order = proto.Field( - proto.STRING, - number=2, - ) - max_suggestions = proto.Field( - proto.INT32, - number=3, - ) - min_prefix_length = proto.Field( - proto.INT32, - number=4, - ) - auto_learning = proto.Field( - proto.BOOL, - number=11, - ) - suggestions_input_config = proto.Field( - proto.MESSAGE, - number=5, - message=import_config.CompletionDataInputConfig, - ) - last_suggestions_import_operation = proto.Field( - proto.STRING, - number=6, - ) - denylist_input_config = proto.Field( - proto.MESSAGE, - number=7, - message=import_config.CompletionDataInputConfig, - ) - last_denylist_import_operation = proto.Field( - proto.STRING, - number=8, - ) - allowlist_input_config = proto.Field( - proto.MESSAGE, - number=9, - message=import_config.CompletionDataInputConfig, - ) - last_allowlist_import_operation = proto.Field( - proto.STRING, - number=10, - ) - - -class MerchantCenterLink(proto.Message): - r"""Represents a link between a Merchant Center account and a - branch. Once a link is established, products from the linked - merchant center account will be streamed to the linked branch. - - Attributes: - merchant_center_account_id (int): - Required. The linked `Merchant center account - id `__. - The account must be a standalone account or a sub-account of - a MCA. - branch_id (str): - The branch id (e.g. 0/1/2) within this catalog that products - from merchant_center_account_id are streamed to. When - updating this field, an empty value will use the currently - configured default branch. However, changing the default - branch later on won't change the linked branch here. - - A single branch id can only have one linked merchant center - account id. - destinations (Sequence[str]): - String representing the destination to import for, all if - left empty. List of possible values can be found here. - [https://support.google.com/merchants/answer/7501026] List - of allowed string values: "Shopping_ads", - "Buy_on_google_listings", "Display_ads", "Local_inventory - \_ads", "Free_listings", "Free_local_listings" NOTE: The - string values are case sensitive. - region_code (str): - Region code of offers to accept. 2-letter Uppercase ISO - 3166-1 alpha-2 code. List of values can be found - `here `__ - under the ``region`` tag. If left blank no region filtering - will be performed. - - Example value: ``US``. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. ISO - 639-1. - - This specifies the language of offers in Merchant Center - that will be accepted. If empty no language filtering will - be performed. - - Example value: ``en``. - """ - - merchant_center_account_id = proto.Field( - proto.INT64, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - destinations = proto.RepeatedField( - proto.STRING, - number=3, - ) - region_code = proto.Field( - proto.STRING, - number=4, - ) - language_code = proto.Field( - proto.STRING, - number=5, - ) - - -class MerchantCenterLinkingConfig(proto.Message): - r"""Configures Merchant Center linking. - Links contained in the config will be used to sync data from a - Merchant Center account to a Cloud Retail branch. - - Attributes: - links (Sequence[google.cloud.retail_v2alpha.types.MerchantCenterLink]): - Links between Merchant Center accounts and - branches. - """ - - links = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='MerchantCenterLink', - ) - - -class Catalog(proto.Message): - r"""The catalog configuration. - - Attributes: - name (str): - Required. Immutable. The fully qualified - resource name of the catalog. - display_name (str): - Required. Immutable. The catalog display name. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - product_level_config (google.cloud.retail_v2alpha.types.ProductLevelConfig): - Required. The product level configuration. - merchant_center_linking_config (google.cloud.retail_v2alpha.types.MerchantCenterLinkingConfig): - The Merchant Center linking configuration. - Once a link is added, the data stream from - Merchant Center to Cloud Retail will be enabled - automatically. The requester must have access to - the merchant center account in order to make - changes to this field. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - product_level_config = proto.Field( - proto.MESSAGE, - number=4, - message='ProductLevelConfig', - ) - merchant_center_linking_config = proto.Field( - proto.MESSAGE, - number=6, - message='MerchantCenterLinkingConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py deleted file mode 100644 index 21d9b1c2..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/catalog_service.py +++ /dev/null @@ -1,453 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'UpdateCatalogRequest', - 'SetDefaultBranchRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'GetCompletionConfigRequest', - 'UpdateCompletionConfigRequest', - 'GetAttributesConfigRequest', - 'UpdateAttributesConfigRequest', - 'AddCatalogAttributeRequest', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - }, -) - - -class ListCatalogsRequest(proto.Message): - r"""Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - - Attributes: - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2alpha.Catalog]s under this - location, regardless of whether or not this location exists, - a PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of - [Catalog][google.cloud.retail.v2alpha.Catalog]s to return. - If unspecified, defaults to 50. The maximum allowed value is - 1000. Values above 1000 will be coerced to 1000. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [ListCatalogsResponse.next_page_token][google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token], - received from a previous - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListCatalogsResponse(proto.Message): - r"""Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2alpha.CatalogService.ListCatalogs] - method. - - Attributes: - catalogs (Sequence[google.cloud.retail_v2alpha.types.Catalog]): - All the customer's - [Catalog][google.cloud.retail.v2alpha.Catalog]s. - next_page_token (str): - A token that can be sent as - [ListCatalogsRequest.page_token][google.cloud.retail.v2alpha.ListCatalogsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - catalogs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateCatalogRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2alpha.CatalogService.UpdateCatalog] - method. - - Attributes: - catalog (google.cloud.retail_v2alpha.types.Catalog): - Required. The [Catalog][google.cloud.retail.v2alpha.Catalog] - to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2alpha.Catalog], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2alpha.Catalog] 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 - [Catalog][google.cloud.retail.v2alpha.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - catalog = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class SetDefaultBranchRequest(proto.Message): - r"""Request message to set a specified branch as new default_branch. - - Attributes: - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - branch_id (str): - The final component of the resource name of a branch. - - This field must be one of "0", "1" or "2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If there are no sufficient active products in the targeted - branch and - [force][google.cloud.retail.v2alpha.SetDefaultBranchRequest.force] - is not set, a FAILED_PRECONDITION error is returned. - note (str): - Some note on this request, this can be retrieved by - [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch] - before next valid default branch set occurs. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - force (bool): - If set to true, it permits switching to a branch with - [branch_id][google.cloud.retail.v2alpha.SetDefaultBranchRequest.branch_id] - even if it has no sufficient active products. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - force = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetDefaultBranchRequest(proto.Message): - r"""Request message to show which branch is currently the default - branch. - - Attributes: - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - - -class GetDefaultBranchResponse(proto.Message): - r"""Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch]. - - Attributes: - branch (str): - Full resource name of the branch id currently - set as default branch. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when this branch is set to default. - note (str): - This corresponds to - [SetDefaultBranchRequest.note][google.cloud.retail.v2alpha.SetDefaultBranchRequest.note] - field, when this branch was set as default. - """ - - branch = proto.Field( - proto.STRING, - number=1, - ) - set_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - - -class GetCompletionConfigRequest(proto.Message): - r"""Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig] - method. - - Attributes: - name (str): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateCompletionConfigRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig] - method. - - Attributes: - completion_config (google.cloud.retail_v2alpha.types.CompletionConfig): - Required. The - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - 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 - [CompletionConfig][google.cloud.retail.v2alpha.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2alpha.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2alpha.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - """ - - completion_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.CompletionConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetAttributesConfigRequest(proto.Message): - r"""Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig] - method. - - Attributes: - name (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateAttributesConfigRequest(proto.Message): - r"""Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig] - method. - - Attributes: - attributes_config (google.cloud.retail_v2alpha.types.AttributesConfig): - Required. The - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - """ - - attributes_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.AttributesConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class AddCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - catalog_attribute (google.cloud.retail_v2alpha.types.CatalogAttribute): - Required. The - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to add. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - catalog_attribute = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_catalog.CatalogAttribute, - ) - - -class RemoveCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - key (str): - Required. The attribute name key of the - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to remove. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - key = proto.Field( - proto.STRING, - number=2, - ) - - -class ReplaceCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - catalog_attribute (google.cloud.retail_v2alpha.types.CatalogAttribute): - Required. The updated - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute]. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - to update. The following are NOT supported: - - - [CatalogAttribute.key][google.cloud.retail.v2alpha.CatalogAttribute.key] - - If not set, all supported fields are updated. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - catalog_attribute = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_catalog.CatalogAttribute, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py deleted file mode 100644 index 25fa2861..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/common.py +++ /dev/null @@ -1,1179 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'AttributeConfigLevel', - 'SolutionType', - 'SearchSolutionUseCase', - 'Condition', - 'Rule', - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'LocalInventory', - }, -) - - -class AttributeConfigLevel(proto.Enum): - r"""At which level we offer configuration for attributes.""" - ATTRIBUTE_CONFIG_LEVEL_UNSPECIFIED = 0 - PRODUCT_LEVEL_ATTRIBUTE_CONFIG = 1 - CATALOG_LEVEL_ATTRIBUTE_CONFIG = 2 - - -class SolutionType(proto.Enum): - r"""The type of solution.""" - SOLUTION_TYPE_UNSPECIFIED = 0 - SOLUTION_TYPE_RECOMMENDATION = 1 - SOLUTION_TYPE_SEARCH = 2 - - -class SearchSolutionUseCase(proto.Enum): - r"""The use case of Cloud Retail Search.""" - SEARCH_SOLUTION_USE_CASE_UNSPECIFIED = 0 - SEARCH_SOLUTION_USE_CASE_SEARCH = 1 - SEARCH_SOLUTION_USE_CASE_BROWSE = 2 - - -class Condition(proto.Message): - r"""Metadata that is used to define a condition that triggers an action. - A valid condition must specify at least one of 'query_terms' or - 'products_filter'. If multiple fields are specified, the condition - is met if all the fields are satisfied e.g. if a set of query terms - and product_filter are set, then only items matching the - product_filter for requests with a query matching the query terms - wil get boosted. - - Attributes: - query_terms (Sequence[google.cloud.retail_v2alpha.types.Condition.QueryTerm]): - A list (up to 10 entries) of terms to match - the query on. If not specified, match all - queries. If many query terms are specified, the - condition is matched if any of the terms is a - match (i.e. using the OR operator). - active_time_range (Sequence[google.cloud.retail_v2alpha.types.Condition.TimeRange]): - Range of time(s) specifying when Condition is - active. Condition true if any time range - matches. - """ - - class QueryTerm(proto.Message): - r"""Query terms that we want to match on. - - Attributes: - value (str): - The value of the term to match on. - Value cannot be empty. - Value can have at most 3 terms if specified as a - partial match. Each space separated string is - considered as one term. Example) "a b c" is 3 - terms and allowed, " a b c d" is 4 terms and not - allowed for partial match. - full_match (bool): - Whether this is supposed to be a full or - partial match. - """ - - value = proto.Field( - proto.STRING, - number=1, - ) - full_match = proto.Field( - proto.BOOL, - number=2, - ) - - class TimeRange(proto.Message): - r"""Used for time-dependent conditions. - Example: Want to have rule applied for week long sale. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start of time range. Range is inclusive. - end_time (google.protobuf.timestamp_pb2.Timestamp): - End of time range. Range is inclusive. - """ - - start_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - query_terms = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=QueryTerm, - ) - active_time_range = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=TimeRange, - ) - - -class Rule(proto.Message): - r"""A rule is a condition-action pair - - - A condition defines when a rule is to be triggered. - - An action specifies what occurs on that trigger. Currently only - boost rules are supported. Currently only supported by the search - endpoint. - - 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: - boost_action (google.cloud.retail_v2alpha.types.Rule.BoostAction): - A boost action. - - This field is a member of `oneof`_ ``action``. - redirect_action (google.cloud.retail_v2alpha.types.Rule.RedirectAction): - Redirects a shopper to a specific page. - - This field is a member of `oneof`_ ``action``. - oneway_synonyms_action (google.cloud.retail_v2alpha.types.Rule.OnewaySynonymsAction): - Treats specific term as a synonym with a - group of terms. Group of terms will not be - treated as synonyms with the specific term. - - This field is a member of `oneof`_ ``action``. - do_not_associate_action (google.cloud.retail_v2alpha.types.Rule.DoNotAssociateAction): - Prevents term from being associated with - other terms. - - This field is a member of `oneof`_ ``action``. - replacement_action (google.cloud.retail_v2alpha.types.Rule.ReplacementAction): - Replaces specific terms in the query. - - This field is a member of `oneof`_ ``action``. - ignore_action (google.cloud.retail_v2alpha.types.Rule.IgnoreAction): - Ignores specific terms from query during - search. - - This field is a member of `oneof`_ ``action``. - filter_action (google.cloud.retail_v2alpha.types.Rule.FilterAction): - Filters results. - - This field is a member of `oneof`_ ``action``. - twoway_synonyms_action (google.cloud.retail_v2alpha.types.Rule.TwowaySynonymsAction): - Treats a set of terms as synonyms of one - another. - - This field is a member of `oneof`_ ``action``. - condition (google.cloud.retail_v2alpha.types.Condition): - Required. The condition that triggers the - rule. If the condition is empty, the rule will - always apply. - """ - - class BoostAction(proto.Message): - r"""A boost action to apply to results matching condition - specified above. - - Attributes: - boost (float): - Strength of the condition boost, which must be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - products_filter (str): - The filter can have a max size of 5000 characters. An - expression which specifies which products to apply an action - to. The syntax and supported fields are the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": *(id: - ANY("product_1", "product_2"))* *AND* *(colorFamilies: - ANY("Red", "Blue"))* - """ - - boost = proto.Field( - proto.FLOAT, - number=1, - ) - products_filter = proto.Field( - proto.STRING, - number=2, - ) - - class FilterAction(proto.Message): - r"""- Rule Condition: - - - No [Condition][query_terms] provided is a global match. - - 1 or more [Condition][query_terms] provided is combined with - OR operator. - - - Action Input: The request query and filter that will be applied - to the retrieved products, in addition to any filters already - provided with the SearchRequest. The AND operator is used to - combine the query's existing filters with the filter rule(s). - NOTE: May result in 0 results when filters conflict. - - Action Result: Filters the returned objects to be ONLY those that - passed the filter. - - Attributes: - filter (str): - A filter to apply on the matching condition results. - Supported features: - - - [filter][google.cloud.retail.v2alpha.Rule.FilterAction.filter] - must be set. - - Filter syntax is identical to - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter]. - See more details at the Retail Search `user - guide `__. - - To filter products with product ID "product_1" or - "product_2", and color "Red" or "Blue": *(id: - ANY("product_1", "product_2"))* *AND* *(colorFamilies: - ANY("Red", "Blue"))* - """ - - filter = proto.Field( - proto.STRING, - number=1, - ) - - class RedirectAction(proto.Message): - r"""Redirects a shopper to a specific page. - - - Rule Condition: - - - Must specify [Condition][query_terms]. - - - Action Input: Request Query - - Action Result: Redirects shopper to provided uri. - - Attributes: - redirect_uri (str): - URL must have length equal or less than 2000 - characters. - """ - - redirect_uri = proto.Field( - proto.STRING, - number=1, - ) - - class TwowaySynonymsAction(proto.Message): - r"""Creates a set of terms that will be treated as synonyms of each - other. Example: synonyms of "sneakers" and "shoes". - - - "sneakers" will use a synonym of "shoes". - - "shoes" will use a synonym of "sneakers". - - Attributes: - synonyms (Sequence[str]): - Defines a set of synonyms. - Can specify up to 100 synonyms. - Must specify at least 2 synonyms. - """ - - synonyms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class OnewaySynonymsAction(proto.Message): - r"""Maps a set of terms to a set of synonyms. Set of synonyms will be - treated as synonyms of each query term only. ``query_terms`` will - not be treated as synonyms of each other. Example: "sneakers" will - use a synonym of "shoes". "shoes" will not use a synonym of - "sneakers". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. - Will treat synonyms as their synonyms. - Not themselves synonyms of the synonyms. - Can specify up to 100 terms. - synonyms (Sequence[str]): - Defines a set of synonyms. - Cannot contain duplicates. - Can specify up to 100 synonyms. - oneway_terms (Sequence[str]): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=3, - ) - synonyms = proto.RepeatedField( - proto.STRING, - number=4, - ) - oneway_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class DoNotAssociateAction(proto.Message): - r"""Prevents ``query_term`` from being associated with specified terms - during search. Example: Don't associate "gShoe" and "cheap". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. Will not consider - do_not_associate_terms for search if in search query. Can - specify up to 100 terms. - do_not_associate_terms (Sequence[str]): - Cannot contain duplicates or the query term. - Can specify up to 100 terms. - terms (Sequence[str]): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - do_not_associate_terms = proto.RepeatedField( - proto.STRING, - number=3, - ) - terms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class ReplacementAction(proto.Message): - r"""Replaces a term in the query. Multiple replacement candidates can be - specified. All ``query_terms`` will be replaced with the replacement - term. Example: Replace "gShoe" with "google shoe". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. - Will be replaced by replacement term. - Can specify up to 100 terms. - replacement_term (str): - Term that will be used for replacement. - term (str): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - replacement_term = proto.Field( - proto.STRING, - number=3, - ) - term = proto.Field( - proto.STRING, - number=1, - ) - - class IgnoreAction(proto.Message): - r"""Prevents a term in the query from being used in search. - Example: Don't search for "shoddy". - - Attributes: - ignore_terms (Sequence[str]): - Terms to ignore in the search query. - """ - - ignore_terms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - boost_action = proto.Field( - proto.MESSAGE, - number=2, - oneof='action', - message=BoostAction, - ) - redirect_action = proto.Field( - proto.MESSAGE, - number=3, - oneof='action', - message=RedirectAction, - ) - oneway_synonyms_action = proto.Field( - proto.MESSAGE, - number=6, - oneof='action', - message=OnewaySynonymsAction, - ) - do_not_associate_action = proto.Field( - proto.MESSAGE, - number=7, - oneof='action', - message=DoNotAssociateAction, - ) - replacement_action = proto.Field( - proto.MESSAGE, - number=8, - oneof='action', - message=ReplacementAction, - ) - ignore_action = proto.Field( - proto.MESSAGE, - number=9, - oneof='action', - message=IgnoreAction, - ) - filter_action = proto.Field( - proto.MESSAGE, - number=10, - oneof='action', - message=FilterAction, - ) - twoway_synonyms_action = proto.Field( - proto.MESSAGE, - number=11, - oneof='action', - message=TwowaySynonymsAction, - ) - condition = proto.Field( - proto.MESSAGE, - number=1, - message='Condition', - ) - - -class Audience(proto.Message): - r"""An intended audience of the - [Product][google.cloud.retail.v2alpha.Product] for whom it's sold. - - Attributes: - genders (Sequence[str]): - The genders of the audience. Strongly encouraged to use the - standard values: "male", "female", "unisex". - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `gender `__. - Schema.org property - `Product.audience.suggestedGender `__. - age_groups (Sequence[str]): - The age groups of the audience. Strongly encouraged to use - the standard values: "newborn" (up to 3 months old), - "infant" (3–12 months old), "toddler" (1–5 years old), - "kids" (5–13 years old), "adult" (typically teens or older). - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `age_group `__. - Schema.org property - `Product.audience.suggestedMinAge `__ - and - `Product.audience.suggestedMaxAge `__. - """ - - genders = proto.RepeatedField( - proto.STRING, - number=1, - ) - age_groups = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class ColorInfo(proto.Message): - r"""The color information of a - [Product][google.cloud.retail.v2alpha.Product]. - - Attributes: - color_families (Sequence[str]): - The standard color families. Strongly recommended to use the - following standard color groups: "Red", "Pink", "Orange", - "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", - "White", "Gray", "Black" and "Mixed". Normally it is - expected to have only 1 color family. May consider using - single "Mixed" instead of multiple values. - - A maximum of 5 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - colors (Sequence[str]): - The color display names, which may be different from - standard color family names, such as the color aliases used - in the website frontend. Normally it is expected to have - only 1 color. May consider using single "Mixed" instead of - multiple values. - - A maximum of 25 colors are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - """ - - color_families = proto.RepeatedField( - proto.STRING, - number=1, - ) - colors = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class CustomAttribute(proto.Message): - r"""A custom attribute that is not explicitly modeled in - [Product][google.cloud.retail.v2alpha.Product]. - - Attributes: - text (Sequence[str]): - The textual values of this custom attribute. For example, - ``["yellow", "green"]`` when the key is "color". - - Empty string is not allowed. Otherwise, an INVALID_ARGUMENT - error is returned. - - Exactly one of - [text][google.cloud.retail.v2alpha.CustomAttribute.text] or - [numbers][google.cloud.retail.v2alpha.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - numbers (Sequence[float]): - The numerical values of this custom attribute. For example, - ``[2.3, 15.4]`` when the key is "lengths_cm". - - Exactly one of - [text][google.cloud.retail.v2alpha.CustomAttribute.text] or - [numbers][google.cloud.retail.v2alpha.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - searchable (bool): - This field will only be used when - [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] - of the [Catalog][google.cloud.retail.v2alpha.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are searchable by text queries in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2alpha.UserEvent]. - - Only set if type - [text][google.cloud.retail.v2alpha.CustomAttribute.text] is - set. Otherwise, a INVALID_ARGUMENT error is returned. - - This field is a member of `oneof`_ ``_searchable``. - indexable (bool): - This field will only be used when - [AttributesConfig.attribute_config_level][google.cloud.retail.v2alpha.AttributesConfig.attribute_config_level] - of the [Catalog][google.cloud.retail.v2alpha.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are indexed, so that it can be filtered, faceted or - boosted in - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2alpha.UserEvent]. - - See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter], - [SearchRequest.facet_specs][google.cloud.retail.v2alpha.SearchRequest.facet_specs] - and - [SearchRequest.boost_spec][google.cloud.retail.v2alpha.SearchRequest.boost_spec] - for more details. - - This field is a member of `oneof`_ ``_indexable``. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - numbers = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - searchable = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - indexable = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - -class FulfillmentInfo(proto.Message): - r"""Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - Attributes: - type_ (str): - The fulfillment type, including commonly used types (such as - pickup in store and same day delivery), and custom types. - Customers have to map custom types to their display names - before rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - place_ids (Sequence[str]): - The IDs for this - [type][google.cloud.retail.v2alpha.FulfillmentInfo.type], - such as the store IDs for - [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2alpha.FulfillmentInfo.type] - or the region IDs for - [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2alpha.FulfillmentInfo.type]. - - A maximum of 3000 values are allowed. Each value must be a - string with a length limit of 30 characters, matching the - pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". - Otherwise, an INVALID_ARGUMENT error is returned. - """ - - type_ = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class Image(proto.Message): - r"""[Product][google.cloud.retail.v2alpha.Product] image. - Recommendations AI and Retail Search do not use product images to - improve prediction and search results. However, product images can - be returned in results, and are shown in prediction or search - previews in the console. - - Attributes: - uri (str): - Required. URI of the image. - - This field must be a valid UTF-8 encoded URI with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - height (int): - Height of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - width (int): - Width of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - height = proto.Field( - proto.INT32, - number=2, - ) - width = proto.Field( - proto.INT32, - number=3, - ) - - -class Interval(proto.Message): - r"""A floating point interval. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - minimum (float): - Inclusive lower bound. - - This field is a member of `oneof`_ ``min``. - exclusive_minimum (float): - Exclusive lower bound. - - This field is a member of `oneof`_ ``min``. - maximum (float): - Inclusive upper bound. - - This field is a member of `oneof`_ ``max``. - exclusive_maximum (float): - Exclusive upper bound. - - This field is a member of `oneof`_ ``max``. - """ - - minimum = proto.Field( - proto.DOUBLE, - number=1, - oneof='min', - ) - exclusive_minimum = proto.Field( - proto.DOUBLE, - number=2, - oneof='min', - ) - maximum = proto.Field( - proto.DOUBLE, - number=3, - oneof='max', - ) - exclusive_maximum = proto.Field( - proto.DOUBLE, - number=4, - oneof='max', - ) - - -class PriceInfo(proto.Message): - r"""The price information of a - [Product][google.cloud.retail.v2alpha.Product]. - - Attributes: - currency_code (str): - The 3-letter currency code defined in `ISO - 4217 `__. - - If this field is an unrecognizable currency code, an - INVALID_ARGUMENT error is returned. - - The - [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s with the - same - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] - must share the same - [currency_code][google.cloud.retail.v2alpha.PriceInfo.currency_code]. - Otherwise, a FAILED_PRECONDITION error is returned. - price (float): - Price of the product. - - Google Merchant Center property - `price `__. - Schema.org property - `Offer.price `__. - original_price (float): - Price of the product without any discount. If zero, by - default set to be the - [price][google.cloud.retail.v2alpha.PriceInfo.price]. - cost (float): - The costs associated with the sale of a particular product. - Used for gross profit reporting. - - - Profit = - [price][google.cloud.retail.v2alpha.PriceInfo.price] - - [cost][google.cloud.retail.v2alpha.PriceInfo.cost] - - Google Merchant Center property - `cost_of_goods_sold `__. - price_effective_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2alpha.PriceInfo.price] starts - to be effective. This can be set as a future timestamp, and - the [price][google.cloud.retail.v2alpha.PriceInfo.price] is - only used for search after - [price_effective_time][google.cloud.retail.v2alpha.PriceInfo.price_effective_time]. - If so, the - [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - is used before - [price_effective_time][google.cloud.retail.v2alpha.PriceInfo.price_effective_time]. - - Do not set if - [price][google.cloud.retail.v2alpha.PriceInfo.price] is - always effective because it will cause additional latency - during search. - price_expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2alpha.PriceInfo.price] stops - to be effective. The - [price][google.cloud.retail.v2alpha.PriceInfo.price] is used - for search before - [price_expire_time][google.cloud.retail.v2alpha.PriceInfo.price_expire_time]. - If this field is set, the - [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - is used after - [price_expire_time][google.cloud.retail.v2alpha.PriceInfo.price_expire_time]. - - Do not set if - [price][google.cloud.retail.v2alpha.PriceInfo.price] is - always effective because it will cause additional latency - during search. - price_range (google.cloud.retail_v2alpha.types.PriceInfo.PriceRange): - Output only. The price range of all the child - [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s grouped - together on the - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]. Only - populated for - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct]. - Do not set this field in API requests. - """ - - class PriceRange(proto.Message): - r"""The price range of all - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. - - Attributes: - price (google.cloud.retail_v2alpha.types.Interval): - The inclusive - [Product.pricing_info.price][google.cloud.retail.v2alpha.PriceInfo.price] - interval of all - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] having the - same - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. - original_price (google.cloud.retail_v2alpha.types.Interval): - The inclusive - [Product.pricing_info.original_price][google.cloud.retail.v2alpha.PriceInfo.original_price] - internal of all - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] having the - same - [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id]. - """ - - price = proto.Field( - proto.MESSAGE, - number=1, - message='Interval', - ) - original_price = proto.Field( - proto.MESSAGE, - number=2, - message='Interval', - ) - - currency_code = proto.Field( - proto.STRING, - number=1, - ) - price = proto.Field( - proto.FLOAT, - number=2, - ) - original_price = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - price_effective_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - price_expire_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - price_range = proto.Field( - proto.MESSAGE, - number=7, - message=PriceRange, - ) - - -class Rating(proto.Message): - r"""The rating of a [Product][google.cloud.retail.v2alpha.Product]. - - Attributes: - rating_count (int): - The total number of ratings. This value is independent of - the value of - [rating_histogram][google.cloud.retail.v2alpha.Rating.rating_histogram]. - - This value must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - average_rating (float): - The average rating of the - [Product][google.cloud.retail.v2alpha.Product]. - - The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT - error is returned. - rating_histogram (Sequence[int]): - List of rating counts per rating value (index = rating - 1). - The list is empty if there is no rating. If the list is - non-empty, its size is always 5. Otherwise, an - INVALID_ARGUMENT error is returned. - - For example, [41, 14, 13, 47, 303]. It means that the - [Product][google.cloud.retail.v2alpha.Product] got 41 - ratings with 1 star, 14 ratings with 2 star, and so on. - """ - - rating_count = proto.Field( - proto.INT32, - number=1, - ) - average_rating = proto.Field( - proto.FLOAT, - number=2, - ) - rating_histogram = proto.RepeatedField( - proto.INT32, - number=3, - ) - - -class UserInfo(proto.Message): - r"""Information of an end user. - - Attributes: - user_id (str): - Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. - - Always use a hashed value for this ID. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - ip_address (str): - The end user's IP address. This field is used to extract - location information for personalization. - - This field must be either an IPv4 address (e.g. - "104.133.9.80") or an IPv6 address (e.g. - "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an - INVALID_ARGUMENT error is returned. - - This should not be set when: - - - setting - [SearchRequest.user_info][google.cloud.retail.v2alpha.SearchRequest.user_info]. - - using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2alpha.UserInfo.direct_user_request] - is set. - user_agent (str): - User agent as included in the HTTP header. Required for - getting - [SearchResponse.sponsored_results][google.cloud.retail.v2alpha.SearchResponse.sponsored_results]. - - The field must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This should not be set when using the client side event - reporting with GTM or JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2alpha.UserInfo.direct_user_request] - is set. - direct_user_request (bool): - True if the request is made directly from the end user, in - which case the - [ip_address][google.cloud.retail.v2alpha.UserInfo.ip_address] - and - [user_agent][google.cloud.retail.v2alpha.UserInfo.user_agent] - can be populated from the HTTP request. This flag should be - set only if the API request is made directly from the end - user such as a mobile app (and not if a gateway or a server - is processing and pushing the user events). - - This should not be set when using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2alpha.UserEventService.CollectUserEvent]. - """ - - user_id = proto.Field( - proto.STRING, - number=1, - ) - ip_address = proto.Field( - proto.STRING, - number=2, - ) - user_agent = proto.Field( - proto.STRING, - number=3, - ) - direct_user_request = proto.Field( - proto.BOOL, - number=4, - ) - - -class LocalInventory(proto.Message): - r"""The inventory information at a place (e.g. a store) - identified by a place ID. - - Attributes: - place_id (str): - The place ID for the current set of inventory - information. - price_info (google.cloud.retail_v2alpha.types.PriceInfo): - Product price and cost information. - - Google Merchant Center property - `price `__. - attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): - Additional local inventory attributes, for example, store - name, promotion tags, etc. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - At most 30 attributes are allowed. - - The key must be a UTF-8 encoded string with a length - limit of 32 characters. - - The key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis - or KEY_1_LIKE_THIS. - - The attribute values must be of the same type (text or - number). - - Only 1 value is allowed for each attribute. - - For text values, the length limit is 256 UTF-8 - characters. - - The attribute does not support search. The ``searchable`` - field should be unset or set to false. - - The max summed total bytes of custom attribute keys and - values per product is 5MiB. - fulfillment_types (Sequence[str]): - Input only. Supported fulfillment types. Valid fulfillment - type values include commonly used types (such as pickup in - store and same day delivery), and custom types. Customers - have to map custom types to their display names before - rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - All the elements must be distinct. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - place_id = proto.Field( - proto.STRING, - number=1, - ) - price_info = proto.Field( - proto.MESSAGE, - number=2, - message='PriceInfo', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='CustomAttribute', - ) - fulfillment_types = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py deleted file mode 100644 index f3bb27b3..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/completion_service.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'CompleteQueryRequest', - 'CompleteQueryResponse', - }, -) - - -class CompleteQueryRequest(proto.Message): - r"""Auto-complete parameters. - - Attributes: - catalog (str): - Required. Catalog for which the completion is performed. - - Full resource name of catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - query (str): - Required. The query used to generate - suggestions. - The maximum number of allowed characters is 255. - visitor_id (str): - Required field. A unique identifier for tracking visitors. - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - language_codes (Sequence[str]): - The language filters applied to the output suggestions. If - set, it should contain the language of the query. If not - set, suggestions are returned without considering language - restrictions. This is the BCP-47 language code, such as - "en-US" or "sr-Latn". For more information, see `Tags for - Identifying - Languages `__. The - maximum number of language codes is 3. - device_type (str): - The device type context for completion suggestions. It is - useful to apply different suggestions on different device - types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the - suggestions are across all device types. - - Supported formats: - - - ``UNKNOWN_DEVICE_TYPE`` - - - ``DESKTOP`` - - - ``MOBILE`` - - - A customized string starts with ``OTHER_``, e.g. - ``OTHER_IPHONE``. - dataset (str): - Determines which dataset to use for fetching completion. - "user-data" will use the imported dataset through - [CompletionService.ImportCompletionData][google.cloud.retail.v2alpha.CompletionService.ImportCompletionData]. - "cloud-retail" will use the dataset generated by cloud - retail based on user events. If leave empty, it will use the - "user-data". - - Current supported values: - - - user-data - - - cloud-retail This option requires additional - allowlisting. Before using cloud-retail, contact Cloud - Retail support team first. - max_suggestions (int): - Completion max suggestions. If left unset or set to 0, then - will fallback to the configured value - [CompletionConfig.max_suggestions][google.cloud.retail.v2alpha.CompletionConfig.max_suggestions]. - - The maximum allowed max suggestions is 20. If it is set - higher, it will be capped by 20. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - visitor_id = proto.Field( - proto.STRING, - number=7, - ) - language_codes = proto.RepeatedField( - proto.STRING, - number=3, - ) - device_type = proto.Field( - proto.STRING, - number=4, - ) - dataset = proto.Field( - proto.STRING, - number=6, - ) - max_suggestions = proto.Field( - proto.INT32, - number=5, - ) - - -class CompleteQueryResponse(proto.Message): - r"""Response of the auto-complete query. - - Attributes: - completion_results (Sequence[google.cloud.retail_v2alpha.types.CompleteQueryResponse.CompletionResult]): - Results of the matching suggestions. The - result list is ordered and the first result is - top suggestion. - attribution_token (str): - A unique complete token. This should be included in the - [UserEvent.completion_detail][google.cloud.retail.v2alpha.UserEvent.completion_detail] - for search events resulting from this completion, which - enables accurate attribution of complete model performance. - recent_search_results (Sequence[google.cloud.retail_v2alpha.types.CompleteQueryResponse.RecentSearchResult]): - Matched recent searches of this user. The maximum number of - recent searches is 10. This field is a restricted feature. - Contact Retail Search support team if you are interested in - enabling it. - - This feature is only available when - [CompleteQueryRequest.visitor_id][google.cloud.retail.v2alpha.CompleteQueryRequest.visitor_id] - field is set and - [UserEvent][google.cloud.retail.v2alpha.UserEvent] is - imported. The recent searches satisfy the follow rules: - - - They are ordered from latest to oldest. - - They are matched with - [CompleteQueryRequest.query][google.cloud.retail.v2alpha.CompleteQueryRequest.query] - case insensitively. - - They are transformed to lower cases. - - They are UTF-8 safe. - - Recent searches are deduplicated. More recent searches will - be reserved when duplication happens. - """ - - class CompletionResult(proto.Message): - r"""Resource that represents completion results. - - Attributes: - suggestion (str): - The suggestion for the query. - attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): - Custom attributes for the suggestion term. - - - For "user-data", the attributes are additional custom - attributes ingested through BigQuery. - - For "cloud-retail", the attributes are product attributes - generated by Cloud Retail. - """ - - suggestion = proto.Field( - proto.STRING, - number=1, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=common.CustomAttribute, - ) - - class RecentSearchResult(proto.Message): - r"""Recent search of this user. - - Attributes: - recent_search (str): - The recent search query. - """ - - recent_search = proto.Field( - proto.STRING, - number=1, - ) - - completion_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=CompletionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - recent_search_results = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=RecentSearchResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py deleted file mode 100644 index 93e84d08..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control.py +++ /dev/null @@ -1,123 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'Control', - }, -) - - -class Control(proto.Message): - r"""Configures dynamic serving time metadata that is used to pre - and post process search/recommendation model results. - - 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: - facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec): - A facet specification to perform faceted - search. - - This field is a member of `oneof`_ ``control``. - rule (google.cloud.retail_v2alpha.types.Rule): - A rule control - a condition-action pair. - Enacts a set action when the condition is - triggered. For example: Boost "gShoe" when query - full matches "Running Shoes". - - This field is a member of `oneof`_ ``control``. - name (str): - Immutable. Fully qualified name - projects/\ */locations/global/catalogs/*/controls/\* - display_name (str): - Required. The human readable control display name. Used in - Retail UI. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is thrown. - associated_serving_config_ids (Sequence[str]): - Output only. List of serving configuration - ids that that are associated with this control. - Note the association is managed via the - ServingConfig, this is an output only - denormalizeed view. Assumed to be in the same - catalog. - solution_types (Sequence[google.cloud.retail_v2alpha.types.SolutionType]): - Required. Immutable. The solution types that the serving - config is used for. Currently we support setting only one - type of solution at creation time. - - Only ``SOLUTION_TYPE_SEARCH`` value is supported at the - moment. If no solution type is provided at creation time, - will default to SOLUTION_TYPE_SEARCH. - search_solution_use_case (Sequence[google.cloud.retail_v2alpha.types.SearchSolutionUseCase]): - Required. Specifies the use case for the control. Affects - what condition fields can be set. Only settable by search - controls. Will default to SEARCH_SOLUTION_USE_CASE_SEARCH if - not specified. Currently only allow one - search_solution_use_case per control. - """ - - facet_spec = proto.Field( - proto.MESSAGE, - number=3, - oneof='control', - message=search_service.SearchRequest.FacetSpec, - ) - rule = proto.Field( - proto.MESSAGE, - number=4, - oneof='control', - message=common.Rule, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - associated_serving_config_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - solution_types = proto.RepeatedField( - proto.ENUM, - number=6, - enum=common.SolutionType, - ) - search_solution_use_case = proto.RepeatedField( - proto.ENUM, - number=7, - enum=common.SearchSolutionUseCase, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py deleted file mode 100644 index da0c4915..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/control_service.py +++ /dev/null @@ -1,197 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'CreateControlRequest', - 'UpdateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - }, -) - - -class CreateControlRequest(proto.Message): - r"""Request for CreateControl method. - - Attributes: - parent (str): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - control (google.cloud.retail_v2alpha.types.Control): - Required. The Control to create. - control_id (str): - Required. The ID to use for the Control, which will become - the final component of the Control's resource name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-_/. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - control = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_control.Control, - ) - control_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateControlRequest(proto.Message): - r"""Request for UpdateControl method. - - Attributes: - control (google.cloud.retail_v2alpha.types.Control): - Required. The Control to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Control][google.cloud.retail.v2alpha.Control] to update. - The following are NOT supported: - - - [Control.name][google.cloud.retail.v2alpha.Control.name] - - If not set or empty, all supported fields are updated. - """ - - control = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_control.Control, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteControlRequest(proto.Message): - r"""Request for DeleteControl method. - - Attributes: - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetControlRequest(proto.Message): - r"""Request for GetControl method. - - Attributes: - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListControlsRequest(proto.Message): - r"""Request for ListControls method. - - Attributes: - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - page_size (int): - Optional. Maximum number of results to - return. If unspecified, defaults to 50. Max - allowed value is 1000. - page_token (str): - Optional. A page token, received from a previous - ``ListControls`` call. Provide this to retrieve the - subsequent page. - filter (str): - Optional. A filter to apply on the list results. Supported - features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2alpha.ListControlsRequest.filter] - is unset. - - List controls that are used in a single ServingConfig: - 'serving_config = "boosted_home_page_cvr"' - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListControlsResponse(proto.Message): - r"""Response for ListControls method. - - Attributes: - controls (Sequence[google.cloud.retail_v2alpha.types.Control]): - All the Controls for a given catalog. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - controls = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_control.Control, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py deleted file mode 100644 index ffb42fde..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/export_config.py +++ /dev/null @@ -1,134 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - }, -) - - -class ExportErrorsConfig(proto.Message): - r"""Configuration of destination for Export related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage path for import errors. This must be an - empty, existing Cloud Storage bucket. Export errors will be - written to a file in this bucket, one per line, as a - JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ExportMetadata(proto.Message): - r"""Metadata related to the progress of the Export operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class ExportProductsResponse(proto.Message): - r"""Response of the ExportProductsRequest. If the long running - operation is done, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2alpha.types.ExportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExportErrorsConfig', - ) - - -class ExportUserEventsResponse(proto.Message): - r"""Response of the ExportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2alpha.types.ExportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExportErrorsConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py deleted file mode 100644 index b6260358..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/import_config.py +++ /dev/null @@ -1,691 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import user_event -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'GcsSource', - 'BigQuerySource', - 'ProductInlineSource', - 'UserEventInlineSource', - 'ImportErrorsConfig', - 'ImportProductsRequest', - 'ImportUserEventsRequest', - 'ImportCompletionDataRequest', - 'ProductInputConfig', - 'UserEventInputConfig', - 'CompletionDataInputConfig', - 'ImportMetadata', - 'ImportProductsResponse', - 'ImportUserEventsResponse', - 'UserEventImportSummary', - 'ImportCompletionDataResponse', - }, -) - - -class GcsSource(proto.Message): - r"""Google Cloud Storage location for input content. - format. - - Attributes: - input_uris (Sequence[str]): - Required. Google Cloud Storage URIs to input files. URI can - be up to 2000 characters long. URIs can match the full - object path (for example, - ``gs://bucket/directory/object.json``) or a pattern matching - one or more files, such as ``gs://bucket/directory/*.json``. - A request can contain at most 100 files, and each file can - be up to 2 GB. See `Importing product - information `__ - for the expected file format and setup instructions. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2alpha.Product] per line. - Each product must have a valid - [Product.id][google.cloud.retail.v2alpha.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2alpha.UserEvent] per - line. - - ``user_event_ga360``: Using - https://support.google.com/analytics/answer/3437719. - - Supported values for control imports: - - - 'control' (default): One JSON - [Control][google.cloud.retail.v2alpha.Control] per line. - - Supported values for catalog attribute imports: - - - 'catalog_attribute' (default): One CSV - [CatalogAttribute][google.cloud.retail.v2alpha.CatalogAttribute] - per line. - """ - - input_uris = proto.RepeatedField( - proto.STRING, - number=1, - ) - data_schema = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""BigQuery source import data from. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - partition_date (google.type.date_pb2.Date): - BigQuery time partitioned table's \_PARTITIONDATE in - YYYY-MM-DD format. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - - This field is a member of `oneof`_ ``partition``. - project_id (str): - The project ID (can be project # or ID) that - the BigQuery source is in with a length limit of - 128 characters. If not specified, inherits the - project ID from the parent request. - dataset_id (str): - Required. The BigQuery data set to copy the - data from with a length limit of 1,024 - characters. - table_id (str): - Required. The BigQuery table to copy the data - from with a length limit of 1,024 characters. - gcs_staging_dir (str): - Intermediate Cloud Storage directory used for - the import with a length limit of 2,000 - characters. Can be specified if one wants to - have the BigQuery export to a specific Cloud - Storage directory. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2alpha.Product] per line. - Each product must have a valid - [Product.id][google.cloud.retail.v2alpha.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2alpha.UserEvent] per - line. - - ``user_event_ga360``: The schema is available here: - https://support.google.com/analytics/answer/3437719. - - ``user_event_ga4``: This feature is in private preview. - Please contact the support team for importing Google - Analytics 4 events. The schema is available here: - https://support.google.com/analytics/answer/7029846. - - Supported values for auto-completion imports: - - - ``suggestions`` (default): One JSON completion suggestion - per line. - - ``denylist``: One JSON deny suggestion per line. - - ``allowlist``: One JSON allow suggestion per line. - """ - - partition_date = proto.Field( - proto.MESSAGE, - number=6, - oneof='partition', - message=date_pb2.Date, - ) - project_id = proto.Field( - proto.STRING, - number=5, - ) - dataset_id = proto.Field( - proto.STRING, - number=1, - ) - table_id = proto.Field( - proto.STRING, - number=2, - ) - gcs_staging_dir = proto.Field( - proto.STRING, - number=3, - ) - data_schema = proto.Field( - proto.STRING, - number=4, - ) - - -class ProductInlineSource(proto.Message): - r"""The inline source for the input config for ImportProducts - method. - - Attributes: - products (Sequence[google.cloud.retail_v2alpha.types.Product]): - Required. A list of products to update/create. Each product - must have a valid - [Product.id][google.cloud.retail.v2alpha.Product.id]. - Recommended max of 100 items. - """ - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=product.Product, - ) - - -class UserEventInlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (Sequence[google.cloud.retail_v2alpha.types.UserEvent]): - Required. A list of user events to import. - Recommended max of 10k items. - """ - - user_events = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - -class ImportErrorsConfig(proto.Message): - r"""Configuration of destination for Import related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage prefix for import errors. This must be - an empty, existing Cloud Storage directory. Import errors - will be written to sharded files in this directory, one per - line, as a JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportProductsRequest(proto.Message): - r"""Request message for Import methods. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` - - If no updateMask is specified, requires products.create - permission. If updateMask is specified, requires - products.update permission. - request_id (str): - Deprecated. This field has no effect. - input_config (google.cloud.retail_v2alpha.types.ProductInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - imported 'products' to update. If not set, will - by default update all fields. - reconciliation_mode (google.cloud.retail_v2alpha.types.ImportProductsRequest.ReconciliationMode): - The mode of reconciliation between existing products and the - products to be imported. Defaults to - [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - """ - class ReconciliationMode(proto.Enum): - r"""Indicates how imported products are reconciled with the - existing products created or imported before. - """ - RECONCILIATION_MODE_UNSPECIFIED = 0 - INCREMENTAL = 1 - FULL = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - request_id = proto.Field( - proto.STRING, - number=6, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='ProductInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - reconciliation_mode = proto.Field( - proto.ENUM, - number=5, - enum=ReconciliationMode, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=7, - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog`` - input_config (google.cloud.retail_v2alpha.types.UserEventInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. Cannot be set for inline user - event imports. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='UserEventInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - - -class ImportCompletionDataRequest(proto.Message): - r"""Request message for ImportCompletionData methods. - - Attributes: - parent (str): - Required. The catalog which the suggestions dataset belongs - to. - - Format: - ``projects/1234/locations/global/catalogs/default_catalog``. - input_config (google.cloud.retail_v2alpha.types.CompletionDataInputConfig): - Required. The desired input location of the - data. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='CompletionDataInputConfig', - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=3, - ) - - -class ProductInputConfig(proto.Message): - r"""The input config source for products. - - 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: - product_inline_source (google.cloud.retail_v2alpha.types.ProductInlineSource): - The Inline source for the input content for - products. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2alpha.types.GcsSource): - Google Cloud Storage location for the input - content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - product_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='ProductInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class UserEventInputConfig(proto.Message): - r"""The input config source for user events. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - user_event_inline_source (google.cloud.retail_v2alpha.types.UserEventInlineSource): - Required. The Inline source for the input - content for UserEvents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2alpha.types.GcsSource): - Required. Google Cloud Storage location for - the input content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): - Required. BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - user_event_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='UserEventInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class CompletionDataInputConfig(proto.Message): - r"""The input config source for completion data. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - big_query_source (google.cloud.retail_v2alpha.types.BigQuerySource): - Required. BigQuery input source. - Add the IAM permission "BigQuery Data Viewer" - for - cloud-retail-customer-data-access@system.gserviceaccount.com - before using this feature otherwise an error is - thrown. - - This field is a member of `oneof`_ ``source``. - """ - - big_query_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='BigQuerySource', - ) - - -class ImportMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - request_id (str): - Deprecated. This field is never set. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=3, - ) - failure_count = proto.Field( - proto.INT64, - number=4, - ) - request_id = proto.Field( - proto.STRING, - number=5, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=6, - ) - - -class ImportProductsResponse(proto.Message): - r"""Response of the - [ImportProductsRequest][google.cloud.retail.v2alpha.ImportProductsRequest]. - If the long running operation is done, then this message is returned - by the google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2alpha.types.ImportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - import_summary (google.cloud.retail_v2alpha.types.UserEventImportSummary): - Aggregated statistics of user event import - status. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - import_summary = proto.Field( - proto.MESSAGE, - number=3, - message='UserEventImportSummary', - ) - - -class UserEventImportSummary(proto.Message): - r"""A summary of import result. The UserEventImportSummary - summarizes the import status for user events. - - Attributes: - joined_events_count (int): - Count of user events imported with complete - existing catalog information. - unjoined_events_count (int): - Count of user events imported, but with - catalog information not found in the imported - catalog. - """ - - joined_events_count = proto.Field( - proto.INT64, - number=1, - ) - unjoined_events_count = proto.Field( - proto.INT64, - number=2, - ) - - -class ImportCompletionDataResponse(proto.Message): - r"""Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2alpha.ImportCompletionDataRequest]. - 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 (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py deleted file mode 100644 index 51233cae..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/prediction_service.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import user_event as gcr_user_event -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'PredictRequest', - 'PredictResponse', - }, -) - - -class PredictRequest(proto.Message): - r"""Request message for Predict method. - - Attributes: - placement (str): - Required. Full resource name of the format: - {name=projects/*/locations/global/catalogs/default_catalog/placements/*} - The ID of the Recommendations AI placement. Before you can - request predictions from your model, you must create at - least one placement for it. For more information, see - `Managing - placements `__. - - The full list of available placements can be seen at - https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements - user_event (google.cloud.retail_v2alpha.types.UserEvent): - Required. Context about the user, what they - are looking at and what action they took to - trigger the predict request. Note that this user - event detail won't be ingested to userEvent - logs. Thus, a separate userEvent write request - is required for event logging. - page_size (int): - Maximum number of results to return per page. - Set this property to the number of prediction - results needed. If zero, the service will choose - a reasonable default. The maximum allowed value - is 100. Values above 100 will be coerced to 100. - page_token (str): - The previous PredictResponse.next_page_token. - filter (str): - Filter for restricting prediction results with a length - limit of 5,000 characters. Accepts values for tags and the - ``filterOutOfStockItems`` flag. - - - Tag expressions. Restricts predictions to products that - match all of the specified tags. Boolean operators ``OR`` - and ``NOT`` are supported if the expression is enclosed - in parentheses, and must be separated from the tag values - by a space. ``-"tagA"`` is also supported and is - equivalent to ``NOT "tagA"``. Tag values must be double - quoted UTF-8 encoded strings with a size limit of 1,000 - characters. - - Note: "Recently viewed" models don't support tag - filtering at the moment. - - - filterOutOfStockItems. Restricts predictions to products - that do not have a stockState value of OUT_OF_STOCK. - - Examples: - - - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT - "promotional") - - filterOutOfStockItems tag=(-"promotional") - - filterOutOfStockItems - - If your filter blocks all prediction results, the API will - return generic (unfiltered) popular products. If you only - want results strictly matching the filters, set - ``strictFiltering`` to True in ``PredictRequest.params`` to - receive empty results instead. Note that the API will never - return items with storageStatus of "EXPIRED" or "DELETED" - regardless of filter choices. - validate_only (bool): - Use validate only mode for this prediction - query. If set to true, a dummy model will be - used that returns arbitrary products. Note that - the validate only mode should only be used for - testing the API, or if the model is not ready. - params (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional domain specific parameters for the predictions. - - Allowed values: - - - ``returnProduct``: Boolean. If set to true, the - associated product object will be returned in the - ``results.metadata`` field in the prediction response. - - ``returnScore``: Boolean. If set to true, the prediction - 'score' corresponding to each returned product will be - set in the ``results.metadata`` field in the prediction - response. The given 'score' indicates the probability of - an product being clicked/purchased given the user's - context and history. - - ``strictFiltering``: Boolean. True by default. If set to - false, the service will return generic (unfiltered) - popular products instead of empty if your filter blocks - all prediction results. - - ``priceRerankLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of - {'no-price-reranking', 'low-price-reranking', - 'medium-price-reranking', 'high-price-reranking'}. This - gives request-level control and adjusts prediction - results based on product price. - - ``diversityLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of {'no-diversity', - 'low-diversity', 'medium-diversity', 'high-diversity', - 'auto-diversity'}. This gives request-level control and - adjusts prediction results based on product category. - labels (Mapping[str, str]): - The labels applied to a resource must meet the following - requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters, and cannot be empty. Values can - be empty, and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - """ - - placement = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - validate_only = proto.Field( - proto.BOOL, - number=6, - ) - params = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class PredictResponse(proto.Message): - r"""Response message for predict method. - - Attributes: - results (Sequence[google.cloud.retail_v2alpha.types.PredictResponse.PredictionResult]): - A list of recommended products. The order - represents the ranking (from the most relevant - product to the least). - attribution_token (str): - A unique attribution token. This should be included in the - [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs - resulting from this recommendation, which enables accurate - attribution of recommendation model performance. - missing_ids (Sequence[str]): - IDs of products in the request that were - missing from the inventory. - validate_only (bool): - True if the validateOnly property was set in - the request. - """ - - class PredictionResult(proto.Message): - r"""PredictionResult represents the recommendation prediction - results. - - Attributes: - id (str): - ID of the recommended product - metadata (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional product metadata / annotations. - - Possible values: - - - ``product``: JSON representation of the product. Will be - set if ``returnProduct`` is set to true in - ``PredictRequest.params``. - - ``score``: Prediction score in double value. Will be set - if ``returnScore`` is set to true in - ``PredictRequest.params``. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - metadata = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=PredictionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - missing_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py deleted file mode 100644 index 492a51ff..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product.py +++ /dev/null @@ -1,705 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'Product', - }, -) - - -class Product(proto.Message): - r"""Product captures all metadata information of items to be - recommended or searched. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this product becomes unavailable for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - If it is set, the - [Product][google.cloud.retail.v2alpha.Product] is not - available for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - after - [expire_time][google.cloud.retail.v2alpha.Product.expire_time]. - However, the product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - [expire_time][google.cloud.retail.v2alpha.Product.expire_time] - must be later than - [available_time][google.cloud.retail.v2alpha.Product.available_time] - and - [publish_time][google.cloud.retail.v2alpha.Product.publish_time], - otherwise an INVALID_ARGUMENT error is thrown. - - Corresponding properties: Google Merchant Center property - `expiration_date `__. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Input only. The TTL (time to live) of the product. - - If it is set, it must be a non-negative value, and - [expire_time][google.cloud.retail.v2alpha.Product.expire_time] - is set as current timestamp plus - [ttl][google.cloud.retail.v2alpha.Product.ttl]. The derived - [expire_time][google.cloud.retail.v2alpha.Product.expire_time] - is returned in the output and - [ttl][google.cloud.retail.v2alpha.Product.ttl] is left blank - when retrieving the - [Product][google.cloud.retail.v2alpha.Product]. - - If it is set, the product is not available for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - after current timestamp plus - [ttl][google.cloud.retail.v2alpha.Product.ttl]. However, the - product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts]. - - This field is a member of `oneof`_ ``expiration``. - name (str): - Immutable. Full resource name of the product, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. - id (str): - Immutable. [Product][google.cloud.retail.v2alpha.Product] - identifier, which is the final component of - [name][google.cloud.retail.v2alpha.Product.name]. For - example, this field is "id_1", if - [name][google.cloud.retail.v2alpha.Product.name] is - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `id `__. - Schema.org property - `Product.sku `__. - type_ (google.cloud.retail_v2alpha.types.Product.Type): - Immutable. The type of the product. Default to - [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2alpha.ProductLevelConfig.ingestion_product_type] - if unset. - primary_product_id (str): - Variant group identifier. Must be an - [id][google.cloud.retail.v2alpha.Product.id], with the same - parent branch with this product. Otherwise, an error is - thrown. - - For - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]s, this field - can only be empty or set to the same value as - [id][google.cloud.retail.v2alpha.Product.id]. - - For VARIANT [Product][google.cloud.retail.v2alpha.Product]s, - this field cannot be empty. A maximum of 2,000 products are - allowed to share the same - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]. Otherwise, - an INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `item_group_id `__. - Schema.org property - `Product.inProductGroupWithID `__. - collection_member_ids (Sequence[str]): - The [id][google.cloud.retail.v2alpha.Product.id] of the - collection members when - [type][google.cloud.retail.v2alpha.Product.type] is - [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION]. - - Non-existent product ids are allowed. The - [type][google.cloud.retail.v2alpha.Product.type] of the - members must be either - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - or - [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - otherwise and INVALID_ARGUMENT error is thrown. Should not - set it for other types. A maximum of 1000 values are - allowed. Otherwise, an INVALID_ARGUMENT error is return. - gtin (str): - The Global Trade Item Number (GTIN) of the product. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This field must be a Unigram. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `gtin `__. - Schema.org property - `Product.isbn `__, - `Product.gtin8 `__, - `Product.gtin12 `__, - `Product.gtin13 `__, or - `Product.gtin14 `__. - - If the value is not a valid GTIN, an INVALID_ARGUMENT error - is returned. - categories (Sequence[str]): - Product categories. This field is repeated for supporting - one product belonging to several parallel categories. - Strongly recommended using the full path for better search / - recommendation quality. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - For example, if a shoes product belongs to both ["Shoes & - Accessories" -> "Shoes"] and ["Sports & Fitness" -> - "Athletic Clothing" -> "Shoes"], it could be represented as: - - :: - - "categories": [ - "Shoes & Accessories > Shoes", - "Sports & Fitness > Athletic Clothing > Shoes" - ] - - Must be set for - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] otherwise an - INVALID_ARGUMENT error is returned. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. Empty values - are not allowed. Each value must be a UTF-8 encoded string - with a length limit of 5,000 characters. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `google_product_category `__. - Schema.org property [Product.category] - (https://schema.org/category). - title (str): - Required. Product title. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `title `__. - Schema.org property - `Product.name `__. - brands (Sequence[str]): - The brands of the product. - - A maximum of 30 brands are allowed. Each brand must be a - UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `brand `__. - Schema.org property - `Product.brand `__. - description (str): - Product description. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `description `__. - Schema.org property - `Product.description `__. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. - - For product prediction, this field is ignored and the model - automatically detects the text language. The - [Product][google.cloud.retail.v2alpha.Product] can include - text in different languages, but duplicating - [Product][google.cloud.retail.v2alpha.Product]s to provide - text in multiple languages can result in degraded model - performance. - - For product search this field is in use. It defaults to - "en-US" if unset. - attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): - Highly encouraged. Extra product attributes to be included. - For example, for products, this could include the store - name, vendor, style, color, etc. These are very strong - signals for recommendation model, thus we highly recommend - providing the attributes here. - - Features that can take on one of a limited number of - possible values. Two types of features can be set are: - - Textual features. some examples would be the brand/maker of - a product, or country of a customer. Numerical features. - Some examples would be the height/weight of a product, or - age of a customer. - - For example: - ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - Max entries count: 200. - - The key must be a UTF-8 encoded string with a length - limit of 128 characters. - - For indexable attribute, the key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, - ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a - non-empty UTF-8 encoded string with a length limit of 256 - characters. - - For number attributes, at most 400 values are allowed. - tags (Sequence[str]): - Custom tags associated with the product. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. This value - must be a UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This tag can be used for filtering recommendation results by - passing the tag as part of the - [PredictRequest.filter][google.cloud.retail.v2alpha.PredictRequest.filter]. - - Corresponding properties: Google Merchant Center property - `custom_label_0–4 `__. - price_info (google.cloud.retail_v2alpha.types.PriceInfo): - Product price and cost information. - - Corresponding properties: Google Merchant Center property - `price `__. - rating (google.cloud.retail_v2alpha.types.Rating): - The rating of this product. - available_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this - [Product][google.cloud.retail.v2alpha.Product] becomes - available for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - availability (google.cloud.retail_v2alpha.types.Product.Availability): - The online availability of the - [Product][google.cloud.retail.v2alpha.Product]. Default to - [Availability.IN_STOCK][google.cloud.retail.v2alpha.Product.Availability.IN_STOCK]. - - Corresponding properties: Google Merchant Center property - `availability `__. - Schema.org property - `Offer.availability `__. - available_quantity (google.protobuf.wrappers_pb2.Int32Value): - The available quantity of the item. - fulfillment_info (Sequence[google.cloud.retail_v2alpha.types.FulfillmentInfo]): - Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - All the elements must have distinct - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type]. - Otherwise, an INVALID_ARGUMENT error is returned. - uri (str): - Canonical URL directly linking to the product detail page. - - It is strongly recommended to provide a valid uri for the - product, otherwise the service performance could be - significantly degraded. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `link `__. - Schema.org property `Offer.url `__. - images (Sequence[google.cloud.retail_v2alpha.types.Image]): - Product images for the product. We highly recommend putting - the main image first. - - A maximum of 300 images are allowed. - - Corresponding properties: Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - audience (google.cloud.retail_v2alpha.types.Audience): - The target group associated with a given - audience (e.g. male, veterans, car owners, - musicians, etc.) of the product. - color_info (google.cloud.retail_v2alpha.types.ColorInfo): - The color of the product. - - Corresponding properties: Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - sizes (Sequence[str]): - The size of the product. To represent different size systems - or size types, consider using this format: - [[[size_system:]size_type:]size_value]. - - For example, in "US:MENS:M", "US" represents size system; - "MENS" represents size type; "M" represents size value. In - "GIRLS:27", size system is empty; "GIRLS" represents size - type; "27" represents size value. In "32 inches", both size - system and size type are empty, while size value is "32 - inches". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `size `__, - `size_type `__, - and - `size_system `__. - Schema.org property - `Product.size `__. - materials (Sequence[str]): - The material of the product. For example, "leather", - "wooden". - - A maximum of 20 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 200 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `material `__. - Schema.org property - `Product.material `__. - patterns (Sequence[str]): - The pattern or graphic print of the product. For example, - "striped", "polka dot", "paisley". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `pattern `__. - Schema.org property - `Product.pattern `__. - conditions (Sequence[str]): - The condition of the product. Strongly encouraged to use the - standard values: "new", "refurbished", "used". - - A maximum of 1 value is allowed per - [Product][google.cloud.retail.v2alpha.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `condition `__. - Schema.org property - `Offer.itemCondition `__. - promotions (Sequence[google.cloud.retail_v2alpha.types.Promotion]): - The promotions applied to the product. A maximum of 10 - values are allowed per - [Product][google.cloud.retail.v2alpha.Product]. Only - [Promotion.promotion_id][google.cloud.retail.v2alpha.Promotion.promotion_id] - will be used, other fields will be ignored if set. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the product is published by the retailer - for the first time, which indicates the freshness of the - products. Note that this field is different from - [available_time][google.cloud.retail.v2alpha.Product.available_time], - given it purely describes product freshness regardless of - when it is available on search and recommendation. - retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the - [Product][google.cloud.retail.v2alpha.Product]s are returned - in - [SearchResponse][google.cloud.retail.v2alpha.SearchResponse]. - - Supported fields for all - [type][google.cloud.retail.v2alpha.Product.type]s: - - - [audience][google.cloud.retail.v2alpha.Product.audience] - - [availability][google.cloud.retail.v2alpha.Product.availability] - - [brands][google.cloud.retail.v2alpha.Product.brands] - - [color_info][google.cloud.retail.v2alpha.Product.color_info] - - [conditions][google.cloud.retail.v2alpha.Product.conditions] - - [gtin][google.cloud.retail.v2alpha.Product.gtin] - - [materials][google.cloud.retail.v2alpha.Product.materials] - - [name][google.cloud.retail.v2alpha.Product.name] - - [patterns][google.cloud.retail.v2alpha.Product.patterns] - - [price_info][google.cloud.retail.v2alpha.Product.price_info] - - [rating][google.cloud.retail.v2alpha.Product.rating] - - [sizes][google.cloud.retail.v2alpha.Product.sizes] - - [title][google.cloud.retail.v2alpha.Product.title] - - [uri][google.cloud.retail.v2alpha.Product.uri] - - Supported fields only for - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION]: - - - [categories][google.cloud.retail.v2alpha.Product.categories] - - [description][google.cloud.retail.v2alpha.Product.description] - - [images][google.cloud.retail.v2alpha.Product.images] - - Supported fields only for - [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT]: - - - Only the first image in - [images][google.cloud.retail.v2alpha.Product.images] - - To mark - [attributes][google.cloud.retail.v2alpha.Product.attributes] - as retrievable, include paths of the form "attributes.key" - where "key" is the key of a custom attribute, as specified - in - [attributes][google.cloud.retail.v2alpha.Product.attributes]. - - For - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION], - the following fields are always returned in - [SearchResponse][google.cloud.retail.v2alpha.SearchResponse] - by default: - - - [name][google.cloud.retail.v2alpha.Product.name] - - For - [Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT], - the following fields are always returned in by default: - - - [name][google.cloud.retail.v2alpha.Product.name] - - [color_info][google.cloud.retail.v2alpha.Product.color_info] - - Maximum number of paths is 30. Otherwise, an - INVALID_ARGUMENT error is returned. - - Note: Returning more fields in - [SearchResponse][google.cloud.retail.v2alpha.SearchResponse] - may increase response payload size and serving latency. - variants (Sequence[google.cloud.retail_v2alpha.types.Product]): - Output only. Product variants grouped together on primary - product which share similar product attributes. It's - automatically grouped by - [primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] - for all the product variants. Only populated for - [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2alpha.ProductService.GetProduct]. - Do not set this field in API requests. - """ - class Type(proto.Enum): - r"""The type of this product.""" - TYPE_UNSPECIFIED = 0 - PRIMARY = 1 - VARIANT = 2 - COLLECTION = 3 - - class Availability(proto.Enum): - r"""Product availability. If this field is unspecified, the - product is assumed to be in stock. - """ - AVAILABILITY_UNSPECIFIED = 0 - IN_STOCK = 1 - OUT_OF_STOCK = 2 - PREORDER = 3 - BACKORDER = 4 - - expire_time = proto.Field( - proto.MESSAGE, - number=16, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl = proto.Field( - proto.MESSAGE, - number=17, - oneof='expiration', - message=duration_pb2.Duration, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - type_ = proto.Field( - proto.ENUM, - number=3, - enum=Type, - ) - primary_product_id = proto.Field( - proto.STRING, - number=4, - ) - collection_member_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - gtin = proto.Field( - proto.STRING, - number=6, - ) - categories = proto.RepeatedField( - proto.STRING, - number=7, - ) - title = proto.Field( - proto.STRING, - number=8, - ) - brands = proto.RepeatedField( - proto.STRING, - number=9, - ) - description = proto.Field( - proto.STRING, - number=10, - ) - language_code = proto.Field( - proto.STRING, - number=11, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=12, - message=common.CustomAttribute, - ) - tags = proto.RepeatedField( - proto.STRING, - number=13, - ) - price_info = proto.Field( - proto.MESSAGE, - number=14, - message=common.PriceInfo, - ) - rating = proto.Field( - proto.MESSAGE, - number=15, - message=common.Rating, - ) - available_time = proto.Field( - proto.MESSAGE, - number=18, - message=timestamp_pb2.Timestamp, - ) - availability = proto.Field( - proto.ENUM, - number=19, - enum=Availability, - ) - available_quantity = proto.Field( - proto.MESSAGE, - number=20, - message=wrappers_pb2.Int32Value, - ) - fulfillment_info = proto.RepeatedField( - proto.MESSAGE, - number=21, - message=common.FulfillmentInfo, - ) - uri = proto.Field( - proto.STRING, - number=22, - ) - images = proto.RepeatedField( - proto.MESSAGE, - number=23, - message=common.Image, - ) - audience = proto.Field( - proto.MESSAGE, - number=24, - message=common.Audience, - ) - color_info = proto.Field( - proto.MESSAGE, - number=25, - message=common.ColorInfo, - ) - sizes = proto.RepeatedField( - proto.STRING, - number=26, - ) - materials = proto.RepeatedField( - proto.STRING, - number=27, - ) - patterns = proto.RepeatedField( - proto.STRING, - number=28, - ) - conditions = proto.RepeatedField( - proto.STRING, - number=29, - ) - promotions = proto.RepeatedField( - proto.MESSAGE, - number=34, - message=promotion.Promotion, - ) - publish_time = proto.Field( - proto.MESSAGE, - number=33, - message=timestamp_pb2.Timestamp, - ) - retrievable_fields = proto.Field( - proto.MESSAGE, - number=30, - message=field_mask_pb2.FieldMask, - ) - variants = proto.RepeatedField( - proto.MESSAGE, - number=31, - message='Product', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py deleted file mode 100644 index ddfc08ed..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/product_service.py +++ /dev/null @@ -1,877 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'CreateProductRequest', - 'GetProductRequest', - 'UpdateProductRequest', - 'DeleteProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'SetInventoryRequest', - 'SetInventoryMetadata', - 'SetInventoryResponse', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesResponse', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesResponse', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesResponse', - }, -) - - -class CreateProductRequest(proto.Message): - r"""Request message for [CreateProduct][] method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - product (google.cloud.retail_v2alpha.types.Product): - Required. The [Product][google.cloud.retail.v2alpha.Product] - to create. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2alpha.Product], which will - become the final component of the - [Product.name][google.cloud.retail.v2alpha.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2alpha.Product]s with the - same - [parent][google.cloud.retail.v2alpha.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - product_id = proto.Field( - proto.STRING, - number=3, - ) - - -class GetProductRequest(proto.Message): - r"""Request message for [GetProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested - [Product][google.cloud.retail.v2alpha.Product] does not - exist, a NOT_FOUND error is returned. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateProductRequest(proto.Message): - r"""Request message for [UpdateProduct][] method. - - Attributes: - product (google.cloud.retail_v2alpha.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Product][google.cloud.retail.v2alpha.Product] to update. - The immutable and output only fields are NOT supported. If - not set, all supported fields (the fields that are neither - immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - a new [Product][google.cloud.retail.v2alpha.Product] will be - created. In this situation, ``update_mask`` is ignored. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteProductRequest(proto.Message): - r"""Request message for [DeleteProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2alpha.Product] to delete - can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] with more - than one - [variants][google.cloud.retail.v2alpha.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2alpha.Product] will be - deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProductsRequest(proto.Message): - r"""Request message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - - Attributes: - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list products - under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2alpha.Product]s under this - branch, regardless of whether or not this branch exists, a - PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of - [Product][google.cloud.retail.v2alpha.Product]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 - [ListProductsResponse.next_page_token][google.cloud.retail.v2alpha.ListProductsResponse.next_page_token], - received from a previous - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - filter (str): - A filter to apply on the list results. Supported features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2alpha.ListProductsRequest.filter] - is unset. - - List - [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s sharing - the same - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product]. For - example: ``primary_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2alpha.Product]s - bundled in a - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product]. For - example: ``collection_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2alpha.Product]s with - a partibular type. For example: ``type = "PRIMARY"`` - ``type = "VARIANT"`` ``type = "COLLECTION"`` - - If the field is unrecognizable, an INVALID_ARGUMENT error is - returned. - - If the specified - [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2alpha.Product] or - [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2alpha.Product] does not - exist, a NOT_FOUND error is returned. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields of [Product][google.cloud.retail.v2alpha.Product] - to return in the responses. If not set or empty, the - following fields are returned: - - - [Product.name][google.cloud.retail.v2alpha.Product.name] - - [Product.id][google.cloud.retail.v2alpha.Product.id] - - [Product.title][google.cloud.retail.v2alpha.Product.title] - - [Product.uri][google.cloud.retail.v2alpha.Product.uri] - - [Product.images][google.cloud.retail.v2alpha.Product.images] - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.brands][google.cloud.retail.v2alpha.Product.brands] - - If "*" is provided, all fields are returned. - [Product.name][google.cloud.retail.v2alpha.Product.name] is - always returned no matter what mask is set. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - require_total_size (bool): - If true and - [page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] - is empty, - [ListProductsResponse.total_size][google.cloud.retail.v2alpha.ListProductsResponse.total_size] - is set to the total count of matched items irrespective of - pagination. - - Notice that setting this field to true affects the - performance. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - require_total_size = proto.Field( - proto.BOOL, - number=6, - ) - - -class ListProductsResponse(proto.Message): - r"""Response message for - [ProductService.ListProducts][google.cloud.retail.v2alpha.ProductService.ListProducts] - method. - - Attributes: - products (Sequence[google.cloud.retail_v2alpha.types.Product]): - The [Product][google.cloud.retail.v2alpha.Product]s. - next_page_token (str): - A token that can be sent as - [ListProductsRequest.page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - total_size (int): - The total count of matched - [Product][google.cloud.retail.v2alpha.Product]s irrespective - of pagination. The total number of - [Product][google.cloud.retail.v2alpha.Product]s returned by - pagination may be less than the - [total_size][google.cloud.retail.v2alpha.ListProductsResponse.total_size] - that matches. - - This field is ignored if - [ListProductsRequest.require_total_size][google.cloud.retail.v2alpha.ListProductsRequest.require_total_size] - is not set or - [ListProductsRequest.page_token][google.cloud.retail.v2alpha.ListProductsRequest.page_token] - is not empty. - """ - - @property - def raw_page(self): - return self - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - - -class SetInventoryRequest(proto.Message): - r"""Request message for [SetInventory][] method. - - Attributes: - inventory (google.cloud.retail_v2alpha.types.Product): - Required. The inventory information to update. The allowable - fields to update are: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2alpha.Product] named in - [Product.name][google.cloud.retail.v2alpha.Product.name], - regardless of whether or not it exists, a PERMISSION_DENIED - error is returned. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2alpha.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting the - last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2alpha.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of fulfillment - types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2alpha.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear in - [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types have - empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following inventory - fields: - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2alpha.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2alpha.Product.fulfillment_info] - - If a full overwrite of inventory information while ignoring - timestamps is needed, [UpdateProduct][] should be invoked - instead. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2alpha.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the request is issued, used to - prevent out-of-order updates on inventory fields - with the last update time recorded. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] with name - [Product.name][google.cloud.retail.v2alpha.Product.name] is - not found, the inventory update will still be processed and - retained for at most 1 day until the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - inventory = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - set_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - set_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=4, - ) - - -class SetInventoryMetadata(proto.Message): - r"""Metadata related to the progress of the SetInventory operation. - Currently empty because there is no meaningful metadata populated - from the [SetInventory][] method. - - """ - - -class SetInventoryResponse(proto.Message): - r"""Response of the SetInventoryRequest. Currently empty because there - is no meaningful response populated from the [SetInventory][] - method. - - """ - - -class AddFulfillmentPlacesRequest(proto.Message): - r"""Request message for [AddFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery" to be added for this - [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type]. - Duplicate IDs will be automatically ignored. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If the total number of place IDs exceeds 2000 for this - [type][google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type] - after adding, then the update will be rejected. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - the fulfillment information will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - add_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class AddFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the AddFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [AddFulfillmentPlaces][] method. - - """ - - -class AddFulfillmentPlacesResponse(proto.Message): - r"""Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - - -class AddLocalInventoriesRequest(proto.Message): - r"""Request message for [AddLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - local_inventories (Sequence[google.cloud.retail_v2alpha.types.LocalInventory]): - Required. A list of inventory information at - difference places. Each place is identified by - its place ID. At most 3000 inventories are - allowed per request. - add_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided list of - [LocalInventory][google.cloud.retail.v2alpha.LocalInventory] - to update. The field is updated to the provided value. - - If a field is set while the place does not have a previous - local inventory, the local inventory at that store is - created. - - If a field is set while the value of that field is not - provided, the original field value, if it exists, is - deleted. - - If the mask is not set or set with empty paths, all - inventory fields will be updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory updates are - issued. Used to prevent out-of-order updates on - local inventory fields. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - the local inventory will still be processed and retained for - at most 1 day and processed once the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - local_inventories = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.LocalInventory, - ) - add_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - add_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=6, - ) - - -class AddLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the AddLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [AddLocalInventories][] method. - - """ - - -class AddLocalInventoriesResponse(proto.Message): - r"""Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesRequest(proto.Message): - r"""Request message for [RemoveLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - place_ids (Sequence[str]): - Required. A list of place IDs to have their - inventory deleted. At most 3000 place IDs are - allowed per request. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory deletions are - issued. Used to prevent out-of-order updates and - deletions on local inventory fields. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - the local inventory removal request will still be processed - and retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class RemoveLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesResponse(proto.Message): - r"""Response of the [RemoveLocalInventories][] API. Currently empty - because there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - - -class RemoveFulfillmentPlacesRequest(proto.Message): - r"""Request message for [RemoveFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2alpha.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2alpha.Product], regardless - of whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery", to be removed for this - [type][google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type]. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2alpha.Product] is not found, - the fulfillment information will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2alpha.Product] is created. - If set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2alpha.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class RemoveFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveFulfillmentPlaces][] method. - - """ - - -class RemoveFulfillmentPlacesResponse(proto.Message): - r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty - because there is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py deleted file mode 100644 index bd5b8a58..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/promotion.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'Promotion', - }, -) - - -class Promotion(proto.Message): - r"""Promotion information. - - Attributes: - promotion_id (str): - ID of the promotion. For example, "free gift". - - The value must be a UTF-8 encoded string with a length limit - of 128 characters, and match the pattern: - ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or - ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is - returned. - - Google Merchant Center property - `promotion `__. - """ - - promotion_id = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py deleted file mode 100644 index ad7ff6f6..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/purge_config.py +++ /dev/null @@ -1,251 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'PurgeMetadata', - 'PurgeProductsMetadata', - 'PurgeProductsRequest', - 'PurgeProductsResponse', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - }, -) - - -class PurgeMetadata(proto.Message): - r"""Metadata related to the progress of the Purge operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - """ - - -class PurgeProductsMetadata(proto.Message): - r"""Metadata related to the progress of the PurgeProducts - operation. This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were deleted - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=3, - ) - failure_count = proto.Field( - proto.INT64, - number=4, - ) - - -class PurgeProductsRequest(proto.Message): - r"""Request message for PurgeProducts method. - - Attributes: - parent (str): - Required. The resource name of the branch under which the - products are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}/branches/${branchId}`` - filter (str): - Required. The filter string to specify the products to be - deleted with a length limit of 5,000 characters. - - Empty string filter is not allowed. "*" implies delete all - items in a branch. - - The eligible fields for filtering are: - - - ``availability``: Double quoted - [Product.availability][google.cloud.retail.v2alpha.Product.availability] - string. - - ``create_time`` : in ISO 8601 "zulu" format. - - Supported syntax: - - - Comparators (">", "<", ">=", "<=", "="). Examples: - - - create_time <= "2015-02-13T17:05:46Z" - - availability = "IN_STOCK" - - - Conjunctions ("AND") Examples: - - - create_time <= "2015-02-13T17:05:46Z" AND availability - = "PREORDER" - - - Disjunctions ("OR") Examples: - - - create_time <= "2015-02-13T17:05:46Z" OR availability - = "IN_STOCK" - - - Can support nested queries. Examples: - - - (create_time <= "2015-02-13T17:05:46Z" AND - availability = "PREORDER") OR (create_time >= - "2015-02-14T13:03:32Z" AND availability = "IN_STOCK") - - - Filter Limits: - - - Filter should not contain more than 6 conditions. - - Max nesting depth should not exceed 2 levels. - - Examples queries: - - - Delete back order products created before a timestamp. - create_time <= "2015-02-13T17:05:46Z" OR availability = - "BACKORDER". - force (bool): - Actually perform the purge. If ``force`` is set to false, - the method will return the expected purge count without - deleting any products. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeProductsResponse(proto.Message): - r"""Response of the PurgeProductsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purge_count (int): - The total count of products purged as a - result of the operation. - purge_sample (Sequence[str]): - A sample of the product names that will be deleted. Only - populated if ``force`` is set to false. A max of 100 names - will be returned and the names are chosen at random. - """ - - purge_count = proto.Field( - proto.INT64, - number=1, - ) - purge_sample = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class PurgeUserEventsRequest(proto.Message): - r"""Request message for PurgeUserEvents method. - - Attributes: - parent (str): - Required. The resource name of the catalog under which the - events are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}`` - filter (str): - Required. The filter string to specify the events to be - deleted with a length limit of 5,000 characters. Empty - string filter is not allowed. The eligible fields for - filtering are: - - - ``eventType``: Double quoted - [UserEvent.event_type][google.cloud.retail.v2alpha.UserEvent.event_type] - string. - - ``eventTime``: in ISO 8601 "zulu" format. - - ``visitorId``: Double quoted string. Specifying this will - delete all events associated with a visitor. - - ``userId``: Double quoted string. Specifying this will - delete all events associated with a user. - - Examples: - - - Deleting all events in a time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - - Deleting specific eventType in time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` - - Deleting all events for a specific visitor: - ``visitorId = "visitor1024"`` - - The filtering fields are assumed to have an implicit AND. - force (bool): - Actually perform the purge. If ``force`` is set to false, - the method will return the expected purge count without - deleting any user events. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeUserEventsResponse(proto.Message): - r"""Response of the PurgeUserEventsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purged_events_count (int): - The total count of events purged as a result - of the operation. - """ - - purged_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py deleted file mode 100644 index e4dc0ba2..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/search_service.py +++ /dev/null @@ -1,1099 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'SearchRequest', - 'SearchResponse', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - - Attributes: - placement (str): - Required. The resource name of the search engine placement, - such as - ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` - This field is used to identify the serving configuration - name and the set of models that will be used to make the - search. - branch (str): - The branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - - Use "default_branch" as the branch ID or leave this field - empty, to search products under the default branch. - query (str): - Raw search query. - visitor_id (str): - Required. A unique identifier for tracking visitors. For - example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - This should be the same identifier as - [UserEvent.visitor_id][google.cloud.retail.v2alpha.UserEvent.visitor_id]. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2alpha.types.UserInfo): - User information. - page_size (int): - Maximum number of - [Product][google.cloud.retail.v2alpha.Product]s to return. - If unspecified, defaults to a reasonable value. The maximum - allowed value is 120. Values above 120 will be coerced to - 120. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [SearchResponse.next_page_token][google.cloud.retail.v2alpha.SearchResponse.next_page_token], - received from a previous - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - offset (int): - A 0-indexed integer that specifies the current offset (that - is, starting result location, amongst the - [Product][google.cloud.retail.v2alpha.Product]s deemed by - the API as relevant) in search results. This field is only - considered if - [page_token][google.cloud.retail.v2alpha.SearchRequest.page_token] - is unset. - - If this field is negative, an INVALID_ARGUMENT is returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. Filter expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - canonical_filter (str): - The default filter that is applied when a user performs a - search without checking any filters on the search page. - - The filter applied to every search request when quality - improvement such as query expansion is needed. For example, - if a query does not have enough results, an expanded query - with - [SearchRequest.canonical_filter][google.cloud.retail.v2alpha.SearchRequest.canonical_filter] - will be returned as a supplement of the original query. This - field is strongly recommended to achieve high search - quality. - - See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for more details about filter syntax. - order_by (str): - The order in which products are returned. Products can be - ordered by a field in an - [Product][google.cloud.retail.v2alpha.Product] object. Leave - it unset if ordered by relevance. OrderBy expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - facet_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec]): - Facet specifications for faceted search. If empty, no facets - are returned. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - dynamic_facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec): - Deprecated. Refer to - https://cloud.google.com/retail/docs/configs#dynamic - to enable dynamic facets. Do not set this field. - The specification for dynamically generated - facets. Notice that only textual facets can be - dynamically generated. - boost_spec (google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec): - Boost specification to boost certain products. See more - details at this `user - guide `__. - - Notice that if both - [ServingConfig.boost_control_ids][google.cloud.retail.v2alpha.ServingConfig.boost_control_ids] - and [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. - query_expansion_spec (google.cloud.retail_v2alpha.types.SearchRequest.QueryExpansionSpec): - The query expansion specification that specifies the - conditions under which query expansion will occur. See more - details at this `user - guide `__. - relevance_threshold (google.cloud.retail_v2alpha.types.SearchRequest.RelevanceThreshold): - The relevance threshold of the search results. - - Defaults to - [RelevanceThreshold.HIGH][google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH], - which means only the most relevant results are shown, and - the least number of results are returned. See more details - at this `user - guide `__. - variant_rollup_keys (Sequence[str]): - The keys to fetch and rollup the matching - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s attributes, - [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo] - or - [LocalInventory][google.cloud.retail.v2alpha.LocalInventory]s - attributes. The attributes from all the matching - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s or - [LocalInventory][google.cloud.retail.v2alpha.LocalInventory]s - are merged and de-duplicated. Notice that rollup attributes - will lead to extra query latency. Maximum number of keys is - 30. - - For - [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], - a fulfillment type and a fulfillment ID must be provided in - the format of "fulfillmentType.fulfillmentId". E.g., in - "pickupInStore.store123", "pickupInStore" is fulfillment - type and "store123" is the store ID. - - Supported keys are: - - - colorFamilies - - price - - originalPrice - - discount - - variantId - - inventory(place_id,price) - - inventory(place_id,original_price) - - inventory(place_id,attributes.key), where key is any key - in the [Product.inventories.attributes][] map. - - attributes.key, where key is any key in the - [Product.attributes][google.cloud.retail.v2alpha.Product.attributes] - map. - - pickupInStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "pickup-in-store". - - shipToStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "ship-to-store". - - sameDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "same-day-delivery". - - nextDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "next-day-delivery". - - customFulfillment1.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-1". - - customFulfillment2.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-2". - - customFulfillment3.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-3". - - customFulfillment4.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-4". - - customFulfillment5.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - "custom-type-5". - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. Required for - category navigation queries to achieve good search quality. - The format should be the same as - [UserEvent.page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories]; - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - search_mode (google.cloud.retail_v2alpha.types.SearchRequest.SearchMode): - The search mode of the search request. If not - specified, a single search request triggers both - product search and faceted search. - personalization_spec (google.cloud.retail_v2alpha.types.SearchRequest.PersonalizationSpec): - The specification for personalization. - """ - class RelevanceThreshold(proto.Enum): - r"""The relevance threshold of the search results. The higher - relevance threshold is, the higher relevant results are shown - and the less number of results are returned. - """ - RELEVANCE_THRESHOLD_UNSPECIFIED = 0 - HIGH = 1 - MEDIUM = 2 - LOW = 3 - LOWEST = 4 - - class SearchMode(proto.Enum): - r"""The search mode of each search request.""" - SEARCH_MODE_UNSPECIFIED = 0 - PRODUCT_SEARCH_ONLY = 1 - FACETED_SEARCH_ONLY = 2 - - class FacetSpec(proto.Message): - r"""A facet specification to perform faceted search. - - Attributes: - facet_key (google.cloud.retail_v2alpha.types.SearchRequest.FacetSpec.FacetKey): - Required. The facet key specification. - limit (int): - Maximum of facet values that should be returned for this - facet. If unspecified, defaults to 20. The maximum allowed - value is 300. Values above 300 will be coerced to 300. - - If this field is negative, an INVALID_ARGUMENT is returned. - excluded_filter_keys (Sequence[str]): - List of keys to exclude when faceting. - - By default, - [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] - is not excluded from the filter unless it is listed in this - field. - - For example, suppose there are 100 products with color facet - "Red" and 200 products with color facet "Blue". A query - containing the filter "colorFamilies:ANY("Red")" and have - "colorFamilies" as - [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] - will by default return the "Red" with count 100. - - If this field contains "colorFamilies", then the query - returns both the "Red" with count 100 and "Blue" with count - 200, because the "colorFamilies" key is now excluded from - the filter. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - enable_dynamic_position (bool): - Enables dynamic position for this facet. If set to true, the - position of this facet among all facets in the response is - determined by Google Retail Search. It will be ordered - together with dynamic facets if dynamic facets is enabled. - If set to false, the position of this facet in the response - will be the same as in the request, and it will be ranked - before the facets with dynamic position enable and all - dynamic facets. - - For example, you may always want to have rating facet - returned in the response, but it's not necessarily to always - display the rating facet at the top. In that case, you can - set enable_dynamic_position to true so that the position of - rating facet in response will be determined by Google Retail - Search. - - Another example, assuming you have the following facets in - the request: - - - "rating", enable_dynamic_position = true - - - "price", enable_dynamic_position = false - - - "brands", enable_dynamic_position = false - - And also you have a dynamic facets enable, which will - generate a facet 'gender'. Then the final order of the - facets in the response can be ("price", "brands", "rating", - "gender") or ("price", "brands", "gender", "rating") depends - on how Google Retail Search orders "gender" and "rating" - facets. However, notice that "price" and "brands" will - always be ranked at 1st and 2nd position since their - enable_dynamic_position are false. - """ - - class FacetKey(proto.Message): - r"""Specifies how a facet is computed. - - Attributes: - key (str): - Required. Supported textual and numerical facet keys in - [Product][google.cloud.retail.v2alpha.Product] object, over - which the facet values are computed. Facet key is - case-sensitive. - - Allowed facet keys when - [FacetKey.query][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.query] - is not specified: - - - textual_field = - - - "brands" - - "categories" - - "genders" - - "ageGroups" - - "availability" - - "colorFamilies" - - "colors" - - "sizes" - - "materials" - - "patterns" - - "conditions" - - "attributes.key" - - "pickupInStore" - - "shipToStore" - - "sameDayDelivery" - - "nextDayDelivery" - - "customFulfillment1" - - "customFulfillment2" - - "customFulfillment3" - - "customFulfillment4" - - "customFulfillment5" - - "inventory(place_id,attributes.key)" - - - numerical_field = - - - "price" - - "discount" - - "rating" - - "ratingCount" - - "attributes.key" - - "inventory(place_id,price)" - - "inventory(place_id,original_price)" - - "inventory(place_id,attributes.key)". - intervals (Sequence[google.cloud.retail_v2alpha.types.Interval]): - Set only if values should be bucketized into - intervals. Must be set for facets with numerical - values. Must not be set for facet with text - values. Maximum number of intervals is 30. - restricted_values (Sequence[str]): - Only get facet for the given restricted values. For example, - when using "pickupInStore" as key and set restricted values - to ["store123", "store456"], only facets for "store123" and - "store456" are returned. Only supported on textual fields - and fulfillments. Maximum is 20. - - Must be set for the fulfillment facet keys: - - - pickupInStore - - - shipToStore - - - sameDayDelivery - - - nextDayDelivery - - - customFulfillment1 - - - customFulfillment2 - - - customFulfillment3 - - - customFulfillment4 - - - customFulfillment5 - prefixes (Sequence[str]): - Only get facet values that start with the - given string prefix. For example, suppose - "categories" has three values "Women > Shoe", - "Women > Dress" and "Men > Shoe". If set - "prefixes" to "Women", the "categories" facet - will give only "Women > Shoe" and "Women > - Dress". Only supported on textual fields. - Maximum is 10. - contains (Sequence[str]): - Only get facet values that contains the given - strings. For example, suppose "categories" has - three values "Women > Shoe", "Women > Dress" and - "Men > Shoe". If set "contains" to "Shoe", the - "categories" facet will give only "Women > Shoe" - and "Men > Shoe". Only supported on textual - fields. Maximum is 10. - order_by (str): - The order in which [Facet.values][] are returned. - - Allowed values are: - - - "count desc", which means order by - [Facet.FacetValue.count][] descending. - - - "value desc", which means order by - [Facet.FacetValue.value][] descending. Only applies to - textual facets. - - If not set, textual values are sorted in `natural - order `__; - numerical intervals are sorted in the order given by - [FacetSpec.FacetKey.intervals][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.intervals]; - [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] - are sorted in the order given by - [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.restricted_values]. - query (str): - The query that is used to compute facet for the given facet - key. When provided, it will override the default behavior of - facet computation. The query syntax is the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for detail syntax and limitations. Notice that there is no - limitation on - [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] - when query is specified. - - In the response, [FacetValue.value][] will be always "1" and - [FacetValue.count][] will be the number of results that - matches the query. - - For example, you can set a customized facet for - "shipToStore", where - [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] - is "customizedShipToStore", and - [FacetKey.query][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.query] - is "availability: ANY("IN_STOCK") AND shipToStore: - ANY("123")". Then the facet will count the products that are - both in stock and ship to store "123". - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - intervals = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Interval, - ) - restricted_values = proto.RepeatedField( - proto.STRING, - number=3, - ) - prefixes = proto.RepeatedField( - proto.STRING, - number=8, - ) - contains = proto.RepeatedField( - proto.STRING, - number=9, - ) - order_by = proto.Field( - proto.STRING, - number=4, - ) - query = proto.Field( - proto.STRING, - number=5, - ) - - facet_key = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.FacetSpec.FacetKey', - ) - limit = proto.Field( - proto.INT32, - number=2, - ) - excluded_filter_keys = proto.RepeatedField( - proto.STRING, - number=3, - ) - enable_dynamic_position = proto.Field( - proto.BOOL, - number=4, - ) - - class DynamicFacetSpec(proto.Message): - r"""The specifications of dynamically generated facets. - - Attributes: - mode (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec.Mode): - Mode of the DynamicFacet feature. Defaults to - [Mode.DISABLED][google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec.Mode.DISABLED] - if it's unset. - """ - class Mode(proto.Enum): - r"""Enum to control DynamicFacet mode""" - MODE_UNSPECIFIED = 0 - DISABLED = 1 - ENABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.DynamicFacetSpec.Mode', - ) - - class BoostSpec(proto.Message): - r"""Boost specification to boost certain items. - - Attributes: - condition_boost_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - Condition boost specifications. If a product - matches multiple conditions in the - specifictions, boost scores from these - specifications are all applied and combined in a - non-linear way. Maximum number of specifications - is 10. - skip_boost_spec_validation (bool): - Whether to skip boostspec validation. If this field is set - to true, invalid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] - will be ignored and valid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] - will still be applied. - - This field is a member of `oneof`_ ``_skip_boost_spec_validation``. - """ - - class ConditionBoostSpec(proto.Message): - r"""Boost applies to products which match a condition. - - Attributes: - condition (str): - An expression which specifies a boost condition. The syntax - and supported fields are the same as a filter expression. - See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": - - - (id: ANY("product_1", "product_2")) AND - (colorFamilies: ANY("Red","Blue")) - boost (float): - Strength of the condition boost, which should be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - """ - - condition = proto.Field( - proto.STRING, - number=1, - ) - boost = proto.Field( - proto.FLOAT, - number=2, - ) - - condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - skip_boost_spec_validation = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - - class QueryExpansionSpec(proto.Message): - r"""Specification to determine under which conditions query - expansion should occur. - - Attributes: - condition (google.cloud.retail_v2alpha.types.SearchRequest.QueryExpansionSpec.Condition): - The condition under which query expansion should occur. - Default to - [Condition.DISABLED][google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - pin_unexpanded_results (bool): - Whether to pin unexpanded results. If this - field is set to true, unexpanded products are - always at the top of the search results, - followed by the expanded results. - """ - class Condition(proto.Enum): - r"""Enum describing under which condition query expansion should - occur. - """ - CONDITION_UNSPECIFIED = 0 - DISABLED = 1 - AUTO = 3 - - condition = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.QueryExpansionSpec.Condition', - ) - pin_unexpanded_results = proto.Field( - proto.BOOL, - number=2, - ) - - class PersonalizationSpec(proto.Message): - r"""The specification for personalization. - - Attributes: - mode (google.cloud.retail_v2alpha.types.SearchRequest.PersonalizationSpec.Mode): - Defaults to - [Mode.AUTO][google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""The personalization mode of each search request.""" - MODE_UNSPECIFIED = 0 - AUTO = 1 - DISABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.PersonalizationSpec.Mode', - ) - - placement = proto.Field( - proto.STRING, - number=1, - ) - branch = proto.Field( - proto.STRING, - number=2, - ) - query = proto.Field( - proto.STRING, - number=3, - ) - visitor_id = proto.Field( - proto.STRING, - number=4, - ) - user_info = proto.Field( - proto.MESSAGE, - number=5, - message=common.UserInfo, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - offset = proto.Field( - proto.INT32, - number=9, - ) - filter = proto.Field( - proto.STRING, - number=10, - ) - canonical_filter = proto.Field( - proto.STRING, - number=28, - ) - order_by = proto.Field( - proto.STRING, - number=11, - ) - facet_specs = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=FacetSpec, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=21, - message=DynamicFacetSpec, - ) - boost_spec = proto.Field( - proto.MESSAGE, - number=13, - message=BoostSpec, - ) - query_expansion_spec = proto.Field( - proto.MESSAGE, - number=14, - message=QueryExpansionSpec, - ) - relevance_threshold = proto.Field( - proto.ENUM, - number=15, - enum=RelevanceThreshold, - ) - variant_rollup_keys = proto.RepeatedField( - proto.STRING, - number=17, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=23, - ) - search_mode = proto.Field( - proto.ENUM, - number=31, - enum=SearchMode, - ) - personalization_spec = proto.Field( - proto.MESSAGE, - number=32, - message=PersonalizationSpec, - ) - - -class SearchResponse(proto.Message): - r"""Response message for - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search] - method. - - Attributes: - results (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.SearchResult]): - A list of matched items. The order represents - the ranking. - facets (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.Facet]): - Results of facets requested by user. - total_size (int): - The estimated total count of matched items irrespective of - pagination. The count of - [results][google.cloud.retail.v2alpha.SearchResponse.results] - returned by pagination may be less than the - [total_size][google.cloud.retail.v2alpha.SearchResponse.total_size] - that matches. - corrected_query (str): - If spell correction applies, the corrected - query. Otherwise, empty. - attribution_token (str): - A unique search token. This should be included in the - [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs - resulting from this search, which enables accurate - attribution of search model performance. - next_page_token (str): - A token that can be sent as - [SearchRequest.page_token][google.cloud.retail.v2alpha.SearchRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - query_expansion_info (google.cloud.retail_v2alpha.types.SearchResponse.QueryExpansionInfo): - Query expansion information for the returned - results. - redirect_uri (str): - The URI of a customer-defined redirect page. If redirect - action is triggered, no search will be performed, and only - [redirect_uri][google.cloud.retail.v2alpha.SearchResponse.redirect_uri] - and - [attribution_token][google.cloud.retail.v2alpha.SearchResponse.attribution_token] - will be set in the response. - applied_controls (Sequence[str]): - The fully qualified resource name of applied - `controls `__. - invalid_condition_boost_specs (Sequence[google.cloud.retail_v2alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - The invalid - [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2alpha.SearchRequest.BoostSpec.condition_boost_specs] - that are not applied during serving. - """ - - class SearchResult(proto.Message): - r"""Represents the search results. - - Attributes: - id (str): - [Product.id][google.cloud.retail.v2alpha.Product.id] of the - searched [Product][google.cloud.retail.v2alpha.Product]. - product (google.cloud.retail_v2alpha.types.Product): - The product data snippet in the search response. Only - [Product.name][google.cloud.retail.v2alpha.Product.name] is - guaranteed to be populated. - - [Product.variants][google.cloud.retail.v2alpha.Product.variants] - contains the product variants that match the search query. - If there are multiple product variants matching the query, - top 5 most relevant product variants are returned and - ordered by relevancy. - - If relevancy can be deternmined, use - [matching_variant_fields][google.cloud.retail.v2alpha.SearchResponse.SearchResult.matching_variant_fields] - to look up matched product variants fields. If relevancy - cannot be determined, e.g. when searching "shoe" all - products in a shoe product can be a match, 5 product - variants are returned but order is meaningless. - matching_variant_count (int): - The count of matched - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product]s. - matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): - If a - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] matches the - search query, this map indicates which - [Product][google.cloud.retail.v2alpha.Product] fields are - matched. The key is the - [Product.name][google.cloud.retail.v2alpha.Product.name], - the value is a field mask of the matched - [Product][google.cloud.retail.v2alpha.Product] fields. If - matched attributes cannot be determined, this map will be - empty. - - For example, a key "sku1" with field mask - "products.color_info" indicates there is a match between - "sku1" [ColorInfo][google.cloud.retail.v2alpha.ColorInfo] - and the query. - variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): - The rollup matching - [variant][google.cloud.retail.v2alpha.Product.Type.VARIANT] - [Product][google.cloud.retail.v2alpha.Product] attributes. - The key is one of the - [SearchRequest.variant_rollup_keys][google.cloud.retail.v2alpha.SearchRequest.variant_rollup_keys]. - The values are the merged and de-duplicated - [Product][google.cloud.retail.v2alpha.Product] attributes. - Notice that the rollup values are respect filter. For - example, when filtering by "colorFamilies:ANY("red")" and - rollup "colorFamilies", only "red" is returned. - - For textual and numerical attributes, the rollup values is a - list of string or double values with type - [google.protobuf.ListValue][google.protobuf.ListValue]. For - example, if there are two variants with colors "red" and - "blue", the rollup values are - - :: - - { key: "colorFamilies" - value { - list_value { - values { string_value: "red" } - values { string_value: "blue" } - } - } - } - - For - [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], - the rollup values is a double value with type - [google.protobuf.Value][google.protobuf.Value]. For example, - ``{key: "pickupInStore.store1" value { number_value: 10 }}`` - means a there are 10 variants in this product are available - in the store "store1". - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - matching_variant_count = proto.Field( - proto.INT32, - number=3, - ) - matching_variant_fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - variant_rollup_values = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - - class Facet(proto.Message): - r"""A facet result. - - Attributes: - key (str): - The key for this facet. E.g., "colorFamilies" - or "price" or "attributes.attr1". - values (Sequence[google.cloud.retail_v2alpha.types.SearchResponse.Facet.FacetValue]): - The facet values for this field. - dynamic_facet (bool): - Whether the facet is dynamically generated. - """ - - class FacetValue(proto.Message): - r"""A facet value which contains value names and their count. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Text value of a facet, such as "Black" for - facet "colorFamilies". - - This field is a member of `oneof`_ ``facet_value``. - interval (google.cloud.retail_v2alpha.types.Interval): - Interval value for a facet, such as [10, 20) for facet - "price". - - This field is a member of `oneof`_ ``facet_value``. - count (int): - Number of items that have this facet value. - """ - - value = proto.Field( - proto.STRING, - number=1, - oneof='facet_value', - ) - interval = proto.Field( - proto.MESSAGE, - number=2, - oneof='facet_value', - message=common.Interval, - ) - count = proto.Field( - proto.INT64, - number=3, - ) - - key = proto.Field( - proto.STRING, - number=1, - ) - values = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SearchResponse.Facet.FacetValue', - ) - dynamic_facet = proto.Field( - proto.BOOL, - number=3, - ) - - class QueryExpansionInfo(proto.Message): - r"""Information describing query expansion including whether - expansion has occurred. - - Attributes: - expanded_query (bool): - Bool describing whether query expansion has - occurred. - pinned_result_count (int): - Number of pinned results. This field will only be set when - expansion happens and - [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] - is set to true. - """ - - expanded_query = proto.Field( - proto.BOOL, - number=1, - ) - pinned_result_count = proto.Field( - proto.INT64, - number=2, - ) - - @property - def raw_page(self): - return self - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=SearchResult, - ) - facets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Facet, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - corrected_query = proto.Field( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - next_page_token = proto.Field( - proto.STRING, - number=6, - ) - query_expansion_info = proto.Field( - proto.MESSAGE, - number=7, - message=QueryExpansionInfo, - ) - redirect_uri = proto.Field( - proto.STRING, - number=10, - ) - applied_controls = proto.RepeatedField( - proto.STRING, - number=12, - ) - invalid_condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py deleted file mode 100644 index c8c3ccca..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config.py +++ /dev/null @@ -1,309 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'ServingConfig', - }, -) - - -class ServingConfig(proto.Message): - r"""Configures metadata that is used to generate serving time results - (e.g. search results or recommendation predictions). The - ServingConfig is passed in the search and predict request and - together with the Catalog.default_branch, generates results. - - Attributes: - name (str): - Immutable. Fully qualified name - projects/\ */locations/global/catalogs/*/servingConfig/\* - display_name (str): - Required. The human readable serving config display name. - Used in Retail UI. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - model_id (str): - The id of the model to use at serving time. Currently only - RecommendationModels are supported: - https://cloud.google.com/retail/recommendations-ai/docs/create-models - Can be changed but only to a compatible model (e.g. - others-you-may-like CTR to others-you-may-like CVR). - - Required when - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - price_reranking_level (str): - How much price ranking we want in serving results. Price - reranking causes product items with a similar recommendation - probability to be ordered by price, with the highest-priced - items first. This setting could result in a decrease in - click-through and conversion rates. Allowed values are: - - - 'no-price-reranking' - - 'low-price-raranking' - - 'medium-price-reranking' - - 'high-price-reranking' - - If not specified, we choose default based on model type. - Default value: 'no-price-reranking'. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - facet_control_ids (Sequence[str]): - Facet specifications for faceted search. If empty, no facets - are returned. The ids refer to the ids of - [Control][google.cloud.retail.v2alpha.Control] resources - with only the Facet control set. These controls are assumed - to be in the same - [Catalog][google.cloud.retail.v2alpha.Catalog] as the - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig]. - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - dynamic_facet_spec (google.cloud.retail_v2alpha.types.SearchRequest.DynamicFacetSpec): - The specification for dynamically generated facets. Notice - that only textual facets can be dynamically generated. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - boost_control_ids (Sequence[str]): - Condition boost specifications. If a product matches - multiple conditions in the specifications, boost scores from - these specifications are all applied and combined in a - non-linear way. Maximum number of specifications is 100. - - Notice that if both - [ServingConfig.boost_control_ids][google.cloud.retail.v2alpha.ServingConfig.boost_control_ids] - and [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - filter_control_ids (Sequence[str]): - Condition filter specifications. If a product matches - multiple conditions in the specifications, filters from - these specifications are all applied and combined via the - AND operator. Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - redirect_control_ids (Sequence[str]): - Condition redirect specifications. Only the first triggered - redirect action is applied, even if multiple apply. Maximum - number of specifications is 1000. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - twoway_synonyms_control_ids (Sequence[str]): - Condition synonyms specifications. If multiple syonyms - conditions match, all matching synonyms control in the list - will execute. Order of controls in the list will not matter. - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - oneway_synonyms_control_ids (Sequence[str]): - Condition oneway synonyms specifications. If multiple oneway - synonyms conditions match, all matching oneway synonyms - controls in the list will execute. Order of controls in the - list will not matter. Maximum number of specifications is - 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - do_not_associate_control_ids (Sequence[str]): - Condition do not associate specifications. If multiple do - not associate conditions match, all matching do not - associate controls in the list will execute. - - - Order does not matter. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - replacement_control_ids (Sequence[str]): - Condition replacement specifications. - - - Applied according to the order in the list. - - A previously replaced term can not be re-replaced. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - ignore_control_ids (Sequence[str]): - Condition ignore specifications. If multiple ignore - conditions match, all matching ignore controls in the list - will execute. - - - Order does not matter. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - diversity_level (str): - How much diversity to use in recommendation model results - e.g. 'medium-diversity' or 'high-diversity'. Currently - supported values: - - - 'no-diversity' - - 'low-diversity' - - 'medium-diversity' - - 'high-diversity' - - 'auto-diversity' - - If not specified, we choose default based on recommendation - model type. Default value: 'no-diversity'. - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - enable_category_filter_level (str): - Whether to add additional category filters on the - 'similar-items' model. If not specified, we enable it by - default. Allowed values are: - - - 'no-category-match': No additional filtering of original - results from the model and the customer's filters. - - 'relaxed-category-match': Only keep results with - categories that match at least one item categories in the - PredictRequests's context item. - - - If customer also sends filters in the PredictRequest, - then the results will satisfy both conditions (user - given and category match). - - Can only be set if - [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - solution_types (Sequence[google.cloud.retail_v2alpha.types.SolutionType]): - Required. Immutable. Specifies the solution - types that a serving config can be associated - with. Currently we support setting only one type - of solution. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - model_id = proto.Field( - proto.STRING, - number=3, - ) - price_reranking_level = proto.Field( - proto.STRING, - number=4, - ) - facet_control_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=6, - message=search_service.SearchRequest.DynamicFacetSpec, - ) - boost_control_ids = proto.RepeatedField( - proto.STRING, - number=7, - ) - filter_control_ids = proto.RepeatedField( - proto.STRING, - number=9, - ) - redirect_control_ids = proto.RepeatedField( - proto.STRING, - number=10, - ) - twoway_synonyms_control_ids = proto.RepeatedField( - proto.STRING, - number=18, - ) - oneway_synonyms_control_ids = proto.RepeatedField( - proto.STRING, - number=12, - ) - do_not_associate_control_ids = proto.RepeatedField( - proto.STRING, - number=13, - ) - replacement_control_ids = proto.RepeatedField( - proto.STRING, - number=14, - ) - ignore_control_ids = proto.RepeatedField( - proto.STRING, - number=15, - ) - diversity_level = proto.Field( - proto.STRING, - number=8, - ) - enable_category_filter_level = proto.Field( - proto.STRING, - number=16, - ) - solution_types = proto.RepeatedField( - proto.ENUM, - number=19, - enum=common.SolutionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py deleted file mode 100644 index 635f42bb..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/serving_config_service.py +++ /dev/null @@ -1,234 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'CreateServingConfigRequest', - 'UpdateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'AddControlRequest', - 'RemoveControlRequest', - }, -) - - -class CreateServingConfigRequest(proto.Message): - r"""Request for CreateServingConfig method. - - Attributes: - parent (str): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - serving_config (google.cloud.retail_v2alpha.types.ServingConfig): - Required. The ServingConfig to create. - serving_config_id (str): - Required. The ID to use for the ServingConfig, which will - become the final component of the ServingConfig's resource - name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-_/. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - serving_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_serving_config.ServingConfig, - ) - serving_config_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateServingConfigRequest(proto.Message): - r"""Request for UpdateServingConfig method. - - Attributes: - serving_config (google.cloud.retail_v2alpha.types.ServingConfig): - Required. The ServingConfig to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [ServingConfig][google.cloud.retail.v2alpha.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2alpha.ServingConfig.name] - - If not set, all supported fields are updated. - """ - - serving_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_serving_config.ServingConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteServingConfigRequest(proto.Message): - r"""Request for DeleteServingConfig method. - - Attributes: - name (str): - Required. The resource name of the ServingConfig to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetServingConfigRequest(proto.Message): - r"""Request for GetServingConfig method. - - Attributes: - name (str): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListServingConfigsRequest(proto.Message): - r"""Request for ListServingConfigs method. - - Attributes: - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - page_size (int): - Optional. Maximum number of results to - return. If unspecified, defaults to 100. If a - value greater than 100 is provided, at most 100 - results are returned. - page_token (str): - Optional. A page token, received from a previous - ``ListServingConfigs`` call. Provide this to retrieve the - subsequent page. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListServingConfigsResponse(proto.Message): - r"""Response for ListServingConfigs method. - - Attributes: - serving_configs (Sequence[google.cloud.retail_v2alpha.types.ServingConfig]): - All the ServingConfigs for a given catalog. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - serving_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_serving_config.ServingConfig, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class AddControlRequest(proto.Message): - r"""Request for AddControl method. - - Attributes: - serving_config (str): - Required. The source ServingConfig resource name . Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - control_id (str): - Required. The id of the control to apply. Assumed to be in - the same catalog as the serving config - if id is not found - a NOT_FOUND error is returned. - """ - - serving_config = proto.Field( - proto.STRING, - number=1, - ) - control_id = proto.Field( - proto.STRING, - number=2, - ) - - -class RemoveControlRequest(proto.Message): - r"""Request for RemoveControl method. - - Attributes: - serving_config (str): - Required. The source ServingConfig resource name . Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - control_id (str): - Required. The id of the control to apply. - Assumed to be in the same catalog as the serving - config. - """ - - serving_config = proto.Field( - proto.STRING, - number=1, - ) - control_id = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py deleted file mode 100644 index f9d6a684..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event.py +++ /dev/null @@ -1,507 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'UserEvent', - 'ProductDetail', - 'CompletionDetail', - 'PurchaseTransaction', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information Retail API needs - to know about how end users interact with customers' website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - - ``add-to-cart``: Products being added to cart. - - ``category-page-view``: Special pages such as sale or - promotion pages viewed. - - ``detail-page-view``: Products detail page viewed. - - ``home-page-view``: Homepage viewed. - - ``promotion-offered``: Promotion is offered to a user. - - ``promotion-not-offered``: Promotion is not offered to a - user. - - ``purchase-complete``: User finishing a purchase. - - ``search``: Product search. - - ``shopping-cart-page-view``: User viewing a shopping - cart. - visitor_id (str): - Required. A unique identifier for tracking visitors. - - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor log in/out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - The field should not contain PII or user-data. We recommend - to use Google Analystics `Client - ID `__ - for this field. - session_id (str): - A unique identifier for tracking a visitor session with a - length limit of 128 bytes. A session is an aggregation of an - end user behavior in a time span. - - A general guideline to populate the sesion_id: - - 1. If user has no activity for 30 min, a new session_id - should be assigned. - 2. The session_id should be unique across users, suggest use - uuid or add visitor_id as prefix. - event_time (google.protobuf.timestamp_pb2.Timestamp): - Only required for - [UserEventService.ImportUserEvents][google.cloud.retail.v2alpha.UserEventService.ImportUserEvents] - method. Timestamp of when the user event happened. - experiment_ids (Sequence[str]): - A list of identifiers for the independent - experiment groups this user event belongs to. - This is used to distinguish between user events - associated with different experiment setups - (e.g. using Retail API, using different - recommendation models). - attribution_token (str): - Highly recommended for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2alpha.PredictionService.Predict]. - This field enables accurate attribution of recommendation - model performance. - - The value must be a valid - [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] - for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2alpha.PredictionService.Predict]. - The value must be a valid - [SearchResponse.attribution_token][google.cloud.retail.v2alpha.SearchResponse.attribution_token] - for user events that are the result of - [SearchService.Search][google.cloud.retail.v2alpha.SearchService.Search]. - - This token enables us to accurately attribute page view or - purchase back to the event and the particular predict - response containing this clicked/purchased product. If user - clicks on product K in the recommendation results, pass - [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] - as a URL parameter to product K's page. When recording - events on product K's page, log the - [PredictResponse.attribution_token][google.cloud.retail.v2alpha.PredictResponse.attribution_token] - to this field. - product_details (Sequence[google.cloud.retail_v2alpha.types.ProductDetail]): - The main product details related to the event. - - This field is required for the following event types: - - - ``add-to-cart`` - - ``detail-page-view`` - - ``purchase-complete`` - - ``search`` - - In a ``search`` event, this field represents the products - returned to the end user on the current page (the end user - may have not finished browsing the whole page yet). When a - new page is returned to the end user, after - pagination/filtering/ordering even for the same query, a new - ``search`` event with different - [product_details][google.cloud.retail.v2alpha.UserEvent.product_details] - is desired. The end user may have not finished browsing the - whole page yet. - completion_detail (google.cloud.retail_v2alpha.types.CompletionDetail): - The main auto-completion details related to the event. - - This field should be set for ``search`` event when - autocomplete function is enabled and the user clicks a - suggestion for search. - attributes (Mapping[str, google.cloud.retail_v2alpha.types.CustomAttribute]): - Extra user event features to include in the recommendation - model. - - If you provide custom attributes for ingested user events, - also include them in the user events that you associate with - prediction requests. Custom attribute formatting must be - consistent between imported events and events provided with - prediction requests. This lets the Retail API use those - custom attributes when training models and serving - predictions, which helps improve recommendation quality. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - The key must be a UTF-8 encoded string with a length - limit of 5,000 characters. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a UTF-8 - encoded string with a length limit of 256 characters. - - For number attributes, at most 400 values are allowed. - - For product recommendations, an example of extra user - information is traffic_channel, which is how a user arrives - at the site. Users can arrive at the site by coming to the - site directly, coming through Google search, or in other - ways. - cart_id (str): - The ID or name of the associated shopping cart. This ID is - used to associate multiple items added or present in the - cart before purchase. - - This can only be set for ``add-to-cart``, - ``purchase-complete``, or ``shopping-cart-page-view`` - events. - purchase_transaction (google.cloud.retail_v2alpha.types.PurchaseTransaction): - A transaction represents the entire purchase transaction. - - Required for ``purchase-complete`` events. Other event types - should not set this field. Otherwise, an INVALID_ARGUMENT - error is returned. - search_query (str): - The user's search query. - - See - [SearchRequest.query][google.cloud.retail.v2alpha.SearchRequest.query] - for definition. - - The value must be a UTF-8 encoded string with a length limit - of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - At least one of - [search_query][google.cloud.retail.v2alpha.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. - - See - [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - order_by (str): - The order in which products are returned. - - See - [SearchRequest.order_by][google.cloud.retail.v2alpha.SearchRequest.order_by] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - offset (int): - An integer that specifies the current offset for pagination - (the 0-indexed starting location, amongst the products - deemed by the API as relevant). - - See - [SearchRequest.offset][google.cloud.retail.v2alpha.SearchRequest.offset] - for definition. - - If this field is negative, an INVALID_ARGUMENT is returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - - Required for ``category-page-view`` events. At least one of - [search_query][google.cloud.retail.v2alpha.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2alpha.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2alpha.types.UserInfo): - User information. - uri (str): - Complete URL (window.location.href) of the - user's current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. Maximum length - 5,000 characters. - referrer_uri (str): - The referrer URL of the current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. - page_view_id (str): - A unique ID of a web page view. - - This should be kept the same for all user events triggered - from the same pageview. For example, an item detail page - view could trigger multiple events as the user is browsing - the page. The ``pageViewId`` property should be kept the - same for all these events so that they can be grouped - together properly. - - When using the client side event reporting with JavaScript - pixel and Google Tag Manager, this value is filled in - automatically. - """ - - event_type = proto.Field( - proto.STRING, - number=1, - ) - visitor_id = proto.Field( - proto.STRING, - number=2, - ) - session_id = proto.Field( - proto.STRING, - number=21, - ) - event_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - experiment_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - product_details = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='ProductDetail', - ) - completion_detail = proto.Field( - proto.MESSAGE, - number=22, - message='CompletionDetail', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=common.CustomAttribute, - ) - cart_id = proto.Field( - proto.STRING, - number=8, - ) - purchase_transaction = proto.Field( - proto.MESSAGE, - number=9, - message='PurchaseTransaction', - ) - search_query = proto.Field( - proto.STRING, - number=10, - ) - filter = proto.Field( - proto.STRING, - number=16, - ) - order_by = proto.Field( - proto.STRING, - number=17, - ) - offset = proto.Field( - proto.INT32, - number=18, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=11, - ) - user_info = proto.Field( - proto.MESSAGE, - number=12, - message=common.UserInfo, - ) - uri = proto.Field( - proto.STRING, - number=13, - ) - referrer_uri = proto.Field( - proto.STRING, - number=14, - ) - page_view_id = proto.Field( - proto.STRING, - number=15, - ) - - -class ProductDetail(proto.Message): - r"""Detailed product information associated with a user event. - - Attributes: - product (google.cloud.retail_v2alpha.types.Product): - Required. [Product][google.cloud.retail.v2alpha.Product] - information. - - Required field(s): - - - [Product.id][google.cloud.retail.v2alpha.Product.id] - - Optional override field(s): - - - [Product.price_info][google.cloud.retail.v2alpha.Product.price_info] - - If any supported optional fields are provided, we will treat - them as a full override when looking up product information - from the catalog. Thus, it is important to ensure that the - overriding fields are accurate and complete. - - All other product fields are ignored and instead populated - via catalog lookup after event ingestion. - quantity (google.protobuf.wrappers_pb2.Int32Value): - Quantity of the product associated with the user event. - - For example, this field will be 2 if two products are added - to the shopping cart for ``purchase-complete`` event. - Required for ``add-to-cart`` and ``purchase-complete`` event - types. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - quantity = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -class CompletionDetail(proto.Message): - r"""Detailed completion information including completion - attribution token and clicked completion info. - - Attributes: - completion_attribution_token (str): - Completion attribution token in - [CompleteQueryResponse.attribution_token][google.cloud.retail.v2alpha.CompleteQueryResponse.attribution_token]. - selected_suggestion (str): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2alpha.CompleteQueryResponse.CompletionResult.suggestion]. - selected_position (int): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2alpha.CompleteQueryResponse.CompletionResult.suggestion] - position, starting from 0. - """ - - completion_attribution_token = proto.Field( - proto.STRING, - number=1, - ) - selected_suggestion = proto.Field( - proto.STRING, - number=2, - ) - selected_position = proto.Field( - proto.INT32, - number=3, - ) - - -class PurchaseTransaction(proto.Message): - r"""A transaction represents the entire purchase transaction. - - Attributes: - id (str): - The transaction ID with a length limit of 128 - characters. - revenue (float): - Required. Total non-zero revenue or grand - total associated with the transaction. This - value include shipping, tax, or other - adjustments to total revenue that you want to - include as part of your revenue calculations. - tax (float): - All the taxes associated with the - transaction. - cost (float): - All the costs associated with the products. These can be - manufacturing costs, shipping expenses not borne by the end - user, or any other costs, such that: - - - Profit = - [revenue][google.cloud.retail.v2alpha.PurchaseTransaction.revenue] - - - [tax][google.cloud.retail.v2alpha.PurchaseTransaction.tax] - - - [cost][google.cloud.retail.v2alpha.PurchaseTransaction.cost] - currency_code (str): - Required. Currency code. Use three-character - ISO-4217 code. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - revenue = proto.Field( - proto.FLOAT, - number=2, - ) - tax = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - currency_code = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py b/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py deleted file mode 100644 index 0e679b22..00000000 --- a/owl-bot-staging/v2alpha/google/cloud/retail_v2alpha/types/user_event_service.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2alpha.types import user_event as gcr_user_event - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2alpha', - manifest={ - 'WriteUserEventRequest', - 'CollectUserEventRequest', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'RejoinUserEventsMetadata', - }, -) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (google.cloud.retail_v2alpha.types.UserEvent): - Required. User event to write. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (str): - Required. URL encoded UserEvent proto with a - length limit of 2,000,000 characters. - uri (str): - The URL including cgi-parameters but - excluding the hash fragment with a length limit - of 5,000 characters. This is often more useful - than the referer URL, because many browsers only - send the domain for 3rd party requests. - ets (int): - The event timestamp in milliseconds. This - prevents browser caching of otherwise identical - get requests. The name is abbreviated to reduce - the payload bytes. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.STRING, - number=2, - ) - uri = proto.Field( - proto.STRING, - number=3, - ) - ets = proto.Field( - proto.INT64, - number=4, - ) - - -class RejoinUserEventsRequest(proto.Message): - r"""Request message for RejoinUserEvents method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event_rejoin_scope (google.cloud.retail_v2alpha.types.RejoinUserEventsRequest.UserEventRejoinScope): - The type of the user event rejoin to define the scope and - range of the user events to be rejoined with the latest - product catalog. Defaults to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not - set, or set to an invalid integer value. - """ - class UserEventRejoinScope(proto.Enum): - r"""The scope of user events to be rejoined with the latest product - catalog. If the rejoining aims at reducing number of unjoined - events, set UserEventRejoinScope to UNJOINED_EVENTS. If the - rejoining aims at correcting product catalog information in joined - events, set UserEventRejoinScope to JOINED_EVENTS. If all events - needs to be rejoined, set UserEventRejoinScope to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. - """ - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 - JOINED_EVENTS = 1 - UNJOINED_EVENTS = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event_rejoin_scope = proto.Field( - proto.ENUM, - number=2, - enum=UserEventRejoinScope, - ) - - -class RejoinUserEventsResponse(proto.Message): - r"""Response message for RejoinUserEvents method. - - Attributes: - rejoined_user_events_count (int): - Number of user events that were joined with - latest product catalog. - """ - - rejoined_user_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -class RejoinUserEventsMetadata(proto.Message): - r"""Metadata for RejoinUserEvents method. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2alpha/mypy.ini b/owl-bot-staging/v2alpha/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v2alpha/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2alpha/noxfile.py b/owl-bot-staging/v2alpha/noxfile.py deleted file mode 100644 index 9f7eeaa1..00000000 --- a/owl-bot-staging/v2alpha/noxfile.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.6", - "3.7", - "3.8", - "3.9", - "3.10", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==19.10b0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.9" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/retail_v2alpha/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py deleted file mode 100644 index 9b5622c2..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async] -from google.cloud import retail_v2alpha - - -async def sample_add_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py deleted file mode 100644 index ec76bc9f..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync] -from google.cloud import retail_v2alpha - - -def sample_add_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py deleted file mode 100644 index d2f66638..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetAttributesConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_get_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetAttributesConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py deleted file mode 100644 index 91c914b3..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_get_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py deleted file mode 100644 index 9da8e840..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetCompletionConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_get_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetCompletionConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py deleted file mode 100644 index 5da5cd9f..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_completion_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_get_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py deleted file mode 100644 index 2134a810..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_async.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetDefaultBranch_async] -from google.cloud import retail_v2alpha - - -async def sample_get_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py deleted file mode 100644 index d233b424..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_get_default_branch_sync.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync] -from google.cloud import retail_v2alpha - - -def sample_get_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py deleted file mode 100644 index 7e7fbf33..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_ListCatalogs_async] -from google.cloud import retail_v2alpha - - -async def sample_list_catalogs(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py deleted file mode 100644 index 8165c25b..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_list_catalogs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_ListCatalogs_sync] -from google.cloud import retail_v2alpha - - -def sample_list_catalogs(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py deleted file mode 100644 index f79bd768..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async] -from google.cloud import retail_v2alpha - - -async def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = await client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py deleted file mode 100644 index 35b6611c..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync] -from google.cloud import retail_v2alpha - - -def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py deleted file mode 100644 index c42a8bb1..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReplaceCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async] -from google.cloud import retail_v2alpha - - -async def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py deleted file mode 100644 index 56e779ab..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReplaceCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync] -from google.cloud import retail_v2alpha - - -def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2alpha.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2alpha.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py deleted file mode 100644 index 9ddf2f8e..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_async.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_SetDefaultBranch_async] -from google.cloud import retail_v2alpha - - -async def sample_set_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - -# [END retail_v2alpha_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py deleted file mode 100644 index 6fa13ce6..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_set_default_branch_sync.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync] -from google.cloud import retail_v2alpha - - -def sample_set_default_branch(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - -# [END retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py deleted file mode 100644 index c4654be4..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_update_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - attributes_config = retail_v2alpha.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2alpha.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = await client.update_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py deleted file mode 100644 index 1f4d3432..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_update_attributes_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - attributes_config = retail_v2alpha.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2alpha.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = client.update_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py deleted file mode 100644 index 6035f718..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateCatalog_async] -from google.cloud import retail_v2alpha - - -async def sample_update_catalog(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2alpha.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2alpha.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py deleted file mode 100644 index 35fff0d1..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_catalog_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateCatalog_sync] -from google.cloud import retail_v2alpha - - -def sample_update_catalog(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2alpha.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2alpha.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py deleted file mode 100644 index 26cac134..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_update_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceAsyncClient() - - # Initialize request argument(s) - completion_config = retail_v2alpha.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2alpha.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = await client.update_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py deleted file mode 100644 index b9e11448..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_catalog_service_update_completion_config_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_update_completion_config(): - # Create a client - client = retail_v2alpha.CatalogServiceClient() - - # Initialize request argument(s) - completion_config = retail_v2alpha.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2alpha.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = client.update_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py deleted file mode 100644 index 13dce99f..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CompletionService_CompleteQuery_async] -from google.cloud import retail_v2alpha - - -async def sample_complete_query(): - # Create a client - client = retail_v2alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py deleted file mode 100644 index 20687e33..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_complete_query_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CompletionService_CompleteQuery_sync] -from google.cloud import retail_v2alpha - - -def sample_complete_query(): - # Create a client - client = retail_v2alpha.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py deleted file mode 100644 index d1a515f2..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CompletionService_ImportCompletionData_async] -from google.cloud import retail_v2alpha - - -async def sample_import_completion_data(): - # Create a client - client = retail_v2alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2alpha.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py deleted file mode 100644 index 3c6ddc55..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_completion_service_import_completion_data_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_CompletionService_ImportCompletionData_sync] -from google.cloud import retail_v2alpha - - -def sample_import_completion_data(): - # Create a client - client = retail_v2alpha.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2alpha.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py deleted file mode 100644 index 131de87e..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_CreateControl_async] -from google.cloud import retail_v2alpha - - -async def sample_create_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = await client.create_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_CreateControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py deleted file mode 100644 index 8fee66d8..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_create_control_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_CreateControl_sync] -from google.cloud import retail_v2alpha - - -def sample_create_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = client.create_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_CreateControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py deleted file mode 100644 index ae438a78..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_DeleteControl_async] -from google.cloud import retail_v2alpha - - -async def sample_delete_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteControlRequest( - name="name_value", - ) - - # Make the request - await client.delete_control(request=request) - - -# [END retail_v2alpha_generated_ControlService_DeleteControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py deleted file mode 100644 index b83ddcd5..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_delete_control_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_DeleteControl_sync] -from google.cloud import retail_v2alpha - - -def sample_delete_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteControlRequest( - name="name_value", - ) - - # Make the request - client.delete_control(request=request) - - -# [END retail_v2alpha_generated_ControlService_DeleteControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py deleted file mode 100644 index 588c8955..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_GetControl_async] -from google.cloud import retail_v2alpha - - -async def sample_get_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetControlRequest( - name="name_value", - ) - - # Make the request - response = await client.get_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_GetControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py deleted file mode 100644 index f04eb36b..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_get_control_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_GetControl_sync] -from google.cloud import retail_v2alpha - - -def sample_get_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetControlRequest( - name="name_value", - ) - - # Make the request - response = client.get_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_GetControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py deleted file mode 100644 index 005329c1..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListControls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_ListControls_async] -from google.cloud import retail_v2alpha - - -async def sample_list_controls(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ControlService_ListControls_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py deleted file mode 100644 index 301c6036..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_list_controls_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListControls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_ListControls_sync] -from google.cloud import retail_v2alpha - - -def sample_list_controls(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ControlService_ListControls_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py deleted file mode 100644 index dc422066..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_UpdateControl_async] -from google.cloud import retail_v2alpha - - -async def sample_update_control(): - # Create a client - client = retail_v2alpha.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.UpdateControlRequest( - control=control, - ) - - # Make the request - response = await client.update_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_UpdateControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py deleted file mode 100644 index cf7823fd..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_control_service_update_control_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ControlService_UpdateControl_sync] -from google.cloud import retail_v2alpha - - -def sample_update_control(): - # Create a client - client = retail_v2alpha.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2alpha.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - control.search_solution_use_case = "SEARCH_SOLUTION_USE_CASE_BROWSE" - - request = retail_v2alpha.UpdateControlRequest( - control=control, - ) - - # Make the request - response = client.update_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ControlService_UpdateControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py deleted file mode 100644 index 7d3c4540..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_PredictionService_Predict_async] -from google.cloud import retail_v2alpha - - -async def sample_predict(): - # Create a client - client = retail_v2alpha.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py deleted file mode 100644 index c3dbd187..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_prediction_service_predict_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_PredictionService_Predict_sync] -from google.cloud import retail_v2alpha - - -def sample_predict(): - # Create a client - client = retail_v2alpha.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py deleted file mode 100644 index 4ef15987..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async] -from google.cloud import retail_v2alpha - - -async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py deleted file mode 100644 index 03f0cd6d..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync] -from google.cloud import retail_v2alpha - - -def sample_add_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py deleted file mode 100644 index c3b7dfdf..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_AddLocalInventories_async] -from google.cloud import retail_v2alpha - - -async def sample_add_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py deleted file mode 100644 index b91b57f3..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_add_local_inventories_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_AddLocalInventories_sync] -from google.cloud import retail_v2alpha - - -def sample_add_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py deleted file mode 100644 index 8ca45663..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_CreateProduct_async] -from google.cloud import retail_v2alpha - - -async def sample_create_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py deleted file mode 100644 index b2946508..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_create_product_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_CreateProduct_sync] -from google.cloud import retail_v2alpha - - -def sample_create_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py deleted file mode 100644 index 1ae74222..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_DeleteProduct_async] -from google.cloud import retail_v2alpha - - -async def sample_delete_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - -# [END retail_v2alpha_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py deleted file mode 100644 index faebc2e4..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_delete_product_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_DeleteProduct_sync] -from google.cloud import retail_v2alpha - - -def sample_delete_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - -# [END retail_v2alpha_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py deleted file mode 100644 index 70903b9e..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_GetProduct_async] -from google.cloud import retail_v2alpha - - -async def sample_get_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py deleted file mode 100644 index 25fccda2..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_get_product_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_GetProduct_sync] -from google.cloud import retail_v2alpha - - -def sample_get_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py deleted file mode 100644 index 5cfaf031..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_ImportProducts_async] -from google.cloud import retail_v2alpha - - -async def sample_import_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2alpha.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py deleted file mode 100644 index ca54ea57..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_import_products_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_ImportProducts_sync] -from google.cloud import retail_v2alpha - - -def sample_import_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2alpha.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py deleted file mode 100644 index 8dcf7a71..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_ListProducts_async] -from google.cloud import retail_v2alpha - - -async def sample_list_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py deleted file mode 100644 index aa96e9c2..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_list_products_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_ListProducts_sync] -from google.cloud import retail_v2alpha - - -def sample_list_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py deleted file mode 100644 index 8adf6af4..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_PurgeProducts_async] -from google.cloud import retail_v2alpha - - -async def sample_purge_products(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeProductsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_PurgeProducts_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py deleted file mode 100644 index 72c32c88..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_purge_products_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_PurgeProducts_sync] -from google.cloud import retail_v2alpha - - -def sample_purge_products(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeProductsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_PurgeProducts_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py deleted file mode 100644 index da379da0..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async] -from google.cloud import retail_v2alpha - - -async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py deleted file mode 100644 index 55bf6522..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync] -from google.cloud import retail_v2alpha - - -def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py deleted file mode 100644 index bc0b9406..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_RemoveLocalInventories_async] -from google.cloud import retail_v2alpha - - -async def sample_remove_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py deleted file mode 100644 index 40e0b2bb..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_remove_local_inventories_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync] -from google.cloud import retail_v2alpha - - -def sample_remove_local_inventories(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py deleted file mode 100644 index 64dc769c..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_SetInventory_async] -from google.cloud import retail_v2alpha - - -async def sample_set_inventory(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2alpha.Product() - inventory.title = "title_value" - - request = retail_v2alpha.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py deleted file mode 100644 index 9dbf88b6..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_set_inventory_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_SetInventory_sync] -from google.cloud import retail_v2alpha - - -def sample_set_inventory(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2alpha.Product() - inventory.title = "title_value" - - request = retail_v2alpha.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py deleted file mode 100644 index 35df5c2b..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_UpdateProduct_async] -from google.cloud import retail_v2alpha - - -async def sample_update_product(): - # Create a client - client = retail_v2alpha.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py deleted file mode 100644 index 6248e977..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_product_service_update_product_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ProductService_UpdateProduct_sync] -from google.cloud import retail_v2alpha - - -def sample_update_product(): - # Create a client - client = retail_v2alpha.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2alpha.Product() - product.title = "title_value" - - request = retail_v2alpha.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py deleted file mode 100644 index 75520b76..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_async.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_SearchService_Search_async] -from google.cloud import retail_v2alpha - - -async def sample_search(): - # Create a client - client = retail_v2alpha.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py deleted file mode 100644 index 2b2853a3..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_search_service_search_sync.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_SearchService_Search_sync] -from google.cloud import retail_v2alpha - - -def sample_search(): - # Create a client - client = retail_v2alpha.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py deleted file mode 100644 index 0694590c..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_AddControl_async] -from google.cloud import retail_v2alpha - - -async def sample_add_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.add_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_AddControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py deleted file mode 100644 index 10d50ff7..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_add_control_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_AddControl_sync] -from google.cloud import retail_v2alpha - - -def sample_add_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.add_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_AddControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py deleted file mode 100644 index 33b080fc..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_create_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = await client.create_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py deleted file mode 100644 index e7b0e80e..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_create_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = client.create_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py deleted file mode 100644 index f8259bdf..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_delete_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_serving_config(request=request) - - -# [END retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py deleted file mode 100644 index 621916ef..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_delete_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_serving_config(request=request) - - -# [END retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py deleted file mode 100644 index fdfd4d80..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_GetServingConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_get_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_GetServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py deleted file mode 100644 index a1408016..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_get_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py deleted file mode 100644 index c8244f95..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServingConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async] -from google.cloud import retail_v2alpha - - -async def sample_list_serving_configs(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py deleted file mode 100644 index 86e02687..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServingConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync] -from google.cloud import retail_v2alpha - - -def sample_list_serving_configs(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py deleted file mode 100644 index 66e07902..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_RemoveControl_async] -from google.cloud import retail_v2alpha - - -async def sample_remove_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.remove_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_RemoveControl_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py deleted file mode 100644 index 8b39362b..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_remove_control_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_RemoveControl_sync] -from google.cloud import retail_v2alpha - - -def sample_remove_control(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.remove_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_RemoveControl_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py deleted file mode 100644 index 64e82dba..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async] -from google.cloud import retail_v2alpha - - -async def sample_update_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = await client.update_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py deleted file mode 100644 index 46d2d65c..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync] -from google.cloud import retail_v2alpha - - -def sample_update_serving_config(): - # Create a client - client = retail_v2alpha.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2alpha.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2alpha.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = client.update_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py deleted file mode 100644 index f8aa3f78..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_CollectUserEvent_async] -from google.cloud import retail_v2alpha - - -async def sample_collect_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py deleted file mode 100644 index 026972b1..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_collect_user_event_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_CollectUserEvent_sync] -from google.cloud import retail_v2alpha - - -def sample_collect_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py deleted file mode 100644 index 540ce130..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_ImportUserEvents_async] -from google.cloud import retail_v2alpha - - -async def sample_import_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2alpha.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py deleted file mode 100644 index fe9310db..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_import_user_events_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_ImportUserEvents_sync] -from google.cloud import retail_v2alpha - - -def sample_import_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2alpha.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2alpha.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py deleted file mode 100644 index 17d5c66d..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_PurgeUserEvents_async] -from google.cloud import retail_v2alpha - - -async def sample_purge_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py deleted file mode 100644 index d8b2ae83..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_purge_user_events_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync] -from google.cloud import retail_v2alpha - - -def sample_purge_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py deleted file mode 100644 index d38bb5f4..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_RejoinUserEvents_async] -from google.cloud import retail_v2alpha - - -async def sample_rejoin_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2alpha.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py deleted file mode 100644 index f88f6437..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync] -from google.cloud import retail_v2alpha - - -def sample_rejoin_user_events(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2alpha.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py deleted file mode 100644 index 2dda0e65..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_WriteUserEvent_async] -from google.cloud import retail_v2alpha - - -async def sample_write_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py deleted file mode 100644 index a121bdbd..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/retail_v2alpha_generated_user_event_service_write_user_event_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2alpha_generated_UserEventService_WriteUserEvent_sync] -from google.cloud import retail_v2alpha - - -def sample_write_user_event(): - # Create a client - client = retail_v2alpha.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2alpha.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2alpha_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json b/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json deleted file mode 100644 index ea2cf419..00000000 --- a/owl-bot-staging/v2alpha/samples/generated_samples/snippet_metadata_retail_v2alpha.json +++ /dev/null @@ -1,7066 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.retail.v2alpha", - "version": "v2alpha" - } - ], - "language": "PYTHON", - "name": "google-cloud-retail" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.add_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "AddCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "add_catalog_attribute" - }, - "description": "Sample for AddCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.add_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.AddCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "AddCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "add_catalog_attribute" - }, - "description": "Sample for AddCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_AddCatalogAttribute_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_add_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetAttributesConfigRequest" - }, - { - "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.retail_v2alpha.types.AttributesConfig", - "shortName": "get_attributes_config" - }, - "description": "Sample for GetAttributesConfig", - "file": "retail_v2alpha_generated_catalog_service_get_attributes_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetAttributesConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_attributes_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetAttributesConfigRequest" - }, - { - "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.retail_v2alpha.types.AttributesConfig", - "shortName": "get_attributes_config" - }, - "description": "Sample for GetAttributesConfig", - "file": "retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetAttributesConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_attributes_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_completion_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetCompletionConfigRequest" - }, - { - "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.retail_v2alpha.types.CompletionConfig", - "shortName": "get_completion_config" - }, - "description": "Sample for GetCompletionConfig", - "file": "retail_v2alpha_generated_catalog_service_get_completion_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetCompletionConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_completion_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_completion_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetCompletionConfigRequest" - }, - { - "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.retail_v2alpha.types.CompletionConfig", - "shortName": "get_completion_config" - }, - "description": "Sample for GetCompletionConfig", - "file": "retail_v2alpha_generated_catalog_service_get_completion_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetCompletionConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_completion_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2alpha_generated_catalog_service_get_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetDefaultBranch_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2alpha_generated_catalog_service_get_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_GetDefaultBranch_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_get_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListCatalogsRequest" - }, - { - "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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsAsyncPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2alpha_generated_catalog_service_list_catalogs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_ListCatalogs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_list_catalogs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListCatalogsRequest" - }, - { - "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.retail_v2alpha.services.catalog_service.pagers.ListCatalogsPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2alpha_generated_catalog_service_list_catalogs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_ListCatalogs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_list_catalogs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.remove_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "RemoveCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "remove_catalog_attribute" - }, - "description": "Sample for RemoveCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.remove_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.RemoveCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "RemoveCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "remove_catalog_attribute" - }, - "description": "Sample for RemoveCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_remove_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.replace_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ReplaceCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "replace_catalog_attribute" - }, - "description": "Sample for ReplaceCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.replace_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.ReplaceCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ReplaceCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ReplaceCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.AttributesConfig", - "shortName": "replace_catalog_attribute" - }, - "description": "Sample for ReplaceCatalogAttribute", - "file": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_replace_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2alpha_generated_catalog_service_set_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_SetDefaultBranch_async", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_set_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2alpha_generated_catalog_service_set_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_SetDefaultBranch_sync", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_set_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest" - }, - { - "name": "attributes_config", - "type": "google.cloud.retail_v2alpha.types.AttributesConfig" - }, - { - "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.retail_v2alpha.types.AttributesConfig", - "shortName": "update_attributes_config" - }, - "description": "Sample for UpdateAttributesConfig", - "file": "retail_v2alpha_generated_catalog_service_update_attributes_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_attributes_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateAttributesConfigRequest" - }, - { - "name": "attributes_config", - "type": "google.cloud.retail_v2alpha.types.AttributesConfig" - }, - { - "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.retail_v2alpha.types.AttributesConfig", - "shortName": "update_attributes_config" - }, - "description": "Sample for UpdateAttributesConfig", - "file": "retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_attributes_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2alpha.types.Catalog" - }, - { - "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.retail_v2alpha.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2alpha_generated_catalog_service_update_catalog_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCatalog_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_catalog_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2alpha.types.Catalog" - }, - { - "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.retail_v2alpha.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2alpha_generated_catalog_service_update_catalog_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCatalog_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_catalog_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceAsyncClient.update_completion_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest" - }, - { - "name": "completion_config", - "type": "google.cloud.retail_v2alpha.types.CompletionConfig" - }, - { - "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.retail_v2alpha.types.CompletionConfig", - "shortName": "update_completion_config" - }, - "description": "Sample for UpdateCompletionConfig", - "file": "retail_v2alpha_generated_catalog_service_update_completion_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_completion_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CatalogServiceClient.update_completion_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.CatalogService.UpdateCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateCompletionConfigRequest" - }, - { - "name": "completion_config", - "type": "google.cloud.retail_v2alpha.types.CompletionConfig" - }, - { - "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.retail_v2alpha.types.CompletionConfig", - "shortName": "update_completion_config" - }, - "description": "Sample for UpdateCompletionConfig", - "file": "retail_v2alpha_generated_catalog_service_update_completion_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_catalog_service_update_completion_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2alpha.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2alpha_generated_completion_service_complete_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CompletionService_CompleteQuery_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_completion_service_complete_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2alpha.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2alpha_generated_completion_service_complete_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CompletionService_CompleteQuery_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_completion_service_complete_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.CompletionServiceAsyncClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2alpha.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2alpha_generated_completion_service_import_completion_data_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CompletionService_ImportCompletionData_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_completion_service_import_completion_data_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.CompletionServiceClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2alpha.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2alpha_generated_completion_service_import_completion_data_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_CompletionService_ImportCompletionData_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_completion_service_import_completion_data_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.create_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.CreateControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "CreateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateControlRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "control", - "type": "google.cloud.retail_v2alpha.types.Control" - }, - { - "name": "control_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.retail_v2alpha.types.Control", - "shortName": "create_control" - }, - "description": "Sample for CreateControl", - "file": "retail_v2alpha_generated_control_service_create_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_CreateControl_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_create_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.create_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.CreateControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "CreateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateControlRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "control", - "type": "google.cloud.retail_v2alpha.types.Control" - }, - { - "name": "control_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.retail_v2alpha.types.Control", - "shortName": "create_control" - }, - "description": "Sample for CreateControl", - "file": "retail_v2alpha_generated_control_service_create_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_CreateControl_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_create_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.delete_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.DeleteControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "DeleteControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteControlRequest" - }, - { - "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_control" - }, - "description": "Sample for DeleteControl", - "file": "retail_v2alpha_generated_control_service_delete_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_DeleteControl_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_delete_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.delete_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.DeleteControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "DeleteControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteControlRequest" - }, - { - "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_control" - }, - "description": "Sample for DeleteControl", - "file": "retail_v2alpha_generated_control_service_delete_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_DeleteControl_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_delete_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.get_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.GetControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "GetControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetControlRequest" - }, - { - "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.retail_v2alpha.types.Control", - "shortName": "get_control" - }, - "description": "Sample for GetControl", - "file": "retail_v2alpha_generated_control_service_get_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_GetControl_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_get_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.get_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.GetControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "GetControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetControlRequest" - }, - { - "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.retail_v2alpha.types.Control", - "shortName": "get_control" - }, - "description": "Sample for GetControl", - "file": "retail_v2alpha_generated_control_service_get_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_GetControl_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_get_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.list_controls", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.ListControls", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "ListControls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListControlsRequest" - }, - { - "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.retail_v2alpha.services.control_service.pagers.ListControlsAsyncPager", - "shortName": "list_controls" - }, - "description": "Sample for ListControls", - "file": "retail_v2alpha_generated_control_service_list_controls_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_ListControls_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_list_controls_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.list_controls", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.ListControls", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "ListControls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListControlsRequest" - }, - { - "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.retail_v2alpha.services.control_service.pagers.ListControlsPager", - "shortName": "list_controls" - }, - "description": "Sample for ListControls", - "file": "retail_v2alpha_generated_control_service_list_controls_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_ListControls_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_list_controls_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceAsyncClient.update_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.UpdateControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "UpdateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateControlRequest" - }, - { - "name": "control", - "type": "google.cloud.retail_v2alpha.types.Control" - }, - { - "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.retail_v2alpha.types.Control", - "shortName": "update_control" - }, - "description": "Sample for UpdateControl", - "file": "retail_v2alpha_generated_control_service_update_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_UpdateControl_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_update_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ControlServiceClient.update_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ControlService.UpdateControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ControlService", - "shortName": "ControlService" - }, - "shortName": "UpdateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateControlRequest" - }, - { - "name": "control", - "type": "google.cloud.retail_v2alpha.types.Control" - }, - { - "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.retail_v2alpha.types.Control", - "shortName": "update_control" - }, - "description": "Sample for UpdateControl", - "file": "retail_v2alpha_generated_control_service_update_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ControlService_UpdateControl_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_control_service_update_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.PredictionServiceAsyncClient", - "shortName": "PredictionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.PredictionServiceAsyncClient.predict", - "method": { - "fullName": "google.cloud.retail.v2alpha.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2alpha.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2alpha_generated_prediction_service_predict_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_PredictionService_Predict_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_prediction_service_predict_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.PredictionServiceClient", - "shortName": "PredictionServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.PredictionServiceClient.predict", - "method": { - "fullName": "google.cloud.retail.v2alpha.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2alpha.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2alpha_generated_prediction_service_predict_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_PredictionService_Predict_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_prediction_service_predict_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2alpha_generated_product_service_add_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_add_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_add_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2alpha_generated_product_service_add_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_AddLocalInventories_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_add_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2alpha_generated_product_service_add_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_AddLocalInventories_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_add_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "name": "product_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.retail_v2alpha.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2alpha_generated_product_service_create_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_CreateProduct_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_create_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "name": "product_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.retail_v2alpha.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2alpha_generated_product_service_create_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_CreateProduct_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_create_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2alpha_generated_product_service_delete_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_DeleteProduct_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_delete_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2alpha_generated_product_service_delete_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_DeleteProduct_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_delete_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetProductRequest" - }, - { - "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.retail_v2alpha.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2alpha_generated_product_service_get_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_GetProduct_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_get_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetProductRequest" - }, - { - "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.retail_v2alpha.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2alpha_generated_product_service_get_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_GetProduct_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_get_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2alpha_generated_product_service_import_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_ImportProducts_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_import_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2alpha_generated_product_service_import_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_ImportProducts_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_import_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListProductsRequest" - }, - { - "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.retail_v2alpha.services.product_service.pagers.ListProductsAsyncPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2alpha_generated_product_service_list_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_ListProducts_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_list_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListProductsRequest" - }, - { - "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.retail_v2alpha.services.product_service.pagers.ListProductsPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2alpha_generated_product_service_list_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_ListProducts_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_list_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.purge_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.PurgeProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "PurgeProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PurgeProductsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_products" - }, - "description": "Sample for PurgeProducts", - "file": "retail_v2alpha_generated_product_service_purge_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_PurgeProducts_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_purge_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.purge_products", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.PurgeProducts", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "PurgeProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PurgeProductsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_products" - }, - "description": "Sample for PurgeProducts", - "file": "retail_v2alpha_generated_product_service_purge_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_PurgeProducts_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_purge_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_remove_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_remove_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2alpha_generated_product_service_remove_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_RemoveLocalInventories_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_remove_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2alpha_generated_product_service_remove_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_RemoveLocalInventories_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_remove_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2alpha_generated_product_service_set_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_SetInventory_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_set_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2alpha_generated_product_service_set_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_SetInventory_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_set_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceAsyncClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "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.retail_v2alpha.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2alpha_generated_product_service_update_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_UpdateProduct_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_update_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ProductServiceClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2alpha.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2alpha.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2alpha.types.Product" - }, - { - "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.retail_v2alpha.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2alpha_generated_product_service_update_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ProductService_UpdateProduct_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_product_service_update_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.SearchServiceAsyncClient.search", - "method": { - "fullName": "google.cloud.retail.v2alpha.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2alpha.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2alpha_generated_search_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_SearchService_Search_async", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_search_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.SearchServiceClient", - "shortName": "SearchServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.SearchServiceClient.search", - "method": { - "fullName": "google.cloud.retail.v2alpha.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2alpha.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.services.search_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2alpha_generated_search_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_SearchService_Search_sync", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_search_service_search_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.add_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.AddControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "AddControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "add_control" - }, - "description": "Sample for AddControl", - "file": "retail_v2alpha_generated_serving_config_service_add_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_AddControl_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_add_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.add_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.AddControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "AddControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.AddControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "add_control" - }, - "description": "Sample for AddControl", - "file": "retail_v2alpha_generated_serving_config_service_add_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_AddControl_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_add_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.create_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.CreateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "CreateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateServingConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2alpha.types.ServingConfig" - }, - { - "name": "serving_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "create_serving_config" - }, - "description": "Sample for CreateServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_create_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_create_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.create_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.CreateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "CreateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CreateServingConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2alpha.types.ServingConfig" - }, - { - "name": "serving_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "create_serving_config" - }, - "description": "Sample for CreateServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_CreateServingConfig_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_create_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.delete_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.DeleteServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "DeleteServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteServingConfigRequest" - }, - { - "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_serving_config" - }, - "description": "Sample for DeleteServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_delete_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.delete_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.DeleteServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "DeleteServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.DeleteServingConfigRequest" - }, - { - "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_serving_config" - }, - "description": "Sample for DeleteServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_delete_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.get_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.GetServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "GetServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetServingConfigRequest" - }, - { - "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.retail_v2alpha.types.ServingConfig", - "shortName": "get_serving_config" - }, - "description": "Sample for GetServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_get_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_GetServingConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_get_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.get_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.GetServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "GetServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.GetServingConfigRequest" - }, - { - "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.retail_v2alpha.types.ServingConfig", - "shortName": "get_serving_config" - }, - "description": "Sample for GetServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_GetServingConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_get_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.list_serving_configs", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.ListServingConfigs", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "ListServingConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListServingConfigsRequest" - }, - { - "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.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsAsyncPager", - "shortName": "list_serving_configs" - }, - "description": "Sample for ListServingConfigs", - "file": "retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_list_serving_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.list_serving_configs", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.ListServingConfigs", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "ListServingConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ListServingConfigsRequest" - }, - { - "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.retail_v2alpha.services.serving_config_service.pagers.ListServingConfigsPager", - "shortName": "list_serving_configs" - }, - "description": "Sample for ListServingConfigs", - "file": "retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_ListServingConfigs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_list_serving_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.remove_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.RemoveControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "RemoveControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "remove_control" - }, - "description": "Sample for RemoveControl", - "file": "retail_v2alpha_generated_serving_config_service_remove_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_RemoveControl_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_remove_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.remove_control", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.RemoveControl", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "RemoveControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RemoveControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.ServingConfig", - "shortName": "remove_control" - }, - "description": "Sample for RemoveControl", - "file": "retail_v2alpha_generated_serving_config_service_remove_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_RemoveControl_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_remove_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceAsyncClient.update_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.UpdateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "UpdateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2alpha.types.ServingConfig" - }, - { - "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.retail_v2alpha.types.ServingConfig", - "shortName": "update_serving_config" - }, - "description": "Sample for UpdateServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_update_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_update_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.ServingConfigServiceClient.update_serving_config", - "method": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService.UpdateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2alpha.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "UpdateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2alpha.types.ServingConfig" - }, - { - "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.retail_v2alpha.types.ServingConfig", - "shortName": "update_serving_config" - }, - "description": "Sample for UpdateServingConfig", - "file": "retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_serving_config_service_update_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2alpha_generated_user_event_service_collect_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_CollectUserEvent_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_collect_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2alpha_generated_user_event_service_collect_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_CollectUserEvent_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_collect_user_event_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2alpha_generated_user_event_service_import_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_ImportUserEvents_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_import_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2alpha_generated_user_event_service_import_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_ImportUserEvents_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_import_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2alpha_generated_user_event_service_purge_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_PurgeUserEvents_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_purge_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2alpha_generated_user_event_service_purge_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_PurgeUserEvents_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_purge_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_RejoinUserEvents_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_rejoin_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_RejoinUserEvents_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_rejoin_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceAsyncClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2alpha_generated_user_event_service_write_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_WriteUserEvent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_write_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2alpha.UserEventServiceClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2alpha.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2alpha.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2alpha.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2alpha_generated_user_event_service_write_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2alpha_generated_UserEventService_WriteUserEvent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2alpha_generated_user_event_service_write_user_event_sync.py" - } - ] -} diff --git a/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py b/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py deleted file mode 100644 index 5fbe2d4d..00000000 --- a/owl-bot-staging/v2alpha/scripts/fixup_retail_v2alpha_keywords.py +++ /dev/null @@ -1,219 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class retailCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_catalog_attribute': ('attributes_config', 'catalog_attribute', ), - 'add_control': ('serving_config', 'control_id', ), - 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), - 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), - 'create_control': ('parent', 'control', 'control_id', ), - 'create_product': ('parent', 'product', 'product_id', ), - 'create_serving_config': ('parent', 'serving_config', 'serving_config_id', ), - 'delete_control': ('name', ), - 'delete_product': ('name', ), - 'delete_serving_config': ('name', ), - 'get_attributes_config': ('name', ), - 'get_completion_config': ('name', ), - 'get_control': ('name', ), - 'get_default_branch': ('catalog', ), - 'get_product': ('name', ), - 'get_serving_config': ('name', ), - 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), - 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), - 'import_user_events': ('parent', 'input_config', 'errors_config', ), - 'list_catalogs': ('parent', 'page_size', 'page_token', ), - 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', 'require_total_size', ), - 'list_serving_configs': ('parent', 'page_size', 'page_token', ), - 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), - 'purge_products': ('parent', 'filter', 'force', ), - 'purge_user_events': ('parent', 'filter', 'force', ), - 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), - 'remove_catalog_attribute': ('attributes_config', 'key', ), - 'remove_control': ('serving_config', 'control_id', ), - 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), - 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), - 'replace_catalog_attribute': ('attributes_config', 'catalog_attribute', 'update_mask', ), - 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'relevance_threshold', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), - 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), - 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), - 'update_attributes_config': ('attributes_config', 'update_mask', ), - 'update_catalog': ('catalog', 'update_mask', ), - 'update_completion_config': ('completion_config', 'update_mask', ), - 'update_control': ('control', 'update_mask', ), - 'update_product': ('product', 'update_mask', 'allow_missing', ), - 'update_serving_config': ('serving_config', 'update_mask', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=retailCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the retail client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2alpha/setup.py b/owl-bot-staging/v2alpha/setup.py deleted file mode 100644 index 1103510b..00000000 --- a/owl-bot-staging/v2alpha/setup.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-retail', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-retail", - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 2.8.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'googleapis-common-protos >= 1.55.0, <2.0.0dev', - 'proto-plus >= 1.19.7', - ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v2alpha/tests/__init__.py b/owl-bot-staging/v2alpha/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2alpha/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/tests/unit/__init__.py b/owl-bot-staging/v2alpha/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py deleted file mode 100644 index 44a7cde0..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_catalog_service.py +++ /dev/null @@ -1,3843 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.catalog_service import CatalogServiceAsyncClient -from google.cloud.retail_v2alpha.services.catalog_service import CatalogServiceClient -from google.cloud.retail_v2alpha.services.catalog_service import pagers -from google.cloud.retail_v2alpha.services.catalog_service import transports -from google.cloud.retail_v2alpha.types import catalog -from google.cloud.retail_v2alpha.types import catalog as gcr_catalog -from google.cloud.retail_v2alpha.types import catalog_service -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CatalogServiceClient._get_default_mtls_endpoint(None) is None - assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CatalogServiceGrpcTransport, "grpc"), - (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_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", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_catalog_service_client_get_transport_class(): - transport = CatalogServiceClient.get_transport_class() - available_transports = [ - transports.CatalogServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CatalogServiceClient.get_transport_class("grpc") - assert transport == transports.CatalogServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CatalogServiceClient, CatalogServiceAsyncClient -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_catalog_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ListCatalogsRequest, - dict, -]) -def test_list_catalogs(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalogs), - '__call__') as call: - client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - -@pytest.mark.asyncio -async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_catalogs_async_from_dict(): - await test_list_catalogs_async(request_type=dict) - - -def test_list_catalogs_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = catalog_service.ListCatalogsResponse() - client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_catalogs( - 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_catalogs_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_catalogs_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_catalogs( - 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_catalogs_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - - -def test_list_catalogs_pager(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_catalogs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, catalog.Catalog) - for i in results) -def test_list_catalogs_pages(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = list(client.list_catalogs(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_catalogs_async_pager(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_catalogs(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, catalog.Catalog) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_catalogs_async_pages(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCatalogRequest, - dict, -]) -def test_update_catalog(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - ) - response = client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_catalog_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalog), - '__call__') as call: - client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - -@pytest.mark.asyncio -async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_catalog_async_from_dict(): - await test_update_catalog_async(request_type=dict) - - -def test_update_catalog_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = gcr_catalog.Catalog() - client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_catalog_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -def test_update_catalog_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_catalog_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.SetDefaultBranchRequest, - dict, -]) -def test_set_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_set_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_set_default_branch_async_from_dict(): - await test_set_default_branch_async(request_type=dict) - - -def test_set_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = None - client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_set_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_set_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetDefaultBranchRequest, - dict, -]) -def test_get_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - ) - response = client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -def test_get_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_default_branch), - '__call__') as call: - client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - )) - response = await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -@pytest.mark.asyncio -async def test_get_default_branch_async_from_dict(): - await test_get_default_branch_async(request_type=dict) - - -def test_get_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = catalog_service.GetDefaultBranchResponse() - client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_get_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_get_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetCompletionConfigRequest, - dict, -]) -def test_get_completion_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - ) - response = client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -def test_get_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_completion_config), - '__call__') as call: - client.get_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - -@pytest.mark.asyncio -async def test_get_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCompletionConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - )) - response = await client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -@pytest.mark.asyncio -async def test_get_completion_config_async_from_dict(): - await test_get_completion_config_async(request_type=dict) - - -def test_get_completion_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCompletionConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - call.return_value = catalog.CompletionConfig() - client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_completion_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCompletionConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - await client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_completion_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_completion_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_completion_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_completion_config( - catalog_service.GetCompletionConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_completion_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_completion_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_completion_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_completion_config( - catalog_service.GetCompletionConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCompletionConfigRequest, - dict, -]) -def test_update_completion_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - ) - response = client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -def test_update_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_completion_config), - '__call__') as call: - client.update_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - -@pytest.mark.asyncio -async def test_update_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCompletionConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - )) - response = await client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -@pytest.mark.asyncio -async def test_update_completion_config_async_from_dict(): - await test_update_completion_config_async(request_type=dict) - - -def test_update_completion_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCompletionConfigRequest() - - request.completion_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - call.return_value = catalog.CompletionConfig() - client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'completion_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_completion_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCompletionConfigRequest() - - request.completion_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - await client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'completion_config.name=name_value', - ) in kw['metadata'] - - -def test_update_completion_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_completion_config( - completion_config=catalog.CompletionConfig(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].completion_config - mock_val = catalog.CompletionConfig(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_completion_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_completion_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_completion_config( - completion_config=catalog.CompletionConfig(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].completion_config - mock_val = catalog.CompletionConfig(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_completion_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetAttributesConfigRequest, - dict, -]) -def test_get_attributes_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_get_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_attributes_config), - '__call__') as call: - client.get_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - -@pytest.mark.asyncio -async def test_get_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetAttributesConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_get_attributes_config_async_from_dict(): - await test_get_attributes_config_async(request_type=dict) - - -def test_get_attributes_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetAttributesConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_attributes_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetAttributesConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_attributes_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_attributes_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_attributes_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_attributes_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_attributes_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_attributes_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateAttributesConfigRequest, - dict, -]) -def test_update_attributes_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_update_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_attributes_config), - '__call__') as call: - client.update_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - -@pytest.mark.asyncio -async def test_update_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateAttributesConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_update_attributes_config_async_from_dict(): - await test_update_attributes_config_async(request_type=dict) - - -def test_update_attributes_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateAttributesConfigRequest() - - request.attributes_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_attributes_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateAttributesConfigRequest() - - request.attributes_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config.name=name_value', - ) in kw['metadata'] - - -def test_update_attributes_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_attributes_config( - attributes_config=catalog.AttributesConfig(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].attributes_config - mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_attributes_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_attributes_config( - attributes_config=catalog.AttributesConfig(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].attributes_config - mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.AddCatalogAttributeRequest, - dict, -]) -def test_add_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_add_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - client.add_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_add_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.AddCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_add_catalog_attribute_async_from_dict(): - await test_add_catalog_attribute_async(request_type=dict) - - -def test_add_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.AddCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.AddCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - catalog_service.RemoveCatalogAttributeRequest, - dict, -]) -def test_remove_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_remove_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - client.remove_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.RemoveCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_async_from_dict(): - await test_remove_catalog_attribute_async(request_type=dict) - - -def test_remove_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.RemoveCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.RemoveCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ReplaceCatalogAttributeRequest, - dict, -]) -def test_replace_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_replace_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - client.replace_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ReplaceCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_async_from_dict(): - await test_replace_catalog_attribute_async(request_type=dict) - - -def test_replace_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ReplaceCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ReplaceCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CatalogServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.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 = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CatalogServiceGrpcTransport, - ) - -def test_catalog_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_catalog_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_catalogs', - 'update_catalog', - 'set_default_branch', - 'get_default_branch', - 'get_completion_config', - 'update_completion_config', - 'get_attributes_config', - 'update_attributes_config', - 'add_catalog_attribute', - 'remove_catalog_attribute', - 'replace_catalog_attribute', - ) - 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_catalog_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.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport( - 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_catalog_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.retail_v2alpha.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport() - adc.assert_called_once() - - -def test_catalog_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) - CatalogServiceClient() - 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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -def test_catalog_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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -def test_catalog_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.CatalogServiceGrpcTransport, grpc_helpers), - (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_catalog_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_no_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_with_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_catalog_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcTransport( - 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_catalog_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcAsyncIOTransport( - 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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_attributes_config_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.attributes_config_path(project, location, catalog) - assert expected == actual - - -def test_parse_attributes_config_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CatalogServiceClient.attributes_config_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_attributes_config_path(path) - assert expected == actual - -def test_branch_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = CatalogServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "branch": "clam", - } - path = CatalogServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_branch_path(path) - assert expected == actual - -def test_catalog_path(): - project = "whelk" - location = "octopus" - catalog = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - } - path = CatalogServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_completion_config_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.completion_config_path(project, location, catalog) - assert expected == actual - - -def test_parse_completion_config_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - } - path = CatalogServiceClient.completion_config_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_completion_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CatalogServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = CatalogServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = CatalogServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = CatalogServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CatalogServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = CatalogServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = CatalogServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = CatalogServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = CatalogServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CatalogServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py deleted file mode 100644 index 9e035903..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_completion_service.py +++ /dev/null @@ -1,1501 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.completion_service import CompletionServiceAsyncClient -from google.cloud.retail_v2alpha.services.completion_service import CompletionServiceClient -from google.cloud.retail_v2alpha.services.completion_service import transports -from google.cloud.retail_v2alpha.types import completion_service -from google.cloud.retail_v2alpha.types import import_config -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CompletionServiceClient._get_default_mtls_endpoint(None) is None - assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CompletionServiceGrpcTransport, "grpc"), - (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_completion_service_client_get_transport_class(): - transport = CompletionServiceClient.get_transport_class() - available_transports = [ - transports.CompletionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CompletionServiceClient.get_transport_class("grpc") - assert transport == transports.CompletionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CompletionServiceClient, CompletionServiceAsyncClient -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_completion_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CompletionServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - ) - response = client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - -@pytest.mark.asyncio -async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - )) - response = await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -@pytest.mark.asyncio -async def test_complete_query_async_from_dict(): - await test_complete_query_async(request_type=dict) - - -def test_complete_query_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = completion_service.CompleteQueryResponse() - client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_complete_query_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) - await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportCompletionDataRequest, - dict, -]) -def test_import_completion_data(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_completion_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - -@pytest.mark.asyncio -async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_completion_data_async_from_dict(): - await test_import_completion_data_async(request_type=dict) - - -def test_import_completion_data_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # 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_completion_data_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CompletionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CompletionServiceGrpcTransport, - ) - -def test_completion_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_completion_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'complete_query', - 'import_completion_data', - ) - 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_completion_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_completion_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport() - adc.assert_called_once() - - -def test_completion_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CompletionServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionServiceGrpcTransport, grpc_helpers), - (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_completion_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_no_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_with_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_completion_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_completion_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_completion_service_grpc_lro_client(): - client = CompletionServiceClient( - 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_completion_service_grpc_lro_async_client(): - client = CompletionServiceAsyncClient( - 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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CompletionServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CompletionServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CompletionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CompletionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = CompletionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CompletionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CompletionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CompletionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = CompletionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CompletionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CompletionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CompletionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CompletionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py deleted file mode 100644 index 1f7f23e9..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_control_service.py +++ /dev/null @@ -1,2616 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.control_service import ControlServiceAsyncClient -from google.cloud.retail_v2alpha.services.control_service import ControlServiceClient -from google.cloud.retail_v2alpha.services.control_service import pagers -from google.cloud.retail_v2alpha.services.control_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import control -from google.cloud.retail_v2alpha.types import control as gcr_control -from google.cloud.retail_v2alpha.types import control_service -from google.cloud.retail_v2alpha.types import search_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ControlServiceClient._get_default_mtls_endpoint(None) is None - assert ControlServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ControlServiceClient, "grpc"), - (ControlServiceAsyncClient, "grpc_asyncio"), -]) -def test_control_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ControlServiceGrpcTransport, "grpc"), - (transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_control_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", [ - (ControlServiceClient, "grpc"), - (ControlServiceAsyncClient, "grpc_asyncio"), -]) -def test_control_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_control_service_client_get_transport_class(): - transport = ControlServiceClient.get_transport_class() - available_transports = [ - transports.ControlServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ControlServiceClient.get_transport_class("grpc") - assert transport == transports.ControlServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -def test_control_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(ControlServiceClient, '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(ControlServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "true"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "false"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_control_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ControlServiceClient, ControlServiceAsyncClient -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -def test_control_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_control_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_control_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_control_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.control_service.transports.ControlServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ControlServiceClient( - 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", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_control_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.CreateControlRequest, - dict, -]) -def test_create_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -def test_create_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.create_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - -@pytest.mark.asyncio -async def test_create_control_async(transport: str = 'grpc_asyncio', request_type=control_service.CreateControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - )) - response = await client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -@pytest.mark.asyncio -async def test_create_control_async_from_dict(): - await test_create_control_async(request_type=dict) - - -def test_create_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.CreateControlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - call.return_value = gcr_control.Control() - client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.CreateControlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - await client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_control( - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) - assert arg == mock_val - arg = args[0].control_id - mock_val = 'control_id_value' - assert arg == mock_val - - -def test_create_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.CreateControlRequest(), - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_id_value', - ) - -@pytest.mark.asyncio -async def test_create_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_control( - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) - assert arg == mock_val - arg = args[0].control_id - mock_val = 'control_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.CreateControlRequest(), - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.DeleteControlRequest, - dict, -]) -def test_delete_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.delete_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - -@pytest.mark.asyncio -async def test_delete_control_async(transport: str = 'grpc_asyncio', request_type=control_service.DeleteControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_control_async_from_dict(): - await test_delete_control_async(request_type=dict) - - -def test_delete_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.DeleteControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__call__') as call: - call.return_value = None - client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.DeleteControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__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_control( - 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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.DeleteControlRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__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_control( - 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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.DeleteControlRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.UpdateControlRequest, - dict, -]) -def test_update_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -def test_update_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.update_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - -@pytest.mark.asyncio -async def test_update_control_async(transport: str = 'grpc_asyncio', request_type=control_service.UpdateControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - )) - response = await client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -@pytest.mark.asyncio -async def test_update_control_async_from_dict(): - await test_update_control_async(request_type=dict) - - -def test_update_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.UpdateControlRequest() - - request.control.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - call.return_value = gcr_control.Control() - client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'control.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.UpdateControlRequest() - - request.control.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - await client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'control.name=name_value', - ) in kw['metadata'] - - -def test_update_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_control( - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_control( - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.GetControlRequest, - dict, -]) -def test_get_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -def test_get_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.get_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - -@pytest.mark.asyncio -async def test_get_control_async(transport: str = 'grpc_asyncio', request_type=control_service.GetControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH], - )) - response = await client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH] - - -@pytest.mark.asyncio -async def test_get_control_async_from_dict(): - await test_get_control_async(request_type=dict) - - -def test_get_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.GetControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - call.return_value = control.Control() - client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.GetControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) - await client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_control( - 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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.GetControlRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_control( - 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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.GetControlRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.ListControlsRequest, - dict, -]) -def test_list_controls(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_controls_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_controls), - '__call__') as call: - client.list_controls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - -@pytest.mark.asyncio -async def test_list_controls_async(transport: str = 'grpc_asyncio', request_type=control_service.ListControlsRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_controls_async_from_dict(): - await test_list_controls_async(request_type=dict) - - -def test_list_controls_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.ListControlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - call.return_value = control_service.ListControlsResponse() - client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_controls_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.ListControlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) - await client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_controls_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_controls( - 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_controls_flattened_error(): - client = ControlServiceClient( - credentials=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_controls( - control_service.ListControlsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_controls_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_controls( - 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_controls_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_controls( - control_service.ListControlsRequest(), - parent='parent_value', - ) - - -def test_list_controls_pager(transport_name: str = "grpc"): - client = ControlServiceClient( - 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_controls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_controls(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, control.Control) - for i in results) -def test_list_controls_pages(transport_name: str = "grpc"): - client = ControlServiceClient( - 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_controls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - pages = list(client.list_controls(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_controls_async_pager(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_controls(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, control.Control) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_controls_async_pages(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_controls(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ControlServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ControlServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ControlServiceClient.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 = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ControlServiceGrpcTransport, - ) - -def test_control_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ControlServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_control_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.control_service.transports.ControlServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ControlServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_control', - 'delete_control', - 'update_control', - 'get_control', - 'list_controls', - ) - 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_control_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.retail_v2alpha.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ControlServiceTransport( - 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_control_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.retail_v2alpha.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ControlServiceTransport() - adc.assert_called_once() - - -def test_control_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) - ControlServiceClient() - 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.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - ], -) -def test_control_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.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - ], -) -def test_control_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.ControlServiceGrpcTransport, grpc_helpers), - (transports.ControlServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_control_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_control_service_host_no_port(transport_name): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_control_service_host_with_port(transport_name): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_control_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ControlServiceGrpcTransport( - 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_control_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ControlServiceGrpcAsyncIOTransport( - 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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = ControlServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = ControlServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_control_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - control = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) - actual = ControlServiceClient.control_path(project, location, catalog, control) - assert expected == actual - - -def test_parse_control_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "control": "clam", - } - path = ControlServiceClient.control_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_control_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ControlServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ControlServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ControlServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ControlServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ControlServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ControlServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ControlServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ControlServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.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 = ControlServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ControlServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.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.ControlServiceTransport, '_prep_wrapped_messages') as prep: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ControlServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ControlServiceClient.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 = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ControlServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ControlServiceClient( - 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", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py deleted file mode 100644 index e1744b72..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_prediction_service.py +++ /dev/null @@ -1,1329 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.prediction_service import PredictionServiceAsyncClient -from google.cloud.retail_v2alpha.services.prediction_service import PredictionServiceClient -from google.cloud.retail_v2alpha.services.prediction_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import prediction_service -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import user_event -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PredictionServiceClient._get_default_mtls_endpoint(None) is None - assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PredictionServiceGrpcTransport, "grpc"), - (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_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", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_prediction_service_client_get_transport_class(): - transport = PredictionServiceClient.get_transport_class() - available_transports = [ - transports.PredictionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = PredictionServiceClient.get_transport_class("grpc") - assert transport == transports.PredictionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - PredictionServiceClient, PredictionServiceAsyncClient -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_prediction_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - prediction_service.PredictRequest, - dict, -]) -def test_predict(request_type, transport: str = 'grpc'): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - response = client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - -@pytest.mark.asyncio -async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - )) - response = await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -@pytest.mark.asyncio -async def test_predict_async_from_dict(): - await test_predict_async(request_type=dict) - - -def test_predict_field_headers(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = prediction_service.PredictResponse() - client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_predict_field_headers_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) - await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PredictionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PredictionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.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 = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, - ) - -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'predict', - ) - 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport( - 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport() - adc.assert_called_once() - - -def test_prediction_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) - PredictionServiceClient() - 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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -def test_prediction_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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -def test_prediction_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.PredictionServiceGrpcTransport, grpc_helpers), - (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_prediction_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_no_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_with_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_prediction_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcTransport( - 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_prediction_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcAsyncIOTransport( - 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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_product_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - product = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - "branch": "winkle", - "product": "nautilus", - } - path = PredictionServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PredictionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = PredictionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = PredictionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = PredictionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PredictionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = PredictionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = PredictionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = PredictionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = PredictionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PredictionServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py deleted file mode 100644 index 1bc17bbe..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_product_service.py +++ /dev/null @@ -1,4287 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.product_service import ProductServiceAsyncClient -from google.cloud.retail_v2alpha.services.product_service import ProductServiceClient -from google.cloud.retail_v2alpha.services.product_service import pagers -from google.cloud.retail_v2alpha.services.product_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import product as gcr_product -from google.cloud.retail_v2alpha.types import product_service -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import purge_config -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ProductServiceClient._get_default_mtls_endpoint(None) is None - assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ProductServiceGrpcTransport, "grpc"), - (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_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", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_product_service_client_get_transport_class(): - transport = ProductServiceClient.get_transport_class() - available_transports = [ - transports.ProductServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ProductServiceClient.get_transport_class("grpc") - assert transport == transports.ProductServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_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(ProductServiceClient, '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(ProductServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ProductServiceClient, ProductServiceAsyncClient -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_product_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.CreateProductRequest, - dict, -]) -def test_create_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_create_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - -@pytest.mark.asyncio -async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_create_product_async_from_dict(): - await test_create_product_async(request_type=dict) - - -def test_create_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - - -def test_create_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - -@pytest.mark.asyncio -async def test_create_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.GetProductRequest, - dict, -]) -def test_get_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_get_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - -@pytest.mark.asyncio -async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_get_product_async_from_dict(): - await test_get_product_async(request_type=dict) - - -def test_get_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = product.Product() - client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.GetProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.GetProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.ListProductsRequest, - dict, -]) -def test_list_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - -@pytest.mark.asyncio -async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_products_async_from_dict(): - await test_list_products_async(request_type=dict) - - -def test_list_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = product_service.ListProductsResponse() - client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_products( - 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_products_flattened_error(): - client = ProductServiceClient( - credentials=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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_products_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_products( - 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_products_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - - -def test_list_products_pager(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_products(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, product.Product) - for i in results) -def test_list_products_pages(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = list(client.list_products(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_products_async_pager(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_products(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, product.Product) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_products_async_pages(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_products(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - product_service.UpdateProductRequest, - dict, -]) -def test_update_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_update_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - -@pytest.mark.asyncio -async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_update_product_async_from_dict(): - await test_update_product_async(request_type=dict) - - -def test_update_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -def test_update_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.DeleteProductRequest, - dict, -]) -def test_delete_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - -@pytest.mark.asyncio -async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_product_async_from_dict(): - await test_delete_product_async(request_type=dict) - - -def test_delete_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = None - client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeProductsRequest, - dict, -]) -def test_purge_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - client.purge_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - -@pytest.mark.asyncio -async def test_purge_products_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.purge_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_products_async_from_dict(): - await test_purge_products_async(request_type=dict) - - -def test_purge_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_purge_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportProductsRequest, - dict, -]) -def test_import_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - -@pytest.mark.asyncio -async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__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_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_products_async_from_dict(): - await test_import_products_async(request_type=dict) - - -def test_import_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - product_service.SetInventoryRequest, - dict, -]) -def test_set_inventory(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_inventory_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - -@pytest.mark.asyncio -async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_inventory_async_from_dict(): - await test_set_inventory_async(request_type=dict) - - -def test_set_inventory_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_inventory_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -def test_set_inventory_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_set_inventory_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_set_inventory_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_inventory_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddFulfillmentPlacesRequest, - dict, -]) -def test_add_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async_from_dict(): - await test_add_fulfillment_places_async(request_type=dict) - - -def test_add_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveFulfillmentPlacesRequest, - dict, -]) -def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async_from_dict(): - await test_remove_fulfillment_places_async(request_type=dict) - - -def test_remove_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddLocalInventoriesRequest, - dict, -]) -def test_add_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_local_inventories_async_from_dict(): - await test_add_local_inventories_async(request_type=dict) - - -def test_add_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveLocalInventoriesRequest, - dict, -]) -def test_remove_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_local_inventories_async_from_dict(): - await test_remove_local_inventories_async(request_type=dict) - - -def test_remove_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProductServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ProductServiceClient.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 = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProductServiceGrpcTransport, - ) - -def test_product_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_product_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.product_service.transports.ProductServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_product', - 'get_product', - 'list_products', - 'update_product', - 'delete_product', - 'purge_products', - 'import_products', - 'set_inventory', - 'add_fulfillment_places', - 'remove_fulfillment_places', - 'add_local_inventories', - 'remove_local_inventories', - ) - 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_product_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.retail_v2alpha.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport( - 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_product_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.retail_v2alpha.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport() - adc.assert_called_once() - - -def test_product_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) - ProductServiceClient() - 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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - ], -) -def test_product_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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - ], -) -def test_product_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.ProductServiceGrpcTransport, grpc_helpers), - (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_product_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_no_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_with_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_product_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcTransport( - 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_product_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcAsyncIOTransport( - 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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_product_service_grpc_lro_client(): - client = ProductServiceClient( - 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_product_service_grpc_lro_async_client(): - client = ProductServiceAsyncClient( - 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" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = ProductServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = ProductServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = ProductServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = ProductServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProductServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ProductServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProductServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ProductServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProductServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ProductServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ProductServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ProductServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ProductServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ProductServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ProductServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py deleted file mode 100644 index 05a00622..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_search_service.py +++ /dev/null @@ -1,1546 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.search_service import SearchServiceAsyncClient -from google.cloud.retail_v2alpha.services.search_service import SearchServiceClient -from google.cloud.retail_v2alpha.services.search_service import pagers -from google.cloud.retail_v2alpha.services.search_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SearchServiceClient._get_default_mtls_endpoint(None) is None - assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SearchServiceGrpcTransport, "grpc"), - (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_search_service_client_get_transport_class(): - transport = SearchServiceClient.get_transport_class() - available_transports = [ - transports.SearchServiceGrpcTransport, - ] - assert transport in available_transports - - transport = SearchServiceClient.get_transport_class("grpc") - assert transport == transports.SearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SearchServiceClient, SearchServiceAsyncClient -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SearchServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - search_service.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - - -def test_search_field_headers(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = search_service.SearchResponse() - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_field_headers_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_search_pager(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('placement', ''), - )), - ) - pager = client.search(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_async_pager(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, - ) - -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_search_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_search_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport() - adc.assert_called_once() - - -def test_search_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SearchServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SearchServiceGrpcTransport, grpc_helpers), - (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_search_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_no_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_with_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_branch_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = SearchServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = SearchServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = SearchServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = SearchServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py deleted file mode 100644 index 12d27ac2..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py +++ /dev/null @@ -1,3329 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.serving_config_service import ServingConfigServiceAsyncClient -from google.cloud.retail_v2alpha.services.serving_config_service import ServingConfigServiceClient -from google.cloud.retail_v2alpha.services.serving_config_service import pagers -from google.cloud.retail_v2alpha.services.serving_config_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import search_service -from google.cloud.retail_v2alpha.types import serving_config -from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config -from google.cloud.retail_v2alpha.types import serving_config_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ServingConfigServiceClient._get_default_mtls_endpoint(None) is None - assert ServingConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServingConfigServiceClient, "grpc"), - (ServingConfigServiceAsyncClient, "grpc_asyncio"), -]) -def test_serving_config_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ServingConfigServiceGrpcTransport, "grpc"), - (transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_serving_config_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", [ - (ServingConfigServiceClient, "grpc"), - (ServingConfigServiceAsyncClient, "grpc_asyncio"), -]) -def test_serving_config_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_serving_config_service_client_get_transport_class(): - transport = ServingConfigServiceClient.get_transport_class() - available_transports = [ - transports.ServingConfigServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ServingConfigServiceClient.get_transport_class("grpc") - assert transport == transports.ServingConfigServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -def test_serving_config_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(ServingConfigServiceClient, '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(ServingConfigServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "true"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "false"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_serving_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ServingConfigServiceClient, ServingConfigServiceAsyncClient -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -def test_serving_config_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_serving_config_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_serving_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_serving_config_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ServingConfigServiceClient( - 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", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_serving_config_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.CreateServingConfigRequest, - dict, -]) -def test_create_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_create_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.create_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - -@pytest.mark.asyncio -async def test_create_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.CreateServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_create_serving_config_async_from_dict(): - await test_create_serving_config_async(request_type=dict) - - -def test_create_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.CreateServingConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.CreateServingConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_serving_config( - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].serving_config - mock_val = gcr_serving_config.ServingConfig(name='name_value') - assert arg == mock_val - arg = args[0].serving_config_id - mock_val = 'serving_config_id_value' - assert arg == mock_val - - -def test_create_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.CreateServingConfigRequest(), - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_serving_config( - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].serving_config - mock_val = gcr_serving_config.ServingConfig(name='name_value') - assert arg == mock_val - arg = args[0].serving_config_id - mock_val = 'serving_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.CreateServingConfigRequest(), - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.DeleteServingConfigRequest, - dict, -]) -def test_delete_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.delete_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - -@pytest.mark.asyncio -async def test_delete_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.DeleteServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_serving_config_async_from_dict(): - await test_delete_serving_config_async(request_type=dict) - - -def test_delete_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.DeleteServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__call__') as call: - call.return_value = None - client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.DeleteServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__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_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.DeleteServingConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__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_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.DeleteServingConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.UpdateServingConfigRequest, - dict, -]) -def test_update_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_update_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.update_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - -@pytest.mark.asyncio -async def test_update_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.UpdateServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_update_serving_config_async_from_dict(): - await test_update_serving_config_async(request_type=dict) - - -def test_update_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.UpdateServingConfigRequest() - - request.serving_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.UpdateServingConfigRequest() - - request.serving_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config.name=name_value', - ) in kw['metadata'] - - -def test_update_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_serving_config( - serving_config=gcr_serving_config.ServingConfig(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].serving_config - mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_serving_config( - serving_config=gcr_serving_config.ServingConfig(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].serving_config - mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.GetServingConfigRequest, - dict, -]) -def test_get_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_get_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.get_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - -@pytest.mark.asyncio -async def test_get_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.GetServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_get_serving_config_async_from_dict(): - await test_get_serving_config_async(request_type=dict) - - -def test_get_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.GetServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - call.return_value = serving_config.ServingConfig() - client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.GetServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) - await client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.GetServingConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.GetServingConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.ListServingConfigsRequest, - dict, -]) -def test_list_serving_configs(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_serving_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_configs), - '__call__') as call: - client.list_serving_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - -@pytest.mark.asyncio -async def test_list_serving_configs_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.ListServingConfigsRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_serving_configs_async_from_dict(): - await test_list_serving_configs_async(request_type=dict) - - -def test_list_serving_configs_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.ListServingConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - call.return_value = serving_config_service.ListServingConfigsResponse() - client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_serving_configs_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.ListServingConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) - await client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_serving_configs_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_serving_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_serving_configs_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_serving_configs_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_serving_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_serving_configs_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent='parent_value', - ) - - -def test_list_serving_configs_pager(transport_name: str = "grpc"): - client = ServingConfigServiceClient( - 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_serving_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_serving_configs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, serving_config.ServingConfig) - for i in results) -def test_list_serving_configs_pages(transport_name: str = "grpc"): - client = ServingConfigServiceClient( - 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_serving_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_serving_configs(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_serving_configs_async_pager(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_serving_configs(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, serving_config.ServingConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_serving_configs_async_pages(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_serving_configs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - serving_config_service.AddControlRequest, - dict, -]) -def test_add_control(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_add_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - client.add_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - -@pytest.mark.asyncio -async def test_add_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.AddControlRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_add_control_async_from_dict(): - await test_add_control_async(request_type=dict) - - -def test_add_control_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.AddControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_control_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.AddControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_add_control_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.add_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - - -def test_add_control_flattened_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_control( - serving_config_service.AddControlRequest(), - serving_config='serving_config_value', - ) - -@pytest.mark.asyncio -async def test_add_control_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.add_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_control_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_control( - serving_config_service.AddControlRequest(), - serving_config='serving_config_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.RemoveControlRequest, - dict, -]) -def test_remove_control(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_remove_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - client.remove_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - -@pytest.mark.asyncio -async def test_remove_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.RemoveControlRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_remove_control_async_from_dict(): - await test_remove_control_async(request_type=dict) - - -def test_remove_control_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.RemoveControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_control_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.RemoveControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_remove_control_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.remove_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - - -def test_remove_control_flattened_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config='serving_config_value', - ) - -@pytest.mark.asyncio -async def test_remove_control_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.remove_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_control_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config='serving_config_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ServingConfigServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ServingConfigServiceClient.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 = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ServingConfigServiceGrpcTransport, - ) - -def test_serving_config_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ServingConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_serving_config_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ServingConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_serving_config', - 'delete_serving_config', - 'update_serving_config', - 'get_serving_config', - 'list_serving_configs', - 'add_control', - 'remove_control', - ) - 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_serving_config_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.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServingConfigServiceTransport( - 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_serving_config_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.retail_v2alpha.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServingConfigServiceTransport() - adc.assert_called_once() - - -def test_serving_config_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) - ServingConfigServiceClient() - 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.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - ], -) -def test_serving_config_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.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - ], -) -def test_serving_config_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.ServingConfigServiceGrpcTransport, grpc_helpers), - (transports.ServingConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_serving_config_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_serving_config_service_host_no_port(transport_name): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_serving_config_service_host_with_port(transport_name): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_serving_config_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServingConfigServiceGrpcTransport( - 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_serving_config_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( - 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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = ServingConfigServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = ServingConfigServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - serving_config = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, serving_config=serving_config, ) - actual = ServingConfigServiceClient.serving_config_path(project, location, catalog, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "serving_config": "clam", - } - path = ServingConfigServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ServingConfigServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ServingConfigServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ServingConfigServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ServingConfigServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ServingConfigServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ServingConfigServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ServingConfigServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ServingConfigServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.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 = ServingConfigServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ServingConfigServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.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.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ServingConfigServiceClient.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 = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ServingConfigServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ServingConfigServiceClient( - 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", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py b/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py deleted file mode 100644 index ef8d7602..00000000 --- a/owl-bot-staging/v2alpha/tests/unit/gapic/retail_v2alpha/test_user_event_service.py +++ /dev/null @@ -1,2038 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2alpha.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.retail_v2alpha.services.user_event_service import UserEventServiceClient -from google.cloud.retail_v2alpha.services.user_event_service import transports -from google.cloud.retail_v2alpha.types import common -from google.cloud.retail_v2alpha.types import import_config -from google.cloud.retail_v2alpha.types import product -from google.cloud.retail_v2alpha.types import promotion -from google.cloud.retail_v2alpha.types import purge_config -from google.cloud.retail_v2alpha.types import user_event -from google.cloud.retail_v2alpha.types import user_event_service -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, UserEventServiceAsyncClient -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - ) - response = client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = user_event.UserEvent() - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) - await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeUserEventsRequest, - dict, -]) -def test_purge_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - -@pytest.mark.asyncio -async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_user_events_async_from_dict(): - await test_purge_user_events_async(request_type=dict) - - -def test_purge_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_purge_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.RejoinUserEventsRequest, - dict, -]) -def test_rejoin_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_rejoin_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - -@pytest.mark.asyncio -async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_rejoin_user_events_async_from_dict(): - await test_rejoin_user_events_async(request_type=dict) - - -def test_rejoin_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_rejoin_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'purge_user_events', - 'import_user_events', - 'rejoin_user_events', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_user_event_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_user_event_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -def test_user_event_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - UserEventServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_no_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_with_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = UserEventServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = UserEventServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_product_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - product = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - "branch": "whelk", - "product": "octopus", - } - path = UserEventServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/.coveragerc b/owl-bot-staging/v2beta/.coveragerc deleted file mode 100644 index a8b114f0..00000000 --- a/owl-bot-staging/v2beta/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/retail/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2beta/.flake8 b/owl-bot-staging/v2beta/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v2beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2beta/MANIFEST.in b/owl-bot-staging/v2beta/MANIFEST.in deleted file mode 100644 index 43074617..00000000 --- a/owl-bot-staging/v2beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/retail *.py -recursive-include google/cloud/retail_v2beta *.py diff --git a/owl-bot-staging/v2beta/README.rst b/owl-bot-staging/v2beta/README.rst deleted file mode 100644 index cb039760..00000000 --- a/owl-bot-staging/v2beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Retail API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Retail API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2beta/docs/conf.py b/owl-bot-staging/v2beta/docs/conf.py deleted file mode 100644 index 5be9eb4b..00000000 --- a/owl-bot-staging/v2beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-retail documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-retail" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-retail-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-retail.tex", - u"google-cloud-retail Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-retail", - u"Google Cloud Retail Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-retail", - u"google-cloud-retail Documentation", - author, - "google-cloud-retail", - "GAPIC library for Google Cloud Retail API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2beta/docs/index.rst b/owl-bot-staging/v2beta/docs/index.rst deleted file mode 100644 index fd60fc85..00000000 --- a/owl-bot-staging/v2beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - retail_v2beta/services - retail_v2beta/types diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst deleted file mode 100644 index 3a7c19e6..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/catalog_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CatalogService --------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.catalog_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.catalog_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst deleted file mode 100644 index 1f6782ed..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/completion_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CompletionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2beta.services.completion_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst deleted file mode 100644 index 86cfcba1..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/control_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ControlService --------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.control_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.control_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst deleted file mode 100644 index 903c951d..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/prediction_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -PredictionService ------------------------------------ - -.. automodule:: google.cloud.retail_v2beta.services.prediction_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst deleted file mode 100644 index 489daa22..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/product_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ProductService --------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.product_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.product_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst deleted file mode 100644 index 591f5c86..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SearchService -------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst deleted file mode 100644 index 04251720..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/services.rst +++ /dev/null @@ -1,13 +0,0 @@ -Services for Google Cloud Retail v2beta API -=========================================== -.. toctree:: - :maxdepth: 2 - - catalog_service - completion_service - control_service - prediction_service - product_service - search_service - serving_config_service - user_event_service diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst deleted file mode 100644 index c074749c..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/serving_config_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ServingConfigService --------------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.serving_config_service - :members: - :inherited-members: - -.. automodule:: google.cloud.retail_v2beta.services.serving_config_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst deleted file mode 100644 index ae17ce43..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Retail v2beta API -======================================== - -.. automodule:: google.cloud.retail_v2beta.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst b/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst deleted file mode 100644 index 11ab3794..00000000 --- a/owl-bot-staging/v2beta/docs/retail_v2beta/user_event_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.retail_v2beta.services.user_event_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta/google/cloud/retail/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail/__init__.py deleted file mode 100644 index 07f795e3..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail/__init__.py +++ /dev/null @@ -1,275 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.retail_v2beta.services.catalog_service.client import CatalogServiceClient -from google.cloud.retail_v2beta.services.catalog_service.async_client import CatalogServiceAsyncClient -from google.cloud.retail_v2beta.services.completion_service.client import CompletionServiceClient -from google.cloud.retail_v2beta.services.completion_service.async_client import CompletionServiceAsyncClient -from google.cloud.retail_v2beta.services.control_service.client import ControlServiceClient -from google.cloud.retail_v2beta.services.control_service.async_client import ControlServiceAsyncClient -from google.cloud.retail_v2beta.services.prediction_service.client import PredictionServiceClient -from google.cloud.retail_v2beta.services.prediction_service.async_client import PredictionServiceAsyncClient -from google.cloud.retail_v2beta.services.product_service.client import ProductServiceClient -from google.cloud.retail_v2beta.services.product_service.async_client import ProductServiceAsyncClient -from google.cloud.retail_v2beta.services.search_service.client import SearchServiceClient -from google.cloud.retail_v2beta.services.search_service.async_client import SearchServiceAsyncClient -from google.cloud.retail_v2beta.services.serving_config_service.client import ServingConfigServiceClient -from google.cloud.retail_v2beta.services.serving_config_service.async_client import ServingConfigServiceAsyncClient -from google.cloud.retail_v2beta.services.user_event_service.client import UserEventServiceClient -from google.cloud.retail_v2beta.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.retail_v2beta.types.catalog import AttributesConfig -from google.cloud.retail_v2beta.types.catalog import Catalog -from google.cloud.retail_v2beta.types.catalog import CatalogAttribute -from google.cloud.retail_v2beta.types.catalog import CompletionConfig -from google.cloud.retail_v2beta.types.catalog import MerchantCenterLink -from google.cloud.retail_v2beta.types.catalog import MerchantCenterLinkingConfig -from google.cloud.retail_v2beta.types.catalog import ProductLevelConfig -from google.cloud.retail_v2beta.types.catalog_service import AddCatalogAttributeRequest -from google.cloud.retail_v2beta.types.catalog_service import GetAttributesConfigRequest -from google.cloud.retail_v2beta.types.catalog_service import GetCompletionConfigRequest -from google.cloud.retail_v2beta.types.catalog_service import GetDefaultBranchRequest -from google.cloud.retail_v2beta.types.catalog_service import GetDefaultBranchResponse -from google.cloud.retail_v2beta.types.catalog_service import ListCatalogsRequest -from google.cloud.retail_v2beta.types.catalog_service import ListCatalogsResponse -from google.cloud.retail_v2beta.types.catalog_service import RemoveCatalogAttributeRequest -from google.cloud.retail_v2beta.types.catalog_service import ReplaceCatalogAttributeRequest -from google.cloud.retail_v2beta.types.catalog_service import SetDefaultBranchRequest -from google.cloud.retail_v2beta.types.catalog_service import UpdateAttributesConfigRequest -from google.cloud.retail_v2beta.types.catalog_service import UpdateCatalogRequest -from google.cloud.retail_v2beta.types.catalog_service import UpdateCompletionConfigRequest -from google.cloud.retail_v2beta.types.common import Audience -from google.cloud.retail_v2beta.types.common import ColorInfo -from google.cloud.retail_v2beta.types.common import Condition -from google.cloud.retail_v2beta.types.common import CustomAttribute -from google.cloud.retail_v2beta.types.common import FulfillmentInfo -from google.cloud.retail_v2beta.types.common import Image -from google.cloud.retail_v2beta.types.common import Interval -from google.cloud.retail_v2beta.types.common import LocalInventory -from google.cloud.retail_v2beta.types.common import PriceInfo -from google.cloud.retail_v2beta.types.common import Rating -from google.cloud.retail_v2beta.types.common import Rule -from google.cloud.retail_v2beta.types.common import UserInfo -from google.cloud.retail_v2beta.types.common import AttributeConfigLevel -from google.cloud.retail_v2beta.types.common import SearchSolutionUseCase -from google.cloud.retail_v2beta.types.common import SolutionType -from google.cloud.retail_v2beta.types.completion_service import CompleteQueryRequest -from google.cloud.retail_v2beta.types.completion_service import CompleteQueryResponse -from google.cloud.retail_v2beta.types.control import Control -from google.cloud.retail_v2beta.types.control_service import CreateControlRequest -from google.cloud.retail_v2beta.types.control_service import DeleteControlRequest -from google.cloud.retail_v2beta.types.control_service import GetControlRequest -from google.cloud.retail_v2beta.types.control_service import ListControlsRequest -from google.cloud.retail_v2beta.types.control_service import ListControlsResponse -from google.cloud.retail_v2beta.types.control_service import UpdateControlRequest -from google.cloud.retail_v2beta.types.export_config import ExportErrorsConfig -from google.cloud.retail_v2beta.types.export_config import ExportMetadata -from google.cloud.retail_v2beta.types.export_config import ExportProductsResponse -from google.cloud.retail_v2beta.types.export_config import ExportUserEventsResponse -from google.cloud.retail_v2beta.types.import_config import BigQuerySource -from google.cloud.retail_v2beta.types.import_config import CompletionDataInputConfig -from google.cloud.retail_v2beta.types.import_config import GcsSource -from google.cloud.retail_v2beta.types.import_config import ImportCompletionDataRequest -from google.cloud.retail_v2beta.types.import_config import ImportCompletionDataResponse -from google.cloud.retail_v2beta.types.import_config import ImportErrorsConfig -from google.cloud.retail_v2beta.types.import_config import ImportMetadata -from google.cloud.retail_v2beta.types.import_config import ImportProductsRequest -from google.cloud.retail_v2beta.types.import_config import ImportProductsResponse -from google.cloud.retail_v2beta.types.import_config import ImportUserEventsRequest -from google.cloud.retail_v2beta.types.import_config import ImportUserEventsResponse -from google.cloud.retail_v2beta.types.import_config import ProductInlineSource -from google.cloud.retail_v2beta.types.import_config import ProductInputConfig -from google.cloud.retail_v2beta.types.import_config import UserEventImportSummary -from google.cloud.retail_v2beta.types.import_config import UserEventInlineSource -from google.cloud.retail_v2beta.types.import_config import UserEventInputConfig -from google.cloud.retail_v2beta.types.prediction_service import PredictRequest -from google.cloud.retail_v2beta.types.prediction_service import PredictResponse -from google.cloud.retail_v2beta.types.product import Product -from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesMetadata -from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesRequest -from google.cloud.retail_v2beta.types.product_service import AddFulfillmentPlacesResponse -from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesMetadata -from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesRequest -from google.cloud.retail_v2beta.types.product_service import AddLocalInventoriesResponse -from google.cloud.retail_v2beta.types.product_service import CreateProductRequest -from google.cloud.retail_v2beta.types.product_service import DeleteProductRequest -from google.cloud.retail_v2beta.types.product_service import GetProductRequest -from google.cloud.retail_v2beta.types.product_service import ListProductsRequest -from google.cloud.retail_v2beta.types.product_service import ListProductsResponse -from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesMetadata -from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesRequest -from google.cloud.retail_v2beta.types.product_service import RemoveFulfillmentPlacesResponse -from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesMetadata -from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesRequest -from google.cloud.retail_v2beta.types.product_service import RemoveLocalInventoriesResponse -from google.cloud.retail_v2beta.types.product_service import SetInventoryMetadata -from google.cloud.retail_v2beta.types.product_service import SetInventoryRequest -from google.cloud.retail_v2beta.types.product_service import SetInventoryResponse -from google.cloud.retail_v2beta.types.product_service import UpdateProductRequest -from google.cloud.retail_v2beta.types.promotion import Promotion -from google.cloud.retail_v2beta.types.purge_config import PurgeMetadata -from google.cloud.retail_v2beta.types.purge_config import PurgeUserEventsRequest -from google.cloud.retail_v2beta.types.purge_config import PurgeUserEventsResponse -from google.cloud.retail_v2beta.types.search_service import SearchRequest -from google.cloud.retail_v2beta.types.search_service import SearchResponse -from google.cloud.retail_v2beta.types.serving_config import ServingConfig -from google.cloud.retail_v2beta.types.serving_config_service import AddControlRequest -from google.cloud.retail_v2beta.types.serving_config_service import CreateServingConfigRequest -from google.cloud.retail_v2beta.types.serving_config_service import DeleteServingConfigRequest -from google.cloud.retail_v2beta.types.serving_config_service import GetServingConfigRequest -from google.cloud.retail_v2beta.types.serving_config_service import ListServingConfigsRequest -from google.cloud.retail_v2beta.types.serving_config_service import ListServingConfigsResponse -from google.cloud.retail_v2beta.types.serving_config_service import RemoveControlRequest -from google.cloud.retail_v2beta.types.serving_config_service import UpdateServingConfigRequest -from google.cloud.retail_v2beta.types.user_event import CompletionDetail -from google.cloud.retail_v2beta.types.user_event import ProductDetail -from google.cloud.retail_v2beta.types.user_event import PurchaseTransaction -from google.cloud.retail_v2beta.types.user_event import UserEvent -from google.cloud.retail_v2beta.types.user_event_service import CollectUserEventRequest -from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsMetadata -from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsRequest -from google.cloud.retail_v2beta.types.user_event_service import RejoinUserEventsResponse -from google.cloud.retail_v2beta.types.user_event_service import WriteUserEventRequest - -__all__ = ('CatalogServiceClient', - 'CatalogServiceAsyncClient', - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', - 'ControlServiceClient', - 'ControlServiceAsyncClient', - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', - 'ProductServiceClient', - 'ProductServiceAsyncClient', - 'SearchServiceClient', - 'SearchServiceAsyncClient', - 'ServingConfigServiceClient', - 'ServingConfigServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'AttributesConfig', - 'Catalog', - 'CatalogAttribute', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'ProductLevelConfig', - 'AddCatalogAttributeRequest', - 'GetAttributesConfigRequest', - 'GetCompletionConfigRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - 'SetDefaultBranchRequest', - 'UpdateAttributesConfigRequest', - 'UpdateCatalogRequest', - 'UpdateCompletionConfigRequest', - 'Audience', - 'ColorInfo', - 'Condition', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'Rule', - 'UserInfo', - 'AttributeConfigLevel', - 'SearchSolutionUseCase', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Control', - 'CreateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - 'UpdateControlRequest', - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'ServingConfig', - 'AddControlRequest', - 'CreateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'RemoveControlRequest', - 'UpdateServingConfigRequest', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail/py.typed b/owl-bot-staging/v2beta/google/cloud/retail/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py deleted file mode 100644 index 3ad83ab4..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/__init__.py +++ /dev/null @@ -1,276 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.catalog_service import CatalogServiceClient -from .services.catalog_service import CatalogServiceAsyncClient -from .services.completion_service import CompletionServiceClient -from .services.completion_service import CompletionServiceAsyncClient -from .services.control_service import ControlServiceClient -from .services.control_service import ControlServiceAsyncClient -from .services.prediction_service import PredictionServiceClient -from .services.prediction_service import PredictionServiceAsyncClient -from .services.product_service import ProductServiceClient -from .services.product_service import ProductServiceAsyncClient -from .services.search_service import SearchServiceClient -from .services.search_service import SearchServiceAsyncClient -from .services.serving_config_service import ServingConfigServiceClient -from .services.serving_config_service import ServingConfigServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.catalog import AttributesConfig -from .types.catalog import Catalog -from .types.catalog import CatalogAttribute -from .types.catalog import CompletionConfig -from .types.catalog import MerchantCenterLink -from .types.catalog import MerchantCenterLinkingConfig -from .types.catalog import ProductLevelConfig -from .types.catalog_service import AddCatalogAttributeRequest -from .types.catalog_service import GetAttributesConfigRequest -from .types.catalog_service import GetCompletionConfigRequest -from .types.catalog_service import GetDefaultBranchRequest -from .types.catalog_service import GetDefaultBranchResponse -from .types.catalog_service import ListCatalogsRequest -from .types.catalog_service import ListCatalogsResponse -from .types.catalog_service import RemoveCatalogAttributeRequest -from .types.catalog_service import ReplaceCatalogAttributeRequest -from .types.catalog_service import SetDefaultBranchRequest -from .types.catalog_service import UpdateAttributesConfigRequest -from .types.catalog_service import UpdateCatalogRequest -from .types.catalog_service import UpdateCompletionConfigRequest -from .types.common import Audience -from .types.common import ColorInfo -from .types.common import Condition -from .types.common import CustomAttribute -from .types.common import FulfillmentInfo -from .types.common import Image -from .types.common import Interval -from .types.common import LocalInventory -from .types.common import PriceInfo -from .types.common import Rating -from .types.common import Rule -from .types.common import UserInfo -from .types.common import AttributeConfigLevel -from .types.common import SearchSolutionUseCase -from .types.common import SolutionType -from .types.completion_service import CompleteQueryRequest -from .types.completion_service import CompleteQueryResponse -from .types.control import Control -from .types.control_service import CreateControlRequest -from .types.control_service import DeleteControlRequest -from .types.control_service import GetControlRequest -from .types.control_service import ListControlsRequest -from .types.control_service import ListControlsResponse -from .types.control_service import UpdateControlRequest -from .types.export_config import ExportErrorsConfig -from .types.export_config import ExportMetadata -from .types.export_config import ExportProductsResponse -from .types.export_config import ExportUserEventsResponse -from .types.import_config import BigQuerySource -from .types.import_config import CompletionDataInputConfig -from .types.import_config import GcsSource -from .types.import_config import ImportCompletionDataRequest -from .types.import_config import ImportCompletionDataResponse -from .types.import_config import ImportErrorsConfig -from .types.import_config import ImportMetadata -from .types.import_config import ImportProductsRequest -from .types.import_config import ImportProductsResponse -from .types.import_config import ImportUserEventsRequest -from .types.import_config import ImportUserEventsResponse -from .types.import_config import ProductInlineSource -from .types.import_config import ProductInputConfig -from .types.import_config import UserEventImportSummary -from .types.import_config import UserEventInlineSource -from .types.import_config import UserEventInputConfig -from .types.prediction_service import PredictRequest -from .types.prediction_service import PredictResponse -from .types.product import Product -from .types.product_service import AddFulfillmentPlacesMetadata -from .types.product_service import AddFulfillmentPlacesRequest -from .types.product_service import AddFulfillmentPlacesResponse -from .types.product_service import AddLocalInventoriesMetadata -from .types.product_service import AddLocalInventoriesRequest -from .types.product_service import AddLocalInventoriesResponse -from .types.product_service import CreateProductRequest -from .types.product_service import DeleteProductRequest -from .types.product_service import GetProductRequest -from .types.product_service import ListProductsRequest -from .types.product_service import ListProductsResponse -from .types.product_service import RemoveFulfillmentPlacesMetadata -from .types.product_service import RemoveFulfillmentPlacesRequest -from .types.product_service import RemoveFulfillmentPlacesResponse -from .types.product_service import RemoveLocalInventoriesMetadata -from .types.product_service import RemoveLocalInventoriesRequest -from .types.product_service import RemoveLocalInventoriesResponse -from .types.product_service import SetInventoryMetadata -from .types.product_service import SetInventoryRequest -from .types.product_service import SetInventoryResponse -from .types.product_service import UpdateProductRequest -from .types.promotion import Promotion -from .types.purge_config import PurgeMetadata -from .types.purge_config import PurgeUserEventsRequest -from .types.purge_config import PurgeUserEventsResponse -from .types.search_service import SearchRequest -from .types.search_service import SearchResponse -from .types.serving_config import ServingConfig -from .types.serving_config_service import AddControlRequest -from .types.serving_config_service import CreateServingConfigRequest -from .types.serving_config_service import DeleteServingConfigRequest -from .types.serving_config_service import GetServingConfigRequest -from .types.serving_config_service import ListServingConfigsRequest -from .types.serving_config_service import ListServingConfigsResponse -from .types.serving_config_service import RemoveControlRequest -from .types.serving_config_service import UpdateServingConfigRequest -from .types.user_event import CompletionDetail -from .types.user_event import ProductDetail -from .types.user_event import PurchaseTransaction -from .types.user_event import UserEvent -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import RejoinUserEventsMetadata -from .types.user_event_service import RejoinUserEventsRequest -from .types.user_event_service import RejoinUserEventsResponse -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CatalogServiceAsyncClient', - 'CompletionServiceAsyncClient', - 'ControlServiceAsyncClient', - 'PredictionServiceAsyncClient', - 'ProductServiceAsyncClient', - 'SearchServiceAsyncClient', - 'ServingConfigServiceAsyncClient', - 'UserEventServiceAsyncClient', -'AddCatalogAttributeRequest', -'AddControlRequest', -'AddFulfillmentPlacesMetadata', -'AddFulfillmentPlacesRequest', -'AddFulfillmentPlacesResponse', -'AddLocalInventoriesMetadata', -'AddLocalInventoriesRequest', -'AddLocalInventoriesResponse', -'AttributeConfigLevel', -'AttributesConfig', -'Audience', -'BigQuerySource', -'Catalog', -'CatalogAttribute', -'CatalogServiceClient', -'CollectUserEventRequest', -'ColorInfo', -'CompleteQueryRequest', -'CompleteQueryResponse', -'CompletionConfig', -'CompletionDataInputConfig', -'CompletionDetail', -'CompletionServiceClient', -'Condition', -'Control', -'ControlServiceClient', -'CreateControlRequest', -'CreateProductRequest', -'CreateServingConfigRequest', -'CustomAttribute', -'DeleteControlRequest', -'DeleteProductRequest', -'DeleteServingConfigRequest', -'ExportErrorsConfig', -'ExportMetadata', -'ExportProductsResponse', -'ExportUserEventsResponse', -'FulfillmentInfo', -'GcsSource', -'GetAttributesConfigRequest', -'GetCompletionConfigRequest', -'GetControlRequest', -'GetDefaultBranchRequest', -'GetDefaultBranchResponse', -'GetProductRequest', -'GetServingConfigRequest', -'Image', -'ImportCompletionDataRequest', -'ImportCompletionDataResponse', -'ImportErrorsConfig', -'ImportMetadata', -'ImportProductsRequest', -'ImportProductsResponse', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'Interval', -'ListCatalogsRequest', -'ListCatalogsResponse', -'ListControlsRequest', -'ListControlsResponse', -'ListProductsRequest', -'ListProductsResponse', -'ListServingConfigsRequest', -'ListServingConfigsResponse', -'LocalInventory', -'MerchantCenterLink', -'MerchantCenterLinkingConfig', -'PredictRequest', -'PredictResponse', -'PredictionServiceClient', -'PriceInfo', -'Product', -'ProductDetail', -'ProductInlineSource', -'ProductInputConfig', -'ProductLevelConfig', -'ProductServiceClient', -'Promotion', -'PurchaseTransaction', -'PurgeMetadata', -'PurgeUserEventsRequest', -'PurgeUserEventsResponse', -'Rating', -'RejoinUserEventsMetadata', -'RejoinUserEventsRequest', -'RejoinUserEventsResponse', -'RemoveCatalogAttributeRequest', -'RemoveControlRequest', -'RemoveFulfillmentPlacesMetadata', -'RemoveFulfillmentPlacesRequest', -'RemoveFulfillmentPlacesResponse', -'RemoveLocalInventoriesMetadata', -'RemoveLocalInventoriesRequest', -'RemoveLocalInventoriesResponse', -'ReplaceCatalogAttributeRequest', -'Rule', -'SearchRequest', -'SearchResponse', -'SearchServiceClient', -'SearchSolutionUseCase', -'ServingConfig', -'ServingConfigServiceClient', -'SetDefaultBranchRequest', -'SetInventoryMetadata', -'SetInventoryRequest', -'SetInventoryResponse', -'SolutionType', -'UpdateAttributesConfigRequest', -'UpdateCatalogRequest', -'UpdateCompletionConfigRequest', -'UpdateControlRequest', -'UpdateProductRequest', -'UpdateServingConfigRequest', -'UserEvent', -'UserEventImportSummary', -'UserEventInlineSource', -'UserEventInputConfig', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json deleted file mode 100644 index bf3205b9..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/gapic_metadata.json +++ /dev/null @@ -1,551 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.retail_v2beta", - "protoPackage": "google.cloud.retail.v2beta", - "schema": "1.0", - "services": { - "CatalogService": { - "clients": { - "grpc": { - "libraryClient": "CatalogServiceClient", - "rpcs": { - "AddCatalogAttribute": { - "methods": [ - "add_catalog_attribute" - ] - }, - "GetAttributesConfig": { - "methods": [ - "get_attributes_config" - ] - }, - "GetCompletionConfig": { - "methods": [ - "get_completion_config" - ] - }, - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "RemoveCatalogAttribute": { - "methods": [ - "remove_catalog_attribute" - ] - }, - "ReplaceCatalogAttribute": { - "methods": [ - "replace_catalog_attribute" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateAttributesConfig": { - "methods": [ - "update_attributes_config" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - }, - "UpdateCompletionConfig": { - "methods": [ - "update_completion_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CatalogServiceAsyncClient", - "rpcs": { - "AddCatalogAttribute": { - "methods": [ - "add_catalog_attribute" - ] - }, - "GetAttributesConfig": { - "methods": [ - "get_attributes_config" - ] - }, - "GetCompletionConfig": { - "methods": [ - "get_completion_config" - ] - }, - "GetDefaultBranch": { - "methods": [ - "get_default_branch" - ] - }, - "ListCatalogs": { - "methods": [ - "list_catalogs" - ] - }, - "RemoveCatalogAttribute": { - "methods": [ - "remove_catalog_attribute" - ] - }, - "ReplaceCatalogAttribute": { - "methods": [ - "replace_catalog_attribute" - ] - }, - "SetDefaultBranch": { - "methods": [ - "set_default_branch" - ] - }, - "UpdateAttributesConfig": { - "methods": [ - "update_attributes_config" - ] - }, - "UpdateCatalog": { - "methods": [ - "update_catalog" - ] - }, - "UpdateCompletionConfig": { - "methods": [ - "update_completion_config" - ] - } - } - } - } - }, - "CompletionService": { - "clients": { - "grpc": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CompletionServiceAsyncClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - }, - "ImportCompletionData": { - "methods": [ - "import_completion_data" - ] - } - } - } - } - }, - "ControlService": { - "clients": { - "grpc": { - "libraryClient": "ControlServiceClient", - "rpcs": { - "CreateControl": { - "methods": [ - "create_control" - ] - }, - "DeleteControl": { - "methods": [ - "delete_control" - ] - }, - "GetControl": { - "methods": [ - "get_control" - ] - }, - "ListControls": { - "methods": [ - "list_controls" - ] - }, - "UpdateControl": { - "methods": [ - "update_control" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ControlServiceAsyncClient", - "rpcs": { - "CreateControl": { - "methods": [ - "create_control" - ] - }, - "DeleteControl": { - "methods": [ - "delete_control" - ] - }, - "GetControl": { - "methods": [ - "get_control" - ] - }, - "ListControls": { - "methods": [ - "list_controls" - ] - }, - "UpdateControl": { - "methods": [ - "update_control" - ] - } - } - } - } - }, - "PredictionService": { - "clients": { - "grpc": { - "libraryClient": "PredictionServiceClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PredictionServiceAsyncClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - } - } - }, - "ProductService": { - "clients": { - "grpc": { - "libraryClient": "ProductServiceClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProductServiceAsyncClient", - "rpcs": { - "AddFulfillmentPlaces": { - "methods": [ - "add_fulfillment_places" - ] - }, - "AddLocalInventories": { - "methods": [ - "add_local_inventories" - ] - }, - "CreateProduct": { - "methods": [ - "create_product" - ] - }, - "DeleteProduct": { - "methods": [ - "delete_product" - ] - }, - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ImportProducts": { - "methods": [ - "import_products" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - }, - "RemoveFulfillmentPlaces": { - "methods": [ - "remove_fulfillment_places" - ] - }, - "RemoveLocalInventories": { - "methods": [ - "remove_local_inventories" - ] - }, - "SetInventory": { - "methods": [ - "set_inventory" - ] - }, - "UpdateProduct": { - "methods": [ - "update_product" - ] - } - } - } - } - }, - "SearchService": { - "clients": { - "grpc": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SearchServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - }, - "ServingConfigService": { - "clients": { - "grpc": { - "libraryClient": "ServingConfigServiceClient", - "rpcs": { - "AddControl": { - "methods": [ - "add_control" - ] - }, - "CreateServingConfig": { - "methods": [ - "create_serving_config" - ] - }, - "DeleteServingConfig": { - "methods": [ - "delete_serving_config" - ] - }, - "GetServingConfig": { - "methods": [ - "get_serving_config" - ] - }, - "ListServingConfigs": { - "methods": [ - "list_serving_configs" - ] - }, - "RemoveControl": { - "methods": [ - "remove_control" - ] - }, - "UpdateServingConfig": { - "methods": [ - "update_serving_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ServingConfigServiceAsyncClient", - "rpcs": { - "AddControl": { - "methods": [ - "add_control" - ] - }, - "CreateServingConfig": { - "methods": [ - "create_serving_config" - ] - }, - "DeleteServingConfig": { - "methods": [ - "delete_serving_config" - ] - }, - "GetServingConfig": { - "methods": [ - "get_serving_config" - ] - }, - "ListServingConfigs": { - "methods": [ - "list_serving_configs" - ] - }, - "RemoveControl": { - "methods": [ - "remove_control" - ] - }, - "UpdateServingConfig": { - "methods": [ - "update_serving_config" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "RejoinUserEvents": { - "methods": [ - "rejoin_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed deleted file mode 100644 index fda82836..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-retail package uses inline types. diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py deleted file mode 100644 index d276b897..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CatalogServiceClient -from .async_client import CatalogServiceAsyncClient - -__all__ = ( - 'CatalogServiceClient', - 'CatalogServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py deleted file mode 100644 index dfff033b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/async_client.py +++ /dev/null @@ -1,1350 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.catalog_service import pagers -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport -from .client import CatalogServiceClient - - -class CatalogServiceAsyncClient: - """Service for managing catalog configuration.""" - - _client: CatalogServiceClient - - DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT - - attributes_config_path = staticmethod(CatalogServiceClient.attributes_config_path) - parse_attributes_config_path = staticmethod(CatalogServiceClient.parse_attributes_config_path) - branch_path = staticmethod(CatalogServiceClient.branch_path) - parse_branch_path = staticmethod(CatalogServiceClient.parse_branch_path) - catalog_path = staticmethod(CatalogServiceClient.catalog_path) - parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) - completion_config_path = staticmethod(CatalogServiceClient.completion_config_path) - parse_completion_config_path = staticmethod(CatalogServiceClient.parse_completion_config_path) - common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CatalogServiceClient.common_project_path) - parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) - common_location_path = staticmethod(CatalogServiceClient.common_location_path) - parse_common_location_path = staticmethod(CatalogServiceClient.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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, 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 variabel 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 CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CatalogServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsAsyncPager: - r"""Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_list_catalogs(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - parent (:class:`str`): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2beta.Catalog]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.retail_v2beta.services.catalog_service.pagers.ListCatalogsAsyncPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.ListCatalogsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_catalogs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCatalogsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_catalog(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2beta.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2beta.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] - method. - catalog (:class:`google.cloud.retail_v2beta.types.Catalog`): - Required. The - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2beta.Catalog], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Catalog][google.cloud.retail.v2beta.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCatalogRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_catalog, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_set_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (:class:`str`): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.SetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (:class:`str`): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetDefaultBranchRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # 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_default_branch, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_completion_config(self, - request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Gets a - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] - method. - name (:class:`str`): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - - 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.retail_v2beta.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetCompletionConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_completion_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_completion_config(self, - request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, - *, - completion_config: catalog.CompletionConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Updates the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - completion_config = retail_v2beta.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2beta.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = await client.update_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] - method. - completion_config (:class:`google.cloud.retail_v2beta.types.CompletionConfig`): - Required. The - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``completion_config`` 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 - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([completion_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCompletionConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if completion_config is not None: - request.completion_config = completion_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_completion_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("completion_config.name", request.completion_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_attributes_config(self, - request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Gets an - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] - method. - name (:class:`str`): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - - 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.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetAttributesConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_attributes_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_attributes_config(self, - request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, - *, - attributes_config: catalog.AttributesConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Updates the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - attributes_config = retail_v2beta.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2beta.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = await client.update_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] - method. - attributes_config (:class:`google.cloud.retail_v2beta.types.AttributesConfig`): - Required. The - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. - - This corresponds to the ``attributes_config`` 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 - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([attributes_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateAttributesConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attributes_config is not None: - request.attributes_config = attributes_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_attributes_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config.name", request.attributes_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def add_catalog_attribute(self, - request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Adds the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_add_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.AddCatalogAttributeRequest(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.add_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def remove_catalog_attribute(self, - request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Removes the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = await client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.RemoveCatalogAttributeRequest(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.remove_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def replace_catalog_attribute(self, - request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Replaces the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - request = catalog_service.ReplaceCatalogAttributeRequest(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.replace_catalog_attribute, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py deleted file mode 100644 index c95200de..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/client.py +++ /dev/null @@ -1,1580 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.catalog_service import pagers -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CatalogServiceGrpcTransport -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -class CatalogServiceClientMeta(type): - """Metaclass for the CatalogService 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[CatalogServiceTransport]] - _transport_registry["grpc"] = CatalogServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CatalogServiceTransport]: - """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): - """Service for managing catalog configuration.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CatalogServiceClient: 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: - CatalogServiceClient: 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) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def attributes_config_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified attributes_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_attributes_config_path(path: str) -> Dict[str,str]: - """Parses a attributes_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/attributesConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def completion_config_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified completion_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_completion_config_path(path: str) -> Dict[str,str]: - """Parses a completion_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/completionConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CatalogServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CatalogServiceTransport): - # transport is a CatalogServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_catalogs(self, - request: Union[catalog_service.ListCatalogsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogsPager: - r"""Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s - associated with the project. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_list_catalogs(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListCatalogsRequest, dict]): - The request object. Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2beta.Catalog]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.retail_v2beta.services.catalog_service.pagers.ListCatalogsPager: - Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ListCatalogsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ListCatalogsRequest): - request = catalog_service.ListCatalogsRequest(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_catalogs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCatalogsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_catalog(self, - request: Union[catalog_service.UpdateCatalogRequest, dict] = None, - *, - catalog: gcr_catalog.Catalog = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_catalog.Catalog: - r"""Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_catalog(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2beta.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2beta.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateCatalogRequest, dict]): - The request object. Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] - method. - catalog (google.cloud.retail_v2beta.types.Catalog): - Required. The - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2beta.Catalog], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Catalog][google.cloud.retail.v2beta.Catalog] to - update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``catalog`` 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 - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Catalog: - The catalog configuration. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCatalogRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCatalogRequest): - request = catalog_service.UpdateCatalogRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - 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_catalog] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog.name", request.catalog.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_default_branch(self, - request: Union[catalog_service.SetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_set_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.SetDefaultBranchRequest, dict]): - The request object. Request message to set a specified - branch as new default_branch. - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.SetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.SetDefaultBranchRequest): - request = catalog_service.SetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_default_branch(self, - request: Union[catalog_service.GetDefaultBranchRequest, dict] = None, - *, - catalog: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog_service.GetDefaultBranchResponse: - r"""Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetDefaultBranchRequest, dict]): - The request object. Request message to show which branch - is currently the default branch. - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``catalog`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.GetDefaultBranchResponse: - Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([catalog]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetDefaultBranchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetDefaultBranchRequest): - request = catalog_service.GetDefaultBranchRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if catalog is not None: - request.catalog = catalog - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_default_branch] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_completion_config(self, - request: Union[catalog_service.GetCompletionConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Gets a - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] - method. - name (str): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - - 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.retail_v2beta.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetCompletionConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetCompletionConfigRequest): - request = catalog_service.GetCompletionConfigRequest(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_completion_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_completion_config(self, - request: Union[catalog_service.UpdateCompletionConfigRequest, dict] = None, - *, - completion_config: catalog.CompletionConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CompletionConfig: - r"""Updates the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - completion_config = retail_v2beta.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2beta.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = client.update_completion_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] - method. - completion_config (google.cloud.retail_v2beta.types.CompletionConfig): - Required. The - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update does not exist, a NOT_FOUND error is returned. - - This corresponds to the ``completion_config`` 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 - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.CompletionConfig: - Catalog level autocomplete config for - customers to customize autocomplete - feature's settings. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([completion_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCompletionConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCompletionConfigRequest): - request = catalog_service.UpdateCompletionConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if completion_config is not None: - request.completion_config = completion_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_completion_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("completion_config.name", request.completion_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_attributes_config(self, - request: Union[catalog_service.GetAttributesConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Gets an - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] - method. - name (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - - 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.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetAttributesConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetAttributesConfigRequest): - request = catalog_service.GetAttributesConfigRequest(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_attributes_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_attributes_config(self, - request: Union[catalog_service.UpdateAttributesConfigRequest, dict] = None, - *, - attributes_config: catalog.AttributesConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Updates the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - attributes_config = retail_v2beta.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2beta.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = client.update_attributes_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest, dict]): - The request object. Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] - method. - attributes_config (google.cloud.retail_v2beta.types.AttributesConfig): - Required. The - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. - - This corresponds to the ``attributes_config`` 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 - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([attributes_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateAttributesConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateAttributesConfigRequest): - request = catalog_service.UpdateAttributesConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attributes_config is not None: - request.attributes_config = attributes_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_attributes_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config.name", request.attributes_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def add_catalog_attribute(self, - request: Union[catalog_service.AddCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Adds the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_add_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.AddCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.AddCatalogAttributeRequest): - request = catalog_service.AddCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def remove_catalog_attribute(self, - request: Union[catalog_service.RemoveCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Removes the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.RemoveCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.RemoveCatalogAttributeRequest): - request = catalog_service.RemoveCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def replace_catalog_attribute(self, - request: Union[catalog_service.ReplaceCatalogAttributeRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.AttributesConfig: - r"""Replaces the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest, dict]): - The request object. Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.AttributesConfig: - Catalog level attribute config. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ReplaceCatalogAttributeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ReplaceCatalogAttributeRequest): - request = catalog_service.ReplaceCatalogAttributeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.replace_catalog_attribute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attributes_config", request.attributes_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py deleted file mode 100644 index 0ca25546..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog_service - - -class ListCatalogsPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` - 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[..., catalog_service.ListCatalogsResponse], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2beta.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - for page in self.pages: - yield from page.catalogs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCatalogsAsyncPager: - """A pager for iterating through ``list_catalogs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``catalogs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCatalogs`` requests and continue to iterate - through the ``catalogs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListCatalogsResponse` - 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[catalog_service.ListCatalogsResponse]], - request: catalog_service.ListCatalogsRequest, - response: catalog_service.ListCatalogsResponse, - *, - 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.retail_v2beta.types.ListCatalogsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListCatalogsResponse): - 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 = catalog_service.ListCatalogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[catalog_service.ListCatalogsResponse]: - 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[catalog.Catalog]: - async def async_generator(): - async for page in self.pages: - for response in page.catalogs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py deleted file mode 100644 index 0cffa336..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CatalogServiceTransport -from .grpc import CatalogServiceGrpcTransport -from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] -_transport_registry['grpc'] = CatalogServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport - -__all__ = ( - 'CatalogServiceTransport', - 'CatalogServiceGrpcTransport', - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py deleted file mode 100644 index 90964f49..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/base.py +++ /dev/null @@ -1,297 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CatalogServiceTransport(abc.ABC): - """Abstract transport class for CatalogService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_catalogs: gapic_v1.method.wrap_method( - self.list_catalogs, - default_timeout=None, - client_info=client_info, - ), - self.update_catalog: gapic_v1.method.wrap_method( - self.update_catalog, - default_timeout=None, - client_info=client_info, - ), - self.set_default_branch: gapic_v1.method.wrap_method( - self.set_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_default_branch: gapic_v1.method.wrap_method( - self.get_default_branch, - default_timeout=None, - client_info=client_info, - ), - self.get_completion_config: gapic_v1.method.wrap_method( - self.get_completion_config, - default_timeout=None, - client_info=client_info, - ), - self.update_completion_config: gapic_v1.method.wrap_method( - self.update_completion_config, - default_timeout=None, - client_info=client_info, - ), - self.get_attributes_config: gapic_v1.method.wrap_method( - self.get_attributes_config, - default_timeout=None, - client_info=client_info, - ), - self.update_attributes_config: gapic_v1.method.wrap_method( - self.update_attributes_config, - default_timeout=None, - client_info=client_info, - ), - self.add_catalog_attribute: gapic_v1.method.wrap_method( - self.add_catalog_attribute, - default_timeout=None, - client_info=client_info, - ), - self.remove_catalog_attribute: gapic_v1.method.wrap_method( - self.remove_catalog_attribute, - default_timeout=None, - client_info=client_info, - ), - self.replace_catalog_attribute: gapic_v1.method.wrap_method( - self.replace_catalog_attribute, - 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Union[ - catalog_service.ListCatalogsResponse, - Awaitable[catalog_service.ListCatalogsResponse] - ]]: - raise NotImplementedError() - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Union[ - gcr_catalog.Catalog, - Awaitable[gcr_catalog.Catalog] - ]]: - raise NotImplementedError() - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Union[ - catalog_service.GetDefaultBranchResponse, - Awaitable[catalog_service.GetDefaultBranchResponse] - ]]: - raise NotImplementedError() - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - Union[ - catalog.CompletionConfig, - Awaitable[catalog.CompletionConfig] - ]]: - raise NotImplementedError() - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - Union[ - catalog.CompletionConfig, - Awaitable[catalog.CompletionConfig] - ]]: - raise NotImplementedError() - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - Union[ - catalog.AttributesConfig, - Awaitable[catalog.AttributesConfig] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CatalogServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py deleted file mode 100644 index 9ae369d1..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc.py +++ /dev/null @@ -1,600 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO - - -class CatalogServiceGrpcTransport(CatalogServiceTransport): - """gRPC backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - catalog_service.ListCatalogsResponse]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - ~.ListCatalogsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - gcr_catalog.Catalog]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - ~.Catalog]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - empty_pb2.Empty]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - ~.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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - catalog_service.GetDefaultBranchResponse]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - ~.GetDefaultBranchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - catalog.CompletionConfig]: - r"""Return a callable for the get completion config method over gRPC. - - Gets a - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. - - Returns: - Callable[[~.GetCompletionConfigRequest], - ~.CompletionConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetCompletionConfig', - request_serializer=catalog_service.GetCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['get_completion_config'] - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - catalog.CompletionConfig]: - r"""Return a callable for the update completion config method over gRPC. - - Updates the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. - - Returns: - Callable[[~.UpdateCompletionConfigRequest], - ~.CompletionConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateCompletionConfig', - request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['update_completion_config'] - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - catalog.AttributesConfig]: - r"""Return a callable for the get attributes config method over gRPC. - - Gets an - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - Returns: - Callable[[~.GetAttributesConfigRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetAttributesConfig', - request_serializer=catalog_service.GetAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['get_attributes_config'] - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - catalog.AttributesConfig]: - r"""Return a callable for the update attributes config method over gRPC. - - Updates the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - Returns: - Callable[[~.UpdateAttributesConfigRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateAttributesConfig', - request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['update_attributes_config'] - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the add catalog attribute method over gRPC. - - Adds the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.AddCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_catalog_attribute' not in self._stubs: - self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/AddCatalogAttribute', - request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['add_catalog_attribute'] - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the remove catalog attribute method over gRPC. - - Removes the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.RemoveCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_catalog_attribute' not in self._stubs: - self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/RemoveCatalogAttribute', - request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['remove_catalog_attribute'] - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - catalog.AttributesConfig]: - r"""Return a callable for the replace catalog attribute method over gRPC. - - Replaces the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.ReplaceCatalogAttributeRequest], - ~.AttributesConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_catalog_attribute' not in self._stubs: - self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/ReplaceCatalogAttribute', - request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['replace_catalog_attribute'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CatalogServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py deleted file mode 100644 index 37eaea4b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,599 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CatalogServiceGrpcTransport - - -class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): - """gRPC AsyncIO backend transport for CatalogService. - - Service for managing catalog configuration. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_catalogs(self) -> Callable[ - [catalog_service.ListCatalogsRequest], - Awaitable[catalog_service.ListCatalogsResponse]]: - r"""Return a callable for the list catalogs method over gRPC. - - Lists all the [Catalog][google.cloud.retail.v2beta.Catalog]s - associated with the project. - - Returns: - Callable[[~.ListCatalogsRequest], - Awaitable[~.ListCatalogsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalogs' not in self._stubs: - self._stubs['list_catalogs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/ListCatalogs', - request_serializer=catalog_service.ListCatalogsRequest.serialize, - response_deserializer=catalog_service.ListCatalogsResponse.deserialize, - ) - return self._stubs['list_catalogs'] - - @property - def update_catalog(self) -> Callable[ - [catalog_service.UpdateCatalogRequest], - Awaitable[gcr_catalog.Catalog]]: - r"""Return a callable for the update catalog method over gRPC. - - Updates the [Catalog][google.cloud.retail.v2beta.Catalog]s. - - Returns: - Callable[[~.UpdateCatalogRequest], - Awaitable[~.Catalog]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog' not in self._stubs: - self._stubs['update_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateCatalog', - request_serializer=catalog_service.UpdateCatalogRequest.serialize, - response_deserializer=gcr_catalog.Catalog.deserialize, - ) - return self._stubs['update_catalog'] - - @property - def set_default_branch(self) -> Callable[ - [catalog_service.SetDefaultBranchRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the set default branch method over gRPC. - - Set a specified branch id as default branch. API methods such as - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct], - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - will treat requests using "default_branch" to the actual branch - id set as default. - - For example, if ``projects/*/locations/*/catalogs/*/branches/1`` - is set as default, setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/default_branch`` - is equivalent to setting - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to ``projects/*/locations/*/catalogs/*/branches/1``. - - Using multiple branches can be useful when developers would like - to have a staging branch to test and verify for future usage. - When it becomes ready, developers switch on the staging branch - using this API while keeping using - ``projects/*/locations/*/catalogs/*/branches/default_branch`` as - [SearchRequest.branch][google.cloud.retail.v2beta.SearchRequest.branch] - to route the traffic to this staging branch. - - CAUTION: If you have live predict/search traffic, switching the - default branch could potentially cause outages if the ID space - of the new branch is very different from the old one. - - More specifically: - - - PredictionService will only return product IDs from branch - {newBranch}. - - SearchService will only return product IDs from branch - {newBranch} (if branch is not explicitly set). - - UserEventService will only join events with products from - branch {newBranch}. - - Returns: - Callable[[~.SetDefaultBranchRequest], - 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 'set_default_branch' not in self._stubs: - self._stubs['set_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/SetDefaultBranch', - request_serializer=catalog_service.SetDefaultBranchRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['set_default_branch'] - - @property - def get_default_branch(self) -> Callable[ - [catalog_service.GetDefaultBranchRequest], - Awaitable[catalog_service.GetDefaultBranchResponse]]: - r"""Return a callable for the get default branch method over gRPC. - - Get which branch is currently default branch set by - [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] - method under a specified parent catalog. - - Returns: - Callable[[~.GetDefaultBranchRequest], - Awaitable[~.GetDefaultBranchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_default_branch' not in self._stubs: - self._stubs['get_default_branch'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetDefaultBranch', - request_serializer=catalog_service.GetDefaultBranchRequest.serialize, - response_deserializer=catalog_service.GetDefaultBranchResponse.deserialize, - ) - return self._stubs['get_default_branch'] - - @property - def get_completion_config(self) -> Callable[ - [catalog_service.GetCompletionConfigRequest], - Awaitable[catalog.CompletionConfig]]: - r"""Return a callable for the get completion config method over gRPC. - - Gets a - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]. - - Returns: - Callable[[~.GetCompletionConfigRequest], - Awaitable[~.CompletionConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['get_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetCompletionConfig', - request_serializer=catalog_service.GetCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['get_completion_config'] - - @property - def update_completion_config(self) -> Callable[ - [catalog_service.UpdateCompletionConfigRequest], - Awaitable[catalog.CompletionConfig]]: - r"""Return a callable for the update completion config method over gRPC. - - Updates the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig]s. - - Returns: - Callable[[~.UpdateCompletionConfigRequest], - Awaitable[~.CompletionConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_config' not in self._stubs: - self._stubs['update_completion_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateCompletionConfig', - request_serializer=catalog_service.UpdateCompletionConfigRequest.serialize, - response_deserializer=catalog.CompletionConfig.deserialize, - ) - return self._stubs['update_completion_config'] - - @property - def get_attributes_config(self) -> Callable[ - [catalog_service.GetAttributesConfigRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the get attributes config method over gRPC. - - Gets an - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - Returns: - Callable[[~.GetAttributesConfigRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['get_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/GetAttributesConfig', - request_serializer=catalog_service.GetAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['get_attributes_config'] - - @property - def update_attributes_config(self) -> Callable[ - [catalog_service.UpdateAttributesConfigRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the update attributes config method over gRPC. - - Updates the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - The catalog attributes in the request will be updated in the - catalog, or inserted if they do not exist. Existing catalog - attributes not included in the request will remain unchanged. - Attributes that are assigned to products, but do not exist at - the catalog level, are always included in the response. The - product attribute is assigned default values for missing catalog - attribute fields, e.g., searchable and dynamic facetable - options. - - Returns: - Callable[[~.UpdateAttributesConfigRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_attributes_config' not in self._stubs: - self._stubs['update_attributes_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/UpdateAttributesConfig', - request_serializer=catalog_service.UpdateAttributesConfigRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['update_attributes_config'] - - @property - def add_catalog_attribute(self) -> Callable[ - [catalog_service.AddCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the add catalog attribute method over gRPC. - - Adds the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.AddCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_catalog_attribute' not in self._stubs: - self._stubs['add_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/AddCatalogAttribute', - request_serializer=catalog_service.AddCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['add_catalog_attribute'] - - @property - def remove_catalog_attribute(self) -> Callable[ - [catalog_service.RemoveCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the remove catalog attribute method over gRPC. - - Removes the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - from the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.RemoveCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_catalog_attribute' not in self._stubs: - self._stubs['remove_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/RemoveCatalogAttribute', - request_serializer=catalog_service.RemoveCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['remove_catalog_attribute'] - - @property - def replace_catalog_attribute(self) -> Callable[ - [catalog_service.ReplaceCatalogAttributeRequest], - Awaitable[catalog.AttributesConfig]]: - r"""Return a callable for the replace catalog attribute method over gRPC. - - Replaces the specified - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - in the - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - by updating the catalog attribute with the same - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key]. - - If the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to replace does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.ReplaceCatalogAttributeRequest], - Awaitable[~.AttributesConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_catalog_attribute' not in self._stubs: - self._stubs['replace_catalog_attribute'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CatalogService/ReplaceCatalogAttribute', - request_serializer=catalog_service.ReplaceCatalogAttributeRequest.serialize, - response_deserializer=catalog.AttributesConfig.deserialize, - ) - return self._stubs['replace_catalog_attribute'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py deleted file mode 100644 index b8af95bd..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CompletionServiceClient -from .async_client import CompletionServiceAsyncClient - -__all__ = ( - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py deleted file mode 100644 index 66c91320..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/async_client.py +++ /dev/null @@ -1,391 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .client import CompletionServiceClient - - -class CompletionServiceAsyncClient: - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: CompletionServiceClient - - DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(CompletionServiceClient.catalog_path) - parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path) - common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CompletionServiceClient.common_project_path) - parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) - common_location_path = staticmethod(CompletionServiceClient.common_location_path) - parse_common_location_path = staticmethod(CompletionServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CompletionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_complete_query(): - # Create a client - client = retail_v2beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.complete_query, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_import_completion_data(): - # Create a client - client = retail_v2beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2beta.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. - 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. - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_completion_data, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py deleted file mode 100644 index 5766b6b2..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/client.py +++ /dev/null @@ -1,593 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CompletionServiceGrpcTransport -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -class CompletionServiceClientMeta(type): - """Metaclass for the CompletionService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] - _transport_registry["grpc"] = CompletionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CompletionServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class CompletionServiceClient(metaclass=CompletionServiceClientMeta): - """Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CompletionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CompletionServiceTransport): - # transport is a CompletionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def complete_query(self, - request: Union[completion_service.CompleteQueryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_complete_query(): - # Create a client - client = retail_v2beta.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]): - The request object. Auto-complete parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.CompleteQueryResponse: - Response of the auto-complete query. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a completion_service.CompleteQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, completion_service.CompleteQueryRequest): - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("catalog", request.catalog), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_completion_data(self, - request: Union[import_config.ImportCompletionDataRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_import_completion_data(): - # Create a client - client = retail_v2beta.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2beta.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]): - The request object. Request message for - ImportCompletionData methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. - 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. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportCompletionDataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportCompletionDataRequest): - request = import_config.ImportCompletionDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_completion_data] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportCompletionDataResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CompletionServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py deleted file mode 100644 index a0c9542f..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CompletionServiceTransport -from .grpc import CompletionServiceGrpcTransport -from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] -_transport_registry['grpc'] = CompletionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport - -__all__ = ( - 'CompletionServiceTransport', - 'CompletionServiceGrpcTransport', - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py deleted file mode 100644 index 6a5d8425..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/base.py +++ /dev/null @@ -1,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CompletionServiceTransport(abc.ABC): - """Abstract transport class for CompletionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.complete_query: gapic_v1.method.wrap_method( - self.complete_query, - default_timeout=None, - client_info=client_info, - ), - self.import_completion_data: gapic_v1.method.wrap_method( - self.import_completion_data, - 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Union[ - completion_service.CompleteQueryResponse, - Awaitable[completion_service.CompleteQueryResponse] - ]]: - raise NotImplementedError() - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CompletionServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py deleted file mode 100644 index d3ee0929..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc.py +++ /dev/null @@ -1,325 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO - - -class CompletionServiceGrpcTransport(CompletionServiceTransport): - """gRPC backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - ~.CompleteQueryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - operations_pb2.Operation]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CompletionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py deleted file mode 100644 index 56463003..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,324 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CompletionServiceGrpcTransport - - -class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): - """gRPC AsyncIO backend transport for CompletionService. - - Auto-completion service for retail. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Awaitable[completion_service.CompleteQueryResponse]]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified prefix with keyword - suggestions. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.CompleteQueryRequest], - Awaitable[~.CompleteQueryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - @property - def import_completion_data(self) -> Callable[ - [import_config.ImportCompletionDataRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import completion data method over gRPC. - - Bulk import of processed completion dataset. - Request processing is asynchronous. Partial updating is - not supported. - The operation is successfully finished only after the - imported suggestions are indexed successfully and ready - for serving. The process takes hours. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.ImportCompletionDataRequest], - 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_completion_data' not in self._stubs: - self._stubs['import_completion_data'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.CompletionService/ImportCompletionData', - request_serializer=import_config.ImportCompletionDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_completion_data'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py deleted file mode 100644 index e9a7be2f..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ControlServiceClient -from .async_client import ControlServiceAsyncClient - -__all__ = ( - 'ControlServiceClient', - 'ControlServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py deleted file mode 100644 index 5d3cfeb7..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/async_client.py +++ /dev/null @@ -1,742 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.control_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.cloud.retail_v2beta.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport -from .client import ControlServiceClient - - -class ControlServiceAsyncClient: - """Service for modifying Control.""" - - _client: ControlServiceClient - - DEFAULT_ENDPOINT = ControlServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ControlServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(ControlServiceClient.catalog_path) - parse_catalog_path = staticmethod(ControlServiceClient.parse_catalog_path) - control_path = staticmethod(ControlServiceClient.control_path) - parse_control_path = staticmethod(ControlServiceClient.parse_control_path) - common_billing_account_path = staticmethod(ControlServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ControlServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ControlServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ControlServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ControlServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ControlServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ControlServiceClient.common_project_path) - parse_common_project_path = staticmethod(ControlServiceClient.parse_common_project_path) - common_location_path = staticmethod(ControlServiceClient.common_location_path) - parse_common_location_path = staticmethod(ControlServiceClient.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: - ControlServiceAsyncClient: The constructed client. - """ - return ControlServiceClient.from_service_account_info.__func__(ControlServiceAsyncClient, 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: - ControlServiceAsyncClient: The constructed client. - """ - return ControlServiceClient.from_service_account_file.__func__(ControlServiceAsyncClient, 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 variabel 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 ControlServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ControlServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ControlServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ControlServiceClient).get_transport_class, type(ControlServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ControlServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the control service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ControlServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ControlServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_control(self, - request: Union[control_service.CreateControlRequest, dict] = None, - *, - parent: str = None, - control: gcr_control.Control = None, - control_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Creates a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_create_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = await client.create_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateControlRequest, dict]): - The request object. Request for CreateControl method. - parent (:class:`str`): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control (:class:`google.cloud.retail_v2beta.types.Control`): - Required. The Control to create. - This corresponds to the ``control`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control_id (:class:`str`): - Required. The ID to use for the Control, which will - become the final component of the Control's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``control_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.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, control, control_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.CreateControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if control is not None: - request.control = control - if control_id is not None: - request.control_id = control_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_control(self, - request: Union[control_service.DeleteControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_delete_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteControlRequest( - name="name_value", - ) - - # Make the request - await client.delete_control(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteControlRequest, dict]): - The request object. Request for DeleteControl method. - name (:class:`str`): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.DeleteControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_control(self, - request: Union[control_service.UpdateControlRequest, dict] = None, - *, - control: gcr_control.Control = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Updates a Control. - - [Control][google.cloud.retail.v2beta.Control] cannot be set to a - different oneof field, if so an INVALID_ARGUMENT is returned. If - the [Control][google.cloud.retail.v2beta.Control] to delete does - not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateControlRequest( - control=control, - ) - - # Make the request - response = await client.update_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateControlRequest, dict]): - The request object. Request for UpdateControl method. - control (:class:`google.cloud.retail_v2beta.types.Control`): - Required. The Control to update. - This corresponds to the ``control`` 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 - [Control][google.cloud.retail.v2beta.Control] to update. - The following are NOT supported: - - - [Control.name][google.cloud.retail.v2beta.Control.name] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([control, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.UpdateControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if control is not None: - request.control = control - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("control.name", request.control.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_control(self, - request: Union[control_service.GetControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> control.Control: - r"""Gets a Control. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetControlRequest( - name="name_value", - ) - - # Make the request - response = await client.get_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetControlRequest, dict]): - The request object. Request for GetControl method. - name (:class:`str`): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.GetControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_controls(self, - request: Union[control_service.ListControlsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListControlsAsyncPager: - r"""Lists all Controls linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_list_controls(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListControlsRequest, dict]): - The request object. Request for ListControls method. - parent (:class:`str`): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.control_service.pagers.ListControlsAsyncPager: - Response for ListControls method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = control_service.ListControlsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_controls, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListControlsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ControlServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py deleted file mode 100644 index fbad615b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/client.py +++ /dev/null @@ -1,951 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.control_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.cloud.retail_v2beta.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ControlServiceGrpcTransport -from .transports.grpc_asyncio import ControlServiceGrpcAsyncIOTransport - - -class ControlServiceClientMeta(type): - """Metaclass for the ControlService 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[ControlServiceTransport]] - _transport_registry["grpc"] = ControlServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ControlServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ControlServiceTransport]: - """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 ControlServiceClient(metaclass=ControlServiceClientMeta): - """Service for modifying Control.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ControlServiceClient: 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: - ControlServiceClient: 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) -> ControlServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ControlServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def control_path(project: str,location: str,catalog: str,control: str,) -> str: - """Returns a fully-qualified control string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) - - @staticmethod - def parse_control_path(path: str) -> Dict[str,str]: - """Parses a control path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/controls/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ControlServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the control service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ControlServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ControlServiceTransport): - # transport is a ControlServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_control(self, - request: Union[control_service.CreateControlRequest, dict] = None, - *, - parent: str = None, - control: gcr_control.Control = None, - control_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Creates a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_create_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = client.create_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateControlRequest, dict]): - The request object. Request for CreateControl method. - parent (str): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control (google.cloud.retail_v2beta.types.Control): - Required. The Control to create. - This corresponds to the ``control`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - control_id (str): - Required. The ID to use for the Control, which will - become the final component of the Control's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``control_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.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, control, control_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.CreateControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.CreateControlRequest): - request = control_service.CreateControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if control is not None: - request.control = control - if control_id is not None: - request.control_id = control_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_control(self, - request: Union[control_service.DeleteControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to delete - does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_delete_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteControlRequest( - name="name_value", - ) - - # Make the request - client.delete_control(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteControlRequest, dict]): - The request object. Request for DeleteControl method. - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.DeleteControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.DeleteControlRequest): - request = control_service.DeleteControlRequest(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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_control(self, - request: Union[control_service.UpdateControlRequest, dict] = None, - *, - control: gcr_control.Control = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_control.Control: - r"""Updates a Control. - - [Control][google.cloud.retail.v2beta.Control] cannot be set to a - different oneof field, if so an INVALID_ARGUMENT is returned. If - the [Control][google.cloud.retail.v2beta.Control] to delete does - not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateControlRequest( - control=control, - ) - - # Make the request - response = client.update_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateControlRequest, dict]): - The request object. Request for UpdateControl method. - control (google.cloud.retail_v2beta.types.Control): - Required. The Control to update. - This corresponds to the ``control`` 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 - [Control][google.cloud.retail.v2beta.Control] to update. - The following are NOT supported: - - - [Control.name][google.cloud.retail.v2beta.Control.name] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([control, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.UpdateControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.UpdateControlRequest): - request = control_service.UpdateControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if control is not None: - request.control = control - 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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("control.name", request.control.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_control(self, - request: Union[control_service.GetControlRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> control.Control: - r"""Gets a Control. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetControlRequest( - name="name_value", - ) - - # Make the request - response = client.get_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetControlRequest, dict]): - The request object. Request for GetControl method. - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Control: - Configures dynamic serving time - metadata that is used to pre and post - process search/recommendation model - results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.GetControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.GetControlRequest): - request = control_service.GetControlRequest(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_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_controls(self, - request: Union[control_service.ListControlsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListControlsPager: - r"""Lists all Controls linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_list_controls(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListControlsRequest, dict]): - The request object. Request for ListControls method. - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.control_service.pagers.ListControlsPager: - Response for ListControls method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a control_service.ListControlsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, control_service.ListControlsRequest): - request = control_service.ListControlsRequest(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_controls] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListControlsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ControlServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py deleted file mode 100644 index f51a3970..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control_service - - -class ListControlsPager: - """A pager for iterating through ``list_controls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListControlsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``controls`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListControls`` requests and continue to iterate - through the ``controls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListControlsResponse` - 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[..., control_service.ListControlsResponse], - request: control_service.ListControlsRequest, - response: control_service.ListControlsResponse, - *, - 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.retail_v2beta.types.ListControlsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListControlsResponse): - 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 = control_service.ListControlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[control_service.ListControlsResponse]: - 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[control.Control]: - for page in self.pages: - yield from page.controls - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListControlsAsyncPager: - """A pager for iterating through ``list_controls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListControlsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``controls`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListControls`` requests and continue to iterate - through the ``controls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListControlsResponse` - 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[control_service.ListControlsResponse]], - request: control_service.ListControlsRequest, - response: control_service.ListControlsResponse, - *, - 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.retail_v2beta.types.ListControlsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListControlsResponse): - 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 = control_service.ListControlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[control_service.ListControlsResponse]: - 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[control.Control]: - async def async_generator(): - async for page in self.pages: - for response in page.controls: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py deleted file mode 100644 index 3622876b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ControlServiceTransport -from .grpc import ControlServiceGrpcTransport -from .grpc_asyncio import ControlServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ControlServiceTransport]] -_transport_registry['grpc'] = ControlServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ControlServiceGrpcAsyncIOTransport - -__all__ = ( - 'ControlServiceTransport', - 'ControlServiceGrpcTransport', - 'ControlServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py deleted file mode 100644 index 2424eb4a..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/base.py +++ /dev/null @@ -1,213 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ControlServiceTransport(abc.ABC): - """Abstract transport class for ControlService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_control: gapic_v1.method.wrap_method( - self.create_control, - default_timeout=None, - client_info=client_info, - ), - self.delete_control: gapic_v1.method.wrap_method( - self.delete_control, - default_timeout=None, - client_info=client_info, - ), - self.update_control: gapic_v1.method.wrap_method( - self.update_control, - default_timeout=None, - client_info=client_info, - ), - self.get_control: gapic_v1.method.wrap_method( - self.get_control, - default_timeout=None, - client_info=client_info, - ), - self.list_controls: gapic_v1.method.wrap_method( - self.list_controls, - 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 create_control(self) -> Callable[ - [control_service.CreateControlRequest], - Union[ - gcr_control.Control, - Awaitable[gcr_control.Control] - ]]: - raise NotImplementedError() - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - Union[ - gcr_control.Control, - Awaitable[gcr_control.Control] - ]]: - raise NotImplementedError() - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - Union[ - control.Control, - Awaitable[control.Control] - ]]: - raise NotImplementedError() - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - Union[ - control_service.ListControlsResponse, - Awaitable[control_service.ListControlsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ControlServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py deleted file mode 100644 index 64b13dfb..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc.py +++ /dev/null @@ -1,382 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO - - -class ControlServiceGrpcTransport(ControlServiceTransport): - """gRPC backend transport for ControlService. - - Service for modifying Control. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_control(self) -> Callable[ - [control_service.CreateControlRequest], - gcr_control.Control]: - r"""Return a callable for the create control method over gRPC. - - Creates a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['create_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/CreateControl', - request_serializer=control_service.CreateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['create_control'] - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete control method over gRPC. - - Deletes a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteControlRequest], - ~.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_control' not in self._stubs: - self._stubs['delete_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/DeleteControl', - request_serializer=control_service.DeleteControlRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_control'] - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - gcr_control.Control]: - r"""Return a callable for the update control method over gRPC. - - Updates a Control. - - [Control][google.cloud.retail.v2beta.Control] cannot be set to a - different oneof field, if so an INVALID_ARGUMENT is returned. If - the [Control][google.cloud.retail.v2beta.Control] to delete does - not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.UpdateControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['update_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/UpdateControl', - request_serializer=control_service.UpdateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['update_control'] - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - control.Control]: - r"""Return a callable for the get control method over gRPC. - - Gets a Control. - - Returns: - Callable[[~.GetControlRequest], - ~.Control]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['get_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/GetControl', - request_serializer=control_service.GetControlRequest.serialize, - response_deserializer=control.Control.deserialize, - ) - return self._stubs['get_control'] - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - control_service.ListControlsResponse]: - r"""Return a callable for the list controls method over gRPC. - - Lists all Controls linked to this catalog. - - Returns: - Callable[[~.ListControlsRequest], - ~.ListControlsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_controls' not in self._stubs: - self._stubs['list_controls'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/ListControls', - request_serializer=control_service.ListControlsRequest.serialize, - response_deserializer=control_service.ListControlsResponse.deserialize, - ) - return self._stubs['list_controls'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ControlServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py deleted file mode 100644 index 701a8de1..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,381 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ControlServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ControlServiceGrpcTransport - - -class ControlServiceGrpcAsyncIOTransport(ControlServiceTransport): - """gRPC AsyncIO backend transport for ControlService. - - Service for modifying Control. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_control(self) -> Callable[ - [control_service.CreateControlRequest], - Awaitable[gcr_control.Control]]: - r"""Return a callable for the create control method over gRPC. - - Creates a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to create - already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['create_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/CreateControl', - request_serializer=control_service.CreateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['create_control'] - - @property - def delete_control(self) -> Callable[ - [control_service.DeleteControlRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete control method over gRPC. - - Deletes a Control. - - If the [Control][google.cloud.retail.v2beta.Control] to delete - does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteControlRequest], - 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_control' not in self._stubs: - self._stubs['delete_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/DeleteControl', - request_serializer=control_service.DeleteControlRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_control'] - - @property - def update_control(self) -> Callable[ - [control_service.UpdateControlRequest], - Awaitable[gcr_control.Control]]: - r"""Return a callable for the update control method over gRPC. - - Updates a Control. - - [Control][google.cloud.retail.v2beta.Control] cannot be set to a - different oneof field, if so an INVALID_ARGUMENT is returned. If - the [Control][google.cloud.retail.v2beta.Control] to delete does - not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.UpdateControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['update_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/UpdateControl', - request_serializer=control_service.UpdateControlRequest.serialize, - response_deserializer=gcr_control.Control.deserialize, - ) - return self._stubs['update_control'] - - @property - def get_control(self) -> Callable[ - [control_service.GetControlRequest], - Awaitable[control.Control]]: - r"""Return a callable for the get control method over gRPC. - - Gets a Control. - - Returns: - Callable[[~.GetControlRequest], - Awaitable[~.Control]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_control' not in self._stubs: - self._stubs['get_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/GetControl', - request_serializer=control_service.GetControlRequest.serialize, - response_deserializer=control.Control.deserialize, - ) - return self._stubs['get_control'] - - @property - def list_controls(self) -> Callable[ - [control_service.ListControlsRequest], - Awaitable[control_service.ListControlsResponse]]: - r"""Return a callable for the list controls method over gRPC. - - Lists all Controls linked to this catalog. - - Returns: - Callable[[~.ListControlsRequest], - Awaitable[~.ListControlsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_controls' not in self._stubs: - self._stubs['list_controls'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ControlService/ListControls', - request_serializer=control_service.ListControlsRequest.serialize, - response_deserializer=control_service.ListControlsResponse.deserialize, - ) - return self._stubs['list_controls'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ControlServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py deleted file mode 100644 index 7c079c80..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import PredictionServiceClient -from .async_client import PredictionServiceAsyncClient - -__all__ = ( - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py deleted file mode 100644 index d8a1a148..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/async_client.py +++ /dev/null @@ -1,279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport -from .client import PredictionServiceClient - - -class PredictionServiceAsyncClient: - """Service for making recommendation prediction.""" - - _client: PredictionServiceClient - - DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT - - product_path = staticmethod(PredictionServiceClient.product_path) - parse_product_path = staticmethod(PredictionServiceClient.parse_product_path) - common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(PredictionServiceClient.common_project_path) - parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) - common_location_path = staticmethod(PredictionServiceClient.common_location_path) - parse_common_location_path = staticmethod(PredictionServiceClient.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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, 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 variabel 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 PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PredictionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_predict(): - # Create a client - client = retail_v2beta.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - request = prediction_service.PredictRequest(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.predict, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py deleted file mode 100644 index 6eb343ca..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/client.py +++ /dev/null @@ -1,480 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PredictionServiceGrpcTransport -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -class PredictionServiceClientMeta(type): - """Metaclass for the PredictionService 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[PredictionServiceTransport]] - _transport_registry["grpc"] = PredictionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PredictionServiceTransport]: - """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): - """Service for making recommendation prediction.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PredictionServiceClient: 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: - PredictionServiceClient: 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) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, PredictionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, PredictionServiceTransport): - # transport is a PredictionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def predict(self, - request: Union[prediction_service.PredictRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_service.PredictResponse: - r"""Makes a recommendation prediction. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_predict(): - # Create a client - client = retail_v2beta.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.PredictRequest, dict]): - The request object. Request message for Predict method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.PredictResponse: - Response message for predict method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a prediction_service.PredictRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_service.PredictRequest): - request = prediction_service.PredictRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.predict] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py deleted file mode 100644 index bb65c664..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PredictionServiceTransport -from .grpc import PredictionServiceGrpcTransport -from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] -_transport_registry['grpc'] = PredictionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport - -__all__ = ( - 'PredictionServiceTransport', - 'PredictionServiceGrpcTransport', - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py deleted file mode 100644 index 12f65a6c..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PredictionServiceTransport(abc.ABC): - """Abstract transport class for PredictionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.predict: gapic_v1.method.wrap_method( - self.predict, - 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - Union[ - prediction_service.PredictResponse, - Awaitable[prediction_service.PredictResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PredictionServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py deleted file mode 100644 index 98c69839..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc.py +++ /dev/null @@ -1,264 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO - - -class PredictionServiceGrpcTransport(PredictionServiceTransport): - """gRPC backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 predict(self) -> Callable[ - [prediction_service.PredictRequest], - prediction_service.PredictResponse]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - ~.PredictResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PredictionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py deleted file mode 100644 index 11fce51c..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import PredictionServiceGrpcTransport - - -class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): - """gRPC AsyncIO backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def predict(self) -> Callable[ - [prediction_service.PredictRequest], - Awaitable[prediction_service.PredictResponse]]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. - - Returns: - Callable[[~.PredictRequest], - Awaitable[~.PredictResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py deleted file mode 100644 index 0fa6330a..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ProductServiceClient -from .async_client import ProductServiceAsyncClient - -__all__ = ( - 'ProductServiceClient', - 'ProductServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py deleted file mode 100644 index 493936e0..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/async_client.py +++ /dev/null @@ -1,1692 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.services.product_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.cloud.retail_v2beta.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport -from .client import ProductServiceClient - - -class ProductServiceAsyncClient: - """Service for ingesting [Product][google.cloud.retail.v2beta.Product] - information of the customer's website. - """ - - _client: ProductServiceClient - - DEFAULT_ENDPOINT = ProductServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProductServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(ProductServiceClient.branch_path) - parse_branch_path = staticmethod(ProductServiceClient.parse_branch_path) - product_path = staticmethod(ProductServiceClient.product_path) - parse_product_path = staticmethod(ProductServiceClient.parse_product_path) - common_billing_account_path = staticmethod(ProductServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProductServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProductServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProductServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProductServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProductServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ProductServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProductServiceClient.parse_common_project_path) - common_location_path = staticmethod(ProductServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProductServiceClient.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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_info.__func__(ProductServiceAsyncClient, 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: - ProductServiceAsyncClient: The constructed client. - """ - return ProductServiceClient.from_service_account_file.__func__(ProductServiceAsyncClient, 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 variabel 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 ProductServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ProductServiceClient).get_transport_class, type(ProductServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ProductServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ProductServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_create_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (:class:`str`): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (:class:`google.cloud.retail_v2beta.types.Product`): - Required. The - [Product][google.cloud.retail.v2beta.Product] to create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (:class:`str`): - Required. The ID to use for the - [Product][google.cloud.retail.v2beta.Product], which - will become the final component of the - [Product.name][google.cloud.retail.v2beta.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This field must be unique among all - [Product][google.cloud.retail.v2beta.Product]s with the - same - [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.CreateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the requested - [Product][google.cloud.retail.v2beta.Product] 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.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.GetProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsAsyncPager: - r"""Gets a list of [Product][google.cloud.retail.v2beta.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_list_products(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - parent (:class:`str`): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2beta.Product]s under - this branch, regardless of whether or not this branch - exists, a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.product_service.pagers.ListProductsAsyncPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.ListProductsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_products, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListProductsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (:class:`google.cloud.retail_v2beta.types.Product`): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2beta.Product] to update. - The immutable and output only fields are NOT supported. - If not set, all supported fields (the fields that are - neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.UpdateProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_delete_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2beta.Product] to - delete can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product] member nor - a - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] with more - than one - [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2beta.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.DeleteProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_product, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2beta.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2beta.Product]s to be - successfully updated. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_import_products(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2beta.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2beta.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_set_inventory(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2beta.Product() - inventory.title = "title_value" - - request = retail_v2beta.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (:class:`google.cloud.retail_v2beta.types.Product`): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product] named in - [Product.name][google.cloud.retail.v2beta.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2beta.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2beta.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.SetInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_inventory, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - async def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [AddFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveFulfillmentPlacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_fulfillment_places, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - async def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_add_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [AddLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.AddLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_remove_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (:class:`str`): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = product_service.RemoveLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_local_inventories, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py deleted file mode 100644 index fa4ba1f6..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/client.py +++ /dev/null @@ -1,1895 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.services.product_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.cloud.retail_v2beta.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProductServiceGrpcTransport -from .transports.grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -class ProductServiceClientMeta(type): - """Metaclass for the ProductService 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[ProductServiceTransport]] - _transport_registry["grpc"] = ProductServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ProductServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ProductServiceTransport]: - """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 ProductServiceClient(metaclass=ProductServiceClientMeta): - """Service for ingesting [Product][google.cloud.retail.v2beta.Product] - information of the customer's website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProductServiceClient: 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: - ProductServiceClient: 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) -> ProductServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProductServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ProductServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ProductServiceTransport): - # transport is a ProductServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_product(self, - request: Union[product_service.CreateProductRequest, dict] = None, - *, - parent: str = None, - product: gcr_product.Product = None, - product_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Creates a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_create_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateProductRequest, dict]): - The request object. Request message for - [CreateProduct][] method. - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product (google.cloud.retail_v2beta.types.Product): - Required. The - [Product][google.cloud.retail.v2beta.Product] to create. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2beta.Product], which - will become the final component of the - [Product.name][google.cloud.retail.v2beta.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This field must be unique among all - [Product][google.cloud.retail.v2beta.Product]s with the - same - [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This corresponds to the ``product_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.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, product, product_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.CreateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.CreateProductRequest): - request = product_service.CreateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if product is not None: - request.product = product - if product_id is not None: - request.product_id = product_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_product(self, - request: Union[product_service.GetProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> product.Product: - r"""Gets a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetProductRequest, dict]): - The request object. Request message for [GetProduct][] - method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the requested - [Product][google.cloud.retail.v2beta.Product] 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.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.GetProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.GetProductRequest): - request = product_service.GetProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_products(self, - request: Union[product_service.ListProductsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsPager: - r"""Gets a list of [Product][google.cloud.retail.v2beta.Product]s. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_list_products(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListProductsRequest, dict]): - The request object. Request message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list - products under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2beta.Product]s under - this branch, regardless of whether or not this branch - exists, a PERMISSION_DENIED error is returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.product_service.pagers.ListProductsPager: - Response message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.ListProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.ListProductsRequest): - request = product_service.ListProductsRequest(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_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListProductsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_product(self, - request: Union[product_service.UpdateProductRequest, dict] = None, - *, - product: gcr_product.Product = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_product.Product: - r"""Updates a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateProductRequest, dict]): - The request object. Request message for - [UpdateProduct][] method. - product (google.cloud.retail_v2beta.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - - This corresponds to the ``product`` 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 - [Product][google.cloud.retail.v2beta.Product] to update. - The immutable and output only fields are NOT supported. - If not set, all supported fields (the fields that are - neither immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.Product: - Product captures all metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.UpdateProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.UpdateProductRequest): - request = product_service.UpdateProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - 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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product.name", request.product.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_product(self, - request: Union[product_service.DeleteProductRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Product][google.cloud.retail.v2beta.Product]. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_delete_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteProductRequest, dict]): - The request object. Request message for - [DeleteProduct][] method. - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2beta.Product] to - delete can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product] member nor - a - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] with more - than one - [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2beta.Product] will be - deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.DeleteProductRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.DeleteProductRequest): - request = product_service.DeleteProductRequest(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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def import_products(self, - request: Union[import_config.ImportProductsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple - [Product][google.cloud.retail.v2beta.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2beta.Product]s to be - successfully updated. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_import_products(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2beta.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportProductsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportProductsResponse` Response of the - [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportProductsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportProductsRequest): - request = import_config.ImportProductsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportProductsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def set_inventory(self, - request: Union[product_service.SetInventoryRequest, dict] = None, - *, - inventory: product.Product = None, - set_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates inventory information for a - [Product][google.cloud.retail.v2beta.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_set_inventory(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2beta.Product() - inventory.title = "title_value" - - request = retail_v2beta.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.SetInventoryRequest, dict]): - The request object. Request message for [SetInventory][] - method. - inventory (google.cloud.retail_v2beta.types.Product): - Required. The inventory information to update. The - allowable fields to update are: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product] named in - [Product.name][google.cloud.retail.v2beta.Product.name], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2beta.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting - the last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear - in [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types - have empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following - inventory fields: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - - If a full overwrite of inventory information while - ignoring timestamps is needed, [UpdateProduct][] should - be invoked instead. - - This corresponds to the ``inventory`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2beta.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - - This corresponds to the ``set_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.SetInventoryResponse` Response of the SetInventoryRequest. Currently empty because - there is no meaningful response populated from the - [SetInventory][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([inventory, set_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.SetInventoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.SetInventoryRequest): - request = product_service.SetInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if inventory is not None: - request.inventory = inventory - if set_mask is not None: - request.set_mask = set_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("inventory.name", request.inventory.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - product_service.SetInventoryResponse, - metadata_type=product_service.SetInventoryMetadata, - ) - - # Done; return the response. - return response - - def add_fulfillment_places(self, - request: Union[product_service.AddFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_add_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest, dict]): - The request object. Request message for - [AddFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.AddFulfillmentPlacesResponse` Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddFulfillmentPlacesRequest): - request = product_service.AddFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddFulfillmentPlacesResponse, - metadata_type=product_service.AddFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def remove_fulfillment_places(self, - request: Union[product_service.RemoveFulfillmentPlacesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest, dict]): - The request object. Request message for - [RemoveFulfillmentPlaces][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RemoveFulfillmentPlacesResponse` Response of the RemoveFulfillmentPlacesRequest. Currently empty because there - is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveFulfillmentPlacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveFulfillmentPlacesRequest): - request = product_service.RemoveFulfillmentPlacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_fulfillment_places] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveFulfillmentPlacesResponse, - metadata_type=product_service.RemoveFulfillmentPlacesMetadata, - ) - - # Done; return the response. - return response - - def add_local_inventories(self, - request: Union[product_service.AddLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_add_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddLocalInventoriesRequest, dict]): - The request object. Request message for - [AddLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.AddLocalInventoriesResponse` Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.AddLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.AddLocalInventoriesRequest): - request = product_service.AddLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.AddLocalInventoriesResponse, - metadata_type=product_service.AddLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def remove_local_inventories(self, - request: Union[product_service.RemoveLocalInventoriesRequest, dict] = None, - *, - product: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Remove local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_remove_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest, dict]): - The request object. Request message for - [RemoveLocalInventories][] method. - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], - regardless of whether or not it exists, a - PERMISSION_DENIED error is returned. - - This corresponds to the ``product`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RemoveLocalInventoriesResponse` Response of the [RemoveLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([product]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a product_service.RemoveLocalInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, product_service.RemoveLocalInventoriesRequest): - request = product_service.RemoveLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if product is not None: - request.product = product - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("product", request.product), - )), - ) - - # 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, - product_service.RemoveLocalInventoriesResponse, - metadata_type=product_service.RemoveLocalInventoriesMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ProductServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py deleted file mode 100644 index 552c2bfa..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product_service - - -class ListProductsPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListProductsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListProductsResponse` - 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[..., product_service.ListProductsResponse], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2beta.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[product_service.ListProductsResponse]: - 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[product.Product]: - for page in self.pages: - yield from page.products - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProductsAsyncPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListProductsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListProductsResponse` - 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[product_service.ListProductsResponse]], - request: product_service.ListProductsRequest, - response: product_service.ListProductsResponse, - *, - 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.retail_v2beta.types.ListProductsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListProductsResponse): - 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 = product_service.ListProductsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[product_service.ListProductsResponse]: - 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[product.Product]: - async def async_generator(): - async for page in self.pages: - for response in page.products: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py deleted file mode 100644 index db824dec..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ProductServiceTransport -from .grpc import ProductServiceGrpcTransport -from .grpc_asyncio import ProductServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProductServiceTransport]] -_transport_registry['grpc'] = ProductServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProductServiceGrpcAsyncIOTransport - -__all__ = ( - 'ProductServiceTransport', - 'ProductServiceGrpcTransport', - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py deleted file mode 100644 index 325ba99e..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/base.py +++ /dev/null @@ -1,312 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ProductServiceTransport(abc.ABC): - """Abstract transport class for ProductService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_product: gapic_v1.method.wrap_method( - self.create_product, - default_timeout=None, - client_info=client_info, - ), - self.get_product: gapic_v1.method.wrap_method( - self.get_product, - default_timeout=None, - client_info=client_info, - ), - self.list_products: gapic_v1.method.wrap_method( - self.list_products, - default_timeout=None, - client_info=client_info, - ), - self.update_product: gapic_v1.method.wrap_method( - self.update_product, - default_timeout=None, - client_info=client_info, - ), - self.delete_product: gapic_v1.method.wrap_method( - self.delete_product, - default_timeout=None, - client_info=client_info, - ), - self.import_products: gapic_v1.method.wrap_method( - self.import_products, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.set_inventory: gapic_v1.method.wrap_method( - self.set_inventory, - default_timeout=None, - client_info=client_info, - ), - self.add_fulfillment_places: gapic_v1.method.wrap_method( - self.add_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.remove_fulfillment_places: gapic_v1.method.wrap_method( - self.remove_fulfillment_places, - default_timeout=None, - client_info=client_info, - ), - self.add_local_inventories: gapic_v1.method.wrap_method( - self.add_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.remove_local_inventories: gapic_v1.method.wrap_method( - self.remove_local_inventories, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Union[ - product.Product, - Awaitable[product.Product] - ]]: - raise NotImplementedError() - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Union[ - product_service.ListProductsResponse, - Awaitable[product_service.ListProductsResponse] - ]]: - raise NotImplementedError() - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Union[ - gcr_product.Product, - Awaitable[gcr_product.Product] - ]]: - raise NotImplementedError() - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ProductServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py deleted file mode 100644 index 8df65e63..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc.py +++ /dev/null @@ -1,680 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO - - -class ProductServiceGrpcTransport(ProductServiceTransport): - """gRPC backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2beta.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - gcr_product.Product]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.CreateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - product.Product]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.GetProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - product_service.ListProductsResponse]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2beta.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - ~.ListProductsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - gcr_product.Product]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - ~.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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2beta.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2beta.Product]s to be - successfully updated. - - Returns: - Callable[[~.ImportProductsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - operations_pb2.Operation]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2beta.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - operations_pb2.Operation]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProductServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py deleted file mode 100644 index 9ccfc3ee..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,679 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ProductServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ProductServiceGrpcTransport - - -class ProductServiceGrpcAsyncIOTransport(ProductServiceTransport): - """gRPC AsyncIO backend transport for ProductService. - - Service for ingesting [Product][google.cloud.retail.v2beta.Product] - information of the customer's website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_product(self) -> Callable[ - [product_service.CreateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the create product method over gRPC. - - Creates a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.CreateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['create_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/CreateProduct', - request_serializer=product_service.CreateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['create_product'] - - @property - def get_product(self) -> Callable[ - [product_service.GetProductRequest], - Awaitable[product.Product]]: - r"""Return a callable for the get product method over gRPC. - - Gets a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.GetProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/GetProduct', - request_serializer=product_service.GetProductRequest.serialize, - response_deserializer=product.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [product_service.ListProductsRequest], - Awaitable[product_service.ListProductsResponse]]: - r"""Return a callable for the list products method over gRPC. - - Gets a list of [Product][google.cloud.retail.v2beta.Product]s. - - Returns: - Callable[[~.ListProductsRequest], - Awaitable[~.ListProductsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/ListProducts', - request_serializer=product_service.ListProductsRequest.serialize, - response_deserializer=product_service.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - @property - def update_product(self) -> Callable[ - [product_service.UpdateProductRequest], - Awaitable[gcr_product.Product]]: - r"""Return a callable for the update product method over gRPC. - - Updates a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.UpdateProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['update_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/UpdateProduct', - request_serializer=product_service.UpdateProductRequest.serialize, - response_deserializer=gcr_product.Product.deserialize, - ) - return self._stubs['update_product'] - - @property - def delete_product(self) -> Callable[ - [product_service.DeleteProductRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete product method over gRPC. - - Deletes a [Product][google.cloud.retail.v2beta.Product]. - - Returns: - Callable[[~.DeleteProductRequest], - 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_product' not in self._stubs: - self._stubs['delete_product'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/DeleteProduct', - request_serializer=product_service.DeleteProductRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product'] - - @property - def import_products(self) -> Callable[ - [import_config.ImportProductsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import products method over gRPC. - - Bulk import of multiple - [Product][google.cloud.retail.v2beta.Product]s. - - Request processing may be synchronous. No partial updating is - supported. Non-existing items are created. - - Note that it is possible for a subset of the - [Product][google.cloud.retail.v2beta.Product]s to be - successfully updated. - - Returns: - Callable[[~.ImportProductsRequest], - 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_products' not in self._stubs: - self._stubs['import_products'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/ImportProducts', - request_serializer=import_config.ImportProductsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_products'] - - @property - def set_inventory(self) -> Callable[ - [product_service.SetInventoryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set inventory method over gRPC. - - Updates inventory information for a - [Product][google.cloud.retail.v2beta.Product] while respecting - the last update timestamps of each inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - When inventory is updated with - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct], - the specified inventory field value(s) will overwrite any - existing value(s) while ignoring the last update time for this - field. Furthermore, the last update time for the specified - inventory fields will be overwritten to the time of the - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - or - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - request. - - If no inventory fields are set in - [CreateProductRequest.product][google.cloud.retail.v2beta.CreateProductRequest.product], - then any pre-existing inventory information for this product - will be used. - - If no inventory fields are set in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask], - then any existing inventory information will be preserved. - - Pre-existing inventory information can only be updated with - [SetInventory][google.cloud.retail.v2beta.ProductService.SetInventory], - [AddFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces], - and - [RemoveFulfillmentPlaces][google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.SetInventoryRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_inventory' not in self._stubs: - self._stubs['set_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/SetInventory', - request_serializer=product_service.SetInventoryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_inventory'] - - @property - def add_fulfillment_places(self) -> Callable[ - [product_service.AddFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add fulfillment places method over gRPC. - - Incrementally adds place IDs to - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the added place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddFulfillmentPlacesRequest], - 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 'add_fulfillment_places' not in self._stubs: - self._stubs['add_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/AddFulfillmentPlaces', - request_serializer=product_service.AddFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_fulfillment_places'] - - @property - def remove_fulfillment_places(self) -> Callable[ - [product_service.RemoveFulfillmentPlacesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove fulfillment places method over gRPC. - - Incrementally removes place IDs from a - [Product.fulfillment_info.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids]. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating fulfillment information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, the removed place IDs - are not immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveFulfillmentPlacesRequest], - 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 'remove_fulfillment_places' not in self._stubs: - self._stubs['remove_fulfillment_places'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/RemoveFulfillmentPlaces', - request_serializer=product_service.RemoveFulfillmentPlacesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_fulfillment_places'] - - @property - def add_local_inventories(self) -> Callable[ - [product_service.AddLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the add local inventories method over gRPC. - - Updates local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places, while respecting the last update timestamps of each - inventory field. - - This process is asynchronous and does not require the - [Product][google.cloud.retail.v2beta.Product] to exist before - updating inventory information. If the request is valid, the - update will be enqueued and processed downstream. As a - consequence, when a response is returned, updates are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be modified using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.AddLocalInventoriesRequest], - 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 'add_local_inventories' not in self._stubs: - self._stubs['add_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/AddLocalInventories', - request_serializer=product_service.AddLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['add_local_inventories'] - - @property - def remove_local_inventories(self) -> Callable[ - [product_service.RemoveLocalInventoriesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the remove local inventories method over gRPC. - - Remove local inventory information for a - [Product][google.cloud.retail.v2beta.Product] at a list of - places at a removal timestamp. - - This process is asynchronous. If the request is valid, the - removal will be enqueued and processed downstream. As a - consequence, when a response is returned, removals are not - immediately manifested in the - [Product][google.cloud.retail.v2beta.Product] queried by - [GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - or - [ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - Local inventory information can only be removed using this - method. - [CreateProduct][google.cloud.retail.v2beta.ProductService.CreateProduct] - and - [UpdateProduct][google.cloud.retail.v2beta.ProductService.UpdateProduct] - has no effect on local inventories. - - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - Returns: - Callable[[~.RemoveLocalInventoriesRequest], - 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 'remove_local_inventories' not in self._stubs: - self._stubs['remove_local_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ProductService/RemoveLocalInventories', - request_serializer=product_service.RemoveLocalInventoriesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['remove_local_inventories'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ProductServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py deleted file mode 100644 index 2f63fc22..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SearchServiceClient -from .async_client import SearchServiceAsyncClient - -__all__ = ( - 'SearchServiceClient', - 'SearchServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py deleted file mode 100644 index 4943cff9..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/async_client.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.search_service import pagers -from google.cloud.retail_v2beta.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .client import SearchServiceClient - - -class SearchServiceAsyncClient: - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - _client: SearchServiceClient - - DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(SearchServiceClient.branch_path) - parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) - product_path = staticmethod(SearchServiceClient.product_path) - parse_product_path = staticmethod(SearchServiceClient.parse_product_path) - common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(SearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(SearchServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SearchServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAsyncPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_search(): - # Create a client - client = retail_v2beta.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.search_service.pagers.SearchAsyncPager: - Response message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py deleted file mode 100644 index 7c944320..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/client.py +++ /dev/null @@ -1,513 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.search_service import pagers -from google.cloud.retail_v2beta.types import search_service -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SearchServiceGrpcTransport -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -class SearchServiceClientMeta(type): - """Metaclass for the SearchService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] - _transport_registry["grpc"] = SearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SearchServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SearchServiceClient(metaclass=SearchServiceClientMeta): - """Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,catalog: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SearchServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SearchServiceTransport): - # transport is a SearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def search(self, - request: Union[search_service.SearchRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchPager: - r"""Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_search(): - # Create a client - client = retail_v2beta.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.search_service.pagers.SearchPager: - Response message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a search_service.SearchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, search_service.SearchRequest): - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("placement", request.placement), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SearchServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py deleted file mode 100644 index 6ff03162..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import search_service - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., search_service.SearchResponse], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2beta.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.SearchResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[search_service.SearchResponse]], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.retail_v2beta.types.SearchRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py deleted file mode 100644 index 7917cd1d..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SearchServiceTransport -from .grpc import SearchServiceGrpcTransport -from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] -_transport_registry['grpc'] = SearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport - -__all__ = ( - 'SearchServiceTransport', - 'SearchServiceGrpcTransport', - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py deleted file mode 100644 index c084a7f1..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import search_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class SearchServiceTransport(abc.ABC): - """Abstract transport class for SearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search: gapic_v1.method.wrap_method( - self.search, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Union[ - search_service.SearchResponse, - Awaitable[search_service.SearchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SearchServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py deleted file mode 100644 index 74a10421..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc.py +++ /dev/null @@ -1,270 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO - - -class SearchServiceGrpcTransport(SearchServiceTransport): - """gRPC backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py deleted file mode 100644 index 3dfd4aa1..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import search_service -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SearchServiceGrpcTransport - - -class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): - """gRPC AsyncIO backend transport for SearchService. - - Service for search. - This feature is only available for users who have Retail Search - enabled. Please enable Retail Search on Cloud Console before - using this feature. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Awaitable[search_service.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - This feature is only available for users who have Retail - Search enabled. Please enable Retail Search on Cloud - Console before using this feature. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py deleted file mode 100644 index d1a0a023..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ServingConfigServiceClient -from .async_client import ServingConfigServiceAsyncClient - -__all__ = ( - 'ServingConfigServiceClient', - 'ServingConfigServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py deleted file mode 100644 index cfdace1d..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/async_client.py +++ /dev/null @@ -1,954 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.serving_config_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport -from .client import ServingConfigServiceClient - - -class ServingConfigServiceAsyncClient: - """Service for modifying ServingConfig.""" - - _client: ServingConfigServiceClient - - DEFAULT_ENDPOINT = ServingConfigServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ServingConfigServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(ServingConfigServiceClient.catalog_path) - parse_catalog_path = staticmethod(ServingConfigServiceClient.parse_catalog_path) - serving_config_path = staticmethod(ServingConfigServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(ServingConfigServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(ServingConfigServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ServingConfigServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ServingConfigServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ServingConfigServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ServingConfigServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ServingConfigServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ServingConfigServiceClient.common_project_path) - parse_common_project_path = staticmethod(ServingConfigServiceClient.parse_common_project_path) - common_location_path = staticmethod(ServingConfigServiceClient.common_location_path) - parse_common_location_path = staticmethod(ServingConfigServiceClient.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: - ServingConfigServiceAsyncClient: The constructed client. - """ - return ServingConfigServiceClient.from_service_account_info.__func__(ServingConfigServiceAsyncClient, 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: - ServingConfigServiceAsyncClient: The constructed client. - """ - return ServingConfigServiceClient.from_service_account_file.__func__(ServingConfigServiceAsyncClient, 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 variabel 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 ServingConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ServingConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ServingConfigServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ServingConfigServiceClient).get_transport_class, type(ServingConfigServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ServingConfigServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the serving config service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ServingConfigServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ServingConfigServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_serving_config(self, - request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, - *, - parent: str = None, - serving_config: gcr_serving_config.ServingConfig = None, - serving_config_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_create_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = await client.create_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateServingConfigRequest, dict]): - The request object. Request for CreateServingConfig - method. - parent (:class:`str`): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config (:class:`google.cloud.retail_v2beta.types.ServingConfig`): - Required. The ServingConfig to - create. - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config_id (:class:`str`): - Required. The ID to use for the ServingConfig, which - will become the final component of the ServingConfig's - resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``serving_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, serving_config, serving_config_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.CreateServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if serving_config is not None: - request.serving_config = serving_config - if serving_config_id is not None: - request.serving_config_id = serving_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_serving_config(self, - request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_delete_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_serving_config(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteServingConfigRequest, dict]): - The request object. Request for DeleteServingConfig - method. - name (:class:`str`): - Required. The resource name of the ServingConfig to - delete. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.DeleteServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_serving_config(self, - request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, - *, - serving_config: gcr_serving_config.ServingConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Updates a ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_update_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = await client.update_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateServingConfigRequest, dict]): - The request object. Request for UpdateServingConfig - method. - serving_config (:class:`google.cloud.retail_v2beta.types.ServingConfig`): - Required. The ServingConfig to - update. - - This corresponds to the ``serving_config`` 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 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.UpdateServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config.name", request.serving_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_serving_config(self, - request: Union[serving_config_service.GetServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> serving_config.ServingConfig: - r"""Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_get_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetServingConfigRequest, dict]): - The request object. Request for GetServingConfig method. - name (:class:`str`): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.GetServingConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_serving_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_serving_configs(self, - request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServingConfigsAsyncPager: - r"""Lists all ServingConfigs linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_list_serving_configs(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListServingConfigsRequest, dict]): - The request object. Request for ListServingConfigs - method. - parent (:class:`str`): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager: - Response for ListServingConfigs - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.ListServingConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_serving_configs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListServingConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def add_control(self, - request: Union[serving_config_service.AddControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_add_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.add_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddControlRequest, dict]): - The request object. Request for AddControl method. - serving_config (:class:`str`): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.AddControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.add_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def remove_control(self, - request: Union[serving_config_service.RemoveControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_remove_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.remove_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveControlRequest, dict]): - The request object. Request for RemoveControl method. - serving_config (:class:`str`): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = serving_config_service.RemoveControlRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.remove_control, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServingConfigServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py deleted file mode 100644 index bca31abe..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/client.py +++ /dev/null @@ -1,1163 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.retail_v2beta.services.serving_config_service import pagers -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ServingConfigServiceGrpcTransport -from .transports.grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport - - -class ServingConfigServiceClientMeta(type): - """Metaclass for the ServingConfigService 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[ServingConfigServiceTransport]] - _transport_registry["grpc"] = ServingConfigServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ServingConfigServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ServingConfigServiceTransport]: - """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 ServingConfigServiceClient(metaclass=ServingConfigServiceClientMeta): - """Service for modifying ServingConfig.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServingConfigServiceClient: 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: - ServingConfigServiceClient: 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) -> ServingConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ServingConfigServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,catalog: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, 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.+?)/catalogs/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ServingConfigServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the serving config service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ServingConfigServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ServingConfigServiceTransport): - # transport is a ServingConfigServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_serving_config(self, - request: Union[serving_config_service.CreateServingConfigRequest, dict] = None, - *, - parent: str = None, - serving_config: gcr_serving_config.ServingConfig = None, - serving_config_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_create_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = client.create_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CreateServingConfigRequest, dict]): - The request object. Request for CreateServingConfig - method. - parent (str): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config (google.cloud.retail_v2beta.types.ServingConfig): - Required. The ServingConfig to - create. - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - serving_config_id (str): - Required. The ID to use for the ServingConfig, which - will become the final component of the ServingConfig's - resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-_/. - - This corresponds to the ``serving_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick 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, serving_config, serving_config_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.CreateServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.CreateServingConfigRequest): - request = serving_config_service.CreateServingConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if serving_config is not None: - request.serving_config = serving_config - if serving_config_id is not None: - request.serving_config_id = serving_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_serving_config(self, - request: Union[serving_config_service.DeleteServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_delete_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_serving_config(request=request) - - Args: - request (Union[google.cloud.retail_v2beta.types.DeleteServingConfigRequest, dict]): - The request object. Request for DeleteServingConfig - method. - name (str): - Required. The resource name of the ServingConfig to - delete. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.DeleteServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.DeleteServingConfigRequest): - request = serving_config_service.DeleteServingConfigRequest(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_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_serving_config(self, - request: Union[serving_config_service.UpdateServingConfigRequest, dict] = None, - *, - serving_config: gcr_serving_config.ServingConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Updates a ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_update_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = client.update_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.UpdateServingConfigRequest, dict]): - The request object. Request for UpdateServingConfig - method. - serving_config (google.cloud.retail_v2beta.types.ServingConfig): - Required. The ServingConfig to - update. - - This corresponds to the ``serving_config`` 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 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig] - to update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] - - If not set, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.UpdateServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.UpdateServingConfigRequest): - request = serving_config_service.UpdateServingConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config.name", request.serving_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_serving_config(self, - request: Union[serving_config_service.GetServingConfigRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> serving_config.ServingConfig: - r"""Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_get_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_serving_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.GetServingConfigRequest, dict]): - The request object. Request for GetServingConfig method. - name (str): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.GetServingConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.GetServingConfigRequest): - request = serving_config_service.GetServingConfigRequest(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_serving_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_serving_configs(self, - request: Union[serving_config_service.ListServingConfigsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServingConfigsPager: - r"""Lists all ServingConfigs linked to this catalog. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_list_serving_configs(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ListServingConfigsRequest, dict]): - The request object. Request for ListServingConfigs - method. - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsPager: - Response for ListServingConfigs - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.ListServingConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.ListServingConfigsRequest): - request = serving_config_service.ListServingConfigsRequest(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_serving_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListServingConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def add_control(self, - request: Union[serving_config_service.AddControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_add_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.add_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.AddControlRequest, dict]): - The request object. Request for AddControl method. - serving_config (str): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.AddControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.AddControlRequest): - request = serving_config_service.AddControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.add_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def remove_control(self, - request: Union[serving_config_service.RemoveControlRequest, dict] = None, - *, - serving_config: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_serving_config.ServingConfig: - r"""Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_remove_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.remove_control(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RemoveControlRequest, dict]): - The request object. Request for RemoveControl method. - serving_config (str): - Required. The source ServingConfig resource name . - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - - This corresponds to the ``serving_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.ServingConfig: - Configures metadata that is used to generate serving time results (e.g. - search results or recommendation predictions). The - ServingConfig is passed in the search and predict - request and together with the Catalog.default_branch, - generates results. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([serving_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a serving_config_service.RemoveControlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, serving_config_service.RemoveControlRequest): - request = serving_config_service.RemoveControlRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if serving_config is not None: - request.serving_config = serving_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_control] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServingConfigServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py deleted file mode 100644 index a45bf88c..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config_service - - -class ListServingConfigsPager: - """A pager for iterating through ``list_serving_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``serving_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServingConfigs`` requests and continue to iterate - through the ``serving_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` - 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[..., serving_config_service.ListServingConfigsResponse], - request: serving_config_service.ListServingConfigsRequest, - response: serving_config_service.ListServingConfigsResponse, - *, - 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.retail_v2beta.types.ListServingConfigsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListServingConfigsResponse): - 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 = serving_config_service.ListServingConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[serving_config_service.ListServingConfigsResponse]: - 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[serving_config.ServingConfig]: - for page in self.pages: - yield from page.serving_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServingConfigsAsyncPager: - """A pager for iterating through ``list_serving_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``serving_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServingConfigs`` requests and continue to iterate - through the ``serving_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.retail_v2beta.types.ListServingConfigsResponse` - 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[serving_config_service.ListServingConfigsResponse]], - request: serving_config_service.ListServingConfigsRequest, - response: serving_config_service.ListServingConfigsResponse, - *, - 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.retail_v2beta.types.ListServingConfigsRequest): - The initial request object. - response (google.cloud.retail_v2beta.types.ListServingConfigsResponse): - 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 = serving_config_service.ListServingConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[serving_config_service.ListServingConfigsResponse]: - 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[serving_config.ServingConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.serving_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py deleted file mode 100644 index 3726ac83..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ServingConfigServiceTransport -from .grpc import ServingConfigServiceGrpcTransport -from .grpc_asyncio import ServingConfigServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ServingConfigServiceTransport]] -_transport_registry['grpc'] = ServingConfigServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ServingConfigServiceGrpcAsyncIOTransport - -__all__ = ( - 'ServingConfigServiceTransport', - 'ServingConfigServiceGrpcTransport', - 'ServingConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py deleted file mode 100644 index b8fc6e2b..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ServingConfigServiceTransport(abc.ABC): - """Abstract transport class for ServingConfigService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_serving_config: gapic_v1.method.wrap_method( - self.create_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_serving_config: gapic_v1.method.wrap_method( - self.delete_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.update_serving_config: gapic_v1.method.wrap_method( - self.update_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.get_serving_config: gapic_v1.method.wrap_method( - self.get_serving_config, - default_timeout=None, - client_info=client_info, - ), - self.list_serving_configs: gapic_v1.method.wrap_method( - self.list_serving_configs, - default_timeout=None, - client_info=client_info, - ), - self.add_control: gapic_v1.method.wrap_method( - self.add_control, - default_timeout=None, - client_info=client_info, - ), - self.remove_control: gapic_v1.method.wrap_method( - self.remove_control, - 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 create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - Union[ - serving_config.ServingConfig, - Awaitable[serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - Union[ - serving_config_service.ListServingConfigsResponse, - Awaitable[serving_config_service.ListServingConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - Union[ - gcr_serving_config.ServingConfig, - Awaitable[gcr_serving_config.ServingConfig] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ServingConfigServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py deleted file mode 100644 index 309a486a..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc.py +++ /dev/null @@ -1,440 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO - - -class ServingConfigServiceGrpcTransport(ServingConfigServiceTransport): - """gRPC backend transport for ServingConfigService. - - Service for modifying ServingConfig. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the create serving config method over gRPC. - - Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - Returns: - Callable[[~.CreateServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/CreateServingConfig', - request_serializer=serving_config_service.CreateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['create_serving_config'] - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete serving config method over gRPC. - - Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.DeleteServingConfigRequest], - ~.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_serving_config' not in self._stubs: - self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/DeleteServingConfig', - request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_serving_config'] - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the update serving config method over gRPC. - - Updates a ServingConfig. - - Returns: - Callable[[~.UpdateServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/UpdateServingConfig', - request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['update_serving_config'] - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - serving_config.ServingConfig]: - r"""Return a callable for the get serving config method over gRPC. - - Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.GetServingConfigRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/GetServingConfig', - request_serializer=serving_config_service.GetServingConfigRequest.serialize, - response_deserializer=serving_config.ServingConfig.deserialize, - ) - return self._stubs['get_serving_config'] - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - serving_config_service.ListServingConfigsResponse]: - r"""Return a callable for the list serving configs method over gRPC. - - Lists all ServingConfigs linked to this catalog. - - Returns: - Callable[[~.ListServingConfigsRequest], - ~.ListServingConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: - self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/ListServingConfigs', - request_serializer=serving_config_service.ListServingConfigsRequest.serialize, - response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, - ) - return self._stubs['list_serving_configs'] - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the add control method over gRPC. - - Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - Returns: - Callable[[~.AddControlRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_control' not in self._stubs: - self._stubs['add_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/AddControl', - request_serializer=serving_config_service.AddControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['add_control'] - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - gcr_serving_config.ServingConfig]: - r"""Return a callable for the remove control method over gRPC. - - Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - Returns: - Callable[[~.RemoveControlRequest], - ~.ServingConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_control' not in self._stubs: - self._stubs['remove_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/RemoveControl', - request_serializer=serving_config_service.RemoveControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['remove_control'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ServingConfigServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py deleted file mode 100644 index 3cd75655..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,439 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.protobuf import empty_pb2 # type: ignore -from .base import ServingConfigServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ServingConfigServiceGrpcTransport - - -class ServingConfigServiceGrpcAsyncIOTransport(ServingConfigServiceTransport): - """gRPC AsyncIO backend transport for ServingConfigService. - - Service for modifying ServingConfig. - - 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 = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_serving_config(self) -> Callable[ - [serving_config_service.CreateServingConfigRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the create serving config method over gRPC. - - Creates a ServingConfig. - - A maximum of 100 - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]s are - allowed in a [Catalog][google.cloud.retail.v2beta.Catalog], - otherwise a FAILED_PRECONDITION error is returned. - - Returns: - Callable[[~.CreateServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['create_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/CreateServingConfig', - request_serializer=serving_config_service.CreateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['create_serving_config'] - - @property - def delete_serving_config(self) -> Callable[ - [serving_config_service.DeleteServingConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete serving config method over gRPC. - - Deletes a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.DeleteServingConfigRequest], - 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_serving_config' not in self._stubs: - self._stubs['delete_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/DeleteServingConfig', - request_serializer=serving_config_service.DeleteServingConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_serving_config'] - - @property - def update_serving_config(self) -> Callable[ - [serving_config_service.UpdateServingConfigRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the update serving config method over gRPC. - - Updates a ServingConfig. - - Returns: - Callable[[~.UpdateServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['update_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/UpdateServingConfig', - request_serializer=serving_config_service.UpdateServingConfigRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['update_serving_config'] - - @property - def get_serving_config(self) -> Callable[ - [serving_config_service.GetServingConfigRequest], - Awaitable[serving_config.ServingConfig]]: - r"""Return a callable for the get serving config method over gRPC. - - Gets a ServingConfig. - Returns a NotFound error if the ServingConfig does not - exist. - - Returns: - Callable[[~.GetServingConfigRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_config' not in self._stubs: - self._stubs['get_serving_config'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/GetServingConfig', - request_serializer=serving_config_service.GetServingConfigRequest.serialize, - response_deserializer=serving_config.ServingConfig.deserialize, - ) - return self._stubs['get_serving_config'] - - @property - def list_serving_configs(self) -> Callable[ - [serving_config_service.ListServingConfigsRequest], - Awaitable[serving_config_service.ListServingConfigsResponse]]: - r"""Return a callable for the list serving configs method over gRPC. - - Lists all ServingConfigs linked to this catalog. - - Returns: - Callable[[~.ListServingConfigsRequest], - Awaitable[~.ListServingConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_serving_configs' not in self._stubs: - self._stubs['list_serving_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/ListServingConfigs', - request_serializer=serving_config_service.ListServingConfigsRequest.serialize, - response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize, - ) - return self._stubs['list_serving_configs'] - - @property - def add_control(self) -> Callable[ - [serving_config_service.AddControlRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the add control method over gRPC. - - Enables a Control on the specified ServingConfig. The control is - added in the last position of the list of controls it belongs to - (e.g. if it's a facet spec control it will be applied in the - last position of servingConfig.facetSpecIds) Returns a - ALREADY_EXISTS error if the control has already been applied. - Returns a FAILED_PRECONDITION error if the addition could exceed - maximum number of control allowed for that type of control. - - Returns: - Callable[[~.AddControlRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'add_control' not in self._stubs: - self._stubs['add_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/AddControl', - request_serializer=serving_config_service.AddControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['add_control'] - - @property - def remove_control(self) -> Callable[ - [serving_config_service.RemoveControlRequest], - Awaitable[gcr_serving_config.ServingConfig]]: - r"""Return a callable for the remove control method over gRPC. - - Disables a Control on the specified ServingConfig. The control - is removed from the ServingConfig. Returns a NOT_FOUND error if - the Control is not enabled for the ServingConfig. - - Returns: - Callable[[~.RemoveControlRequest], - Awaitable[~.ServingConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'remove_control' not in self._stubs: - self._stubs['remove_control'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.ServingConfigService/RemoveControl', - request_serializer=serving_config_service.RemoveControlRequest.serialize, - response_deserializer=gcr_serving_config.ServingConfig.deserialize, - ) - return self._stubs['remove_control'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ServingConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py deleted file mode 100644 index 5f5171c1..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py deleted file mode 100644 index 24cdc934..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/async_client.py +++ /dev/null @@ -1,730 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on the customer - website. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(UserEventServiceClient.catalog_path) - parse_catalog_path = staticmethod(UserEventServiceClient.parse_catalog_path) - product_path = staticmethod(UserEventServiceClient.product_path) - parse_product_path = staticmethod(UserEventServiceClient.parse_product_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_write_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_collect_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_purge_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_import_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2beta.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - async def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2beta - - async def sample_rejoin_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.RejoinUserEventsRequest(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.rejoin_user_events, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py deleted file mode 100644 index a57e4e27..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/client.py +++ /dev/null @@ -1,930 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[UserEventServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on the customer - website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "retail.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_path(project: str,location: str,catalog: str,branch: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/branches/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def write_user_event(self, - request: Union[user_event_service.WriteUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_write_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.retail_v2beta.types.UserEvent: - UserEvent captures all metadata - information Retail API needs to know - about how end users interact with - customers' website. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: Union[user_event_service.CollectUserEventRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_collect_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def purge_user_events(self, - request: Union[purge_config.PurgeUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_purge_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeUserEventsRequest): - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeMetadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: Union[import_config.ImportUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_import_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2beta.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportUserEventsRequest): - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportMetadata, - ) - - # Done; return the response. - return response - - def rejoin_user_events(self, - request: Union[user_event_service.RejoinUserEventsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - .. code-block:: python - - from google.cloud import retail_v2beta - - def sample_rejoin_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.retail_v2beta.types.RejoinUserEventsRequest, dict]): - The request object. Request message for RejoinUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.retail_v2beta.types.RejoinUserEventsResponse` - Response message for RejoinUserEvents method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.RejoinUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.RejoinUserEventsRequest): - request = user_event_service.RejoinUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rejoin_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - user_event_service.RejoinUserEventsResponse, - metadata_type=user_event_service.RejoinUserEventsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-retail", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py deleted file mode 100644 index f53ee5d7..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py deleted file mode 100644 index bf9e4cfe..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/base.py +++ /dev/null @@ -1,235 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-retail', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'retail.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_timeout=None, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_timeout=None, - client_info=client_info, - ), - self.purge_user_events: gapic_v1.method.wrap_method( - self.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=300.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.rejoin_user_events: gapic_v1.method.wrap_method( - self.rejoin_user_events, - 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 write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - user_event.UserEvent, - Awaitable[user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py deleted file mode 100644 index 098839e0..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index 7fbcb123..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'retail.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Retail API JavaScript - pixel and Google Tag Manager. Users should not call this - method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - @property - def rejoin_user_events(self) -> Callable[ - [user_event_service.RejoinUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the rejoin user events method over gRPC. - - Starts a user event rejoin operation with latest - product catalog. Events will not be annotated with - detailed product information if product is missing from - the catalog at the time the user event is ingested, and - these events are stored as unjoined events with a - limited usage on training and serving. This method can - be used to start a join operation on specified events - with latest version of product catalog. It can also be - used to correct events joined with the wrong product - catalog. A rejoin operation can take hours or days to - complete. - - Returns: - Callable[[~.RejoinUserEventsRequest], - 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 'rejoin_user_events' not in self._stubs: - self._stubs['rejoin_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.retail.v2beta.UserEventService/RejoinUserEvents', - request_serializer=user_event_service.RejoinUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rejoin_user_events'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py deleted file mode 100644 index 62477503..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/__init__.py +++ /dev/null @@ -1,278 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .catalog import ( - AttributesConfig, - Catalog, - CatalogAttribute, - CompletionConfig, - MerchantCenterLink, - MerchantCenterLinkingConfig, - ProductLevelConfig, -) -from .catalog_service import ( - AddCatalogAttributeRequest, - GetAttributesConfigRequest, - GetCompletionConfigRequest, - GetDefaultBranchRequest, - GetDefaultBranchResponse, - ListCatalogsRequest, - ListCatalogsResponse, - RemoveCatalogAttributeRequest, - ReplaceCatalogAttributeRequest, - SetDefaultBranchRequest, - UpdateAttributesConfigRequest, - UpdateCatalogRequest, - UpdateCompletionConfigRequest, -) -from .common import ( - Audience, - ColorInfo, - Condition, - CustomAttribute, - FulfillmentInfo, - Image, - Interval, - LocalInventory, - PriceInfo, - Rating, - Rule, - UserInfo, - AttributeConfigLevel, - SearchSolutionUseCase, - SolutionType, -) -from .completion_service import ( - CompleteQueryRequest, - CompleteQueryResponse, -) -from .control import ( - Control, -) -from .control_service import ( - CreateControlRequest, - DeleteControlRequest, - GetControlRequest, - ListControlsRequest, - ListControlsResponse, - UpdateControlRequest, -) -from .export_config import ( - ExportErrorsConfig, - ExportMetadata, - ExportProductsResponse, - ExportUserEventsResponse, -) -from .import_config import ( - BigQuerySource, - CompletionDataInputConfig, - GcsSource, - ImportCompletionDataRequest, - ImportCompletionDataResponse, - ImportErrorsConfig, - ImportMetadata, - ImportProductsRequest, - ImportProductsResponse, - ImportUserEventsRequest, - ImportUserEventsResponse, - ProductInlineSource, - ProductInputConfig, - UserEventImportSummary, - UserEventInlineSource, - UserEventInputConfig, -) -from .prediction_service import ( - PredictRequest, - PredictResponse, -) -from .product import ( - Product, -) -from .product_service import ( - AddFulfillmentPlacesMetadata, - AddFulfillmentPlacesRequest, - AddFulfillmentPlacesResponse, - AddLocalInventoriesMetadata, - AddLocalInventoriesRequest, - AddLocalInventoriesResponse, - CreateProductRequest, - DeleteProductRequest, - GetProductRequest, - ListProductsRequest, - ListProductsResponse, - RemoveFulfillmentPlacesMetadata, - RemoveFulfillmentPlacesRequest, - RemoveFulfillmentPlacesResponse, - RemoveLocalInventoriesMetadata, - RemoveLocalInventoriesRequest, - RemoveLocalInventoriesResponse, - SetInventoryMetadata, - SetInventoryRequest, - SetInventoryResponse, - UpdateProductRequest, -) -from .promotion import ( - Promotion, -) -from .purge_config import ( - PurgeMetadata, - PurgeUserEventsRequest, - PurgeUserEventsResponse, -) -from .search_service import ( - SearchRequest, - SearchResponse, -) -from .serving_config import ( - ServingConfig, -) -from .serving_config_service import ( - AddControlRequest, - CreateServingConfigRequest, - DeleteServingConfigRequest, - GetServingConfigRequest, - ListServingConfigsRequest, - ListServingConfigsResponse, - RemoveControlRequest, - UpdateServingConfigRequest, -) -from .user_event import ( - CompletionDetail, - ProductDetail, - PurchaseTransaction, - UserEvent, -) -from .user_event_service import ( - CollectUserEventRequest, - RejoinUserEventsMetadata, - RejoinUserEventsRequest, - RejoinUserEventsResponse, - WriteUserEventRequest, -) - -__all__ = ( - 'AttributesConfig', - 'Catalog', - 'CatalogAttribute', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'ProductLevelConfig', - 'AddCatalogAttributeRequest', - 'GetAttributesConfigRequest', - 'GetCompletionConfigRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - 'SetDefaultBranchRequest', - 'UpdateAttributesConfigRequest', - 'UpdateCatalogRequest', - 'UpdateCompletionConfigRequest', - 'Audience', - 'ColorInfo', - 'Condition', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'LocalInventory', - 'PriceInfo', - 'Rating', - 'Rule', - 'UserInfo', - 'AttributeConfigLevel', - 'SearchSolutionUseCase', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Control', - 'CreateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - 'UpdateControlRequest', - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - 'BigQuerySource', - 'CompletionDataInputConfig', - 'GcsSource', - 'ImportCompletionDataRequest', - 'ImportCompletionDataResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportProductsRequest', - 'ImportProductsResponse', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ProductInlineSource', - 'ProductInputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'UserEventInputConfig', - 'PredictRequest', - 'PredictResponse', - 'Product', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesResponse', - 'CreateProductRequest', - 'DeleteProductRequest', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesResponse', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesResponse', - 'SetInventoryMetadata', - 'SetInventoryRequest', - 'SetInventoryResponse', - 'UpdateProductRequest', - 'Promotion', - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'SearchRequest', - 'SearchResponse', - 'ServingConfig', - 'AddControlRequest', - 'CreateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'RemoveControlRequest', - 'UpdateServingConfigRequest', - 'CompletionDetail', - 'ProductDetail', - 'PurchaseTransaction', - 'UserEvent', - 'CollectUserEventRequest', - 'RejoinUserEventsMetadata', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py deleted file mode 100644 index 8398213f..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog.py +++ /dev/null @@ -1,528 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'ProductLevelConfig', - 'CatalogAttribute', - 'AttributesConfig', - 'CompletionConfig', - 'MerchantCenterLink', - 'MerchantCenterLinkingConfig', - 'Catalog', - }, -) - - -class ProductLevelConfig(proto.Message): - r"""Configures what level the product should be uploaded with - regards to how users will be send events and how predictions - will be made. - - Attributes: - ingestion_product_type (str): - The type of [Product][google.cloud.retail.v2beta.Product]s - allowed to be ingested into the catalog. Acceptable values - are: - - - ``primary`` (default): You can ingest - [Product][google.cloud.retail.v2beta.Product]s of all - types. When ingesting a - [Product][google.cloud.retail.v2beta.Product], its type - will default to - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - if unset. - - ``variant``: You can only ingest - [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s. This - means - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] - cannot be empty. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``variant`` and - [merchant_center_product_id_field][google.cloud.retail.v2beta.ProductLevelConfig.merchant_center_product_id_field] - is ``itemGroupId``, an INVALID_ARGUMENT error is returned. - - See `Using product - levels `__ - for more details. - merchant_center_product_id_field (str): - Which field of `Merchant Center - Product `__ - should be imported as - [Product.id][google.cloud.retail.v2beta.Product.id]. - Acceptable values are: - - - ``offerId`` (default): Import ``offerId`` as the product - ID. - - ``itemGroupId``: Import ``itemGroupId`` as the product - ID. Notice that Retail API will choose one item from the - ones with the same ``itemGroupId``, and use it to - represent the item group. - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - If this field is ``itemGroupId`` and - [ingestion_product_type][google.cloud.retail.v2beta.ProductLevelConfig.ingestion_product_type] - is ``variant``, an INVALID_ARGUMENT error is returned. - - See `Using product - levels `__ - for more details. - """ - - ingestion_product_type = proto.Field( - proto.STRING, - number=1, - ) - merchant_center_product_id_field = proto.Field( - proto.STRING, - number=2, - ) - - -class CatalogAttribute(proto.Message): - r"""Catalog level attribute config for an attribute. For example, - if customers want to enable/disable facet for a specific - attribute. - - Attributes: - key (str): - Required. Attribute name. For example: ``color``, - ``brands``, ``attributes.custom_attribute``, such as - ``attributes.xyz``. - in_use (bool): - Output only. Indicates whether this attribute has been used - by any products. ``True`` if at least one - [Product][google.cloud.retail.v2beta.Product] is using this - attribute in - [Product.attributes][google.cloud.retail.v2beta.Product.attributes]. - Otherwise, this field is ``False``. - - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - can be pre-loaded by using [AddCatalogAttribute][], - [ImportCatalogAttributes][], or [UpdateAttributesConfig][] - APIs. This field is ``False`` for pre-loaded - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s. - - Only - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s - that are not in use by products can be deleted. - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]s - that are in use by products cannot be deleted; however, - their configuration properties will reset to default values - upon removal request. - - After catalog changes, it takes about 10 minutes for this - field to update. - type_ (google.cloud.retail_v2beta.types.CatalogAttribute.AttributeType): - Output only. The type of this attribute. This is derived - from the attribute in - [Product.attributes][google.cloud.retail.v2beta.Product.attributes]. - indexable_option (google.cloud.retail_v2beta.types.CatalogAttribute.IndexableOption): - When - [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] - is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if INDEXABLE_ENABLED - attribute values are indexed so that it can be filtered, - faceted, or boosted in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - dynamic_facetable_option (google.cloud.retail_v2beta.types.CatalogAttribute.DynamicFacetableOption): - If DYNAMIC_FACETABLE_ENABLED, attribute values are available - for dynamic facet. Could only be DYNAMIC_FACETABLE_DISABLED - if - [CatalogAttribute.indexable_option][google.cloud.retail.v2beta.CatalogAttribute.indexable_option] - is INDEXABLE_DISABLED. Otherwise, an INVALID_ARGUMENT error - is returned. - searchable_option (google.cloud.retail_v2beta.types.CatalogAttribute.SearchableOption): - When - [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] - is CATALOG_LEVEL_ATTRIBUTE_CONFIG, if SEARCHABLE_ENABLED, - attribute values are searchable by text queries in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - If SEARCHABLE_ENABLED but attribute type is numerical, - attribute values will not be searchable by text queries in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search], - as there are no text values associated to numerical - attributes. - """ - class AttributeType(proto.Enum): - r"""The type of an attribute.""" - UNKNOWN = 0 - TEXTUAL = 1 - NUMERICAL = 2 - - class IndexableOption(proto.Enum): - r"""The status of the indexable option of a catalog attribute.""" - INDEXABLE_OPTION_UNSPECIFIED = 0 - INDEXABLE_ENABLED = 1 - INDEXABLE_DISABLED = 2 - - class DynamicFacetableOption(proto.Enum): - r"""The status of the dynamic facetable option of a catalog - attribute. - """ - DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 - DYNAMIC_FACETABLE_ENABLED = 1 - DYNAMIC_FACETABLE_DISABLED = 2 - - class SearchableOption(proto.Enum): - r"""The status of the searchable option of a catalog attribute.""" - SEARCHABLE_OPTION_UNSPECIFIED = 0 - SEARCHABLE_ENABLED = 1 - SEARCHABLE_DISABLED = 2 - - key = proto.Field( - proto.STRING, - number=1, - ) - in_use = proto.Field( - proto.BOOL, - number=9, - ) - type_ = proto.Field( - proto.ENUM, - number=10, - enum=AttributeType, - ) - indexable_option = proto.Field( - proto.ENUM, - number=5, - enum=IndexableOption, - ) - dynamic_facetable_option = proto.Field( - proto.ENUM, - number=6, - enum=DynamicFacetableOption, - ) - searchable_option = proto.Field( - proto.ENUM, - number=7, - enum=SearchableOption, - ) - - -class AttributesConfig(proto.Message): - r"""Catalog level attribute config. - - Attributes: - name (str): - Required. Immutable. The fully qualified resource name of - the attribute config. Format: - ``projects/*/locations/*/catalogs/*/attributesConfig`` - catalog_attributes (Mapping[str, google.cloud.retail_v2beta.types.CatalogAttribute]): - Enable attribute(s) config at catalog level. For example, - indexable, dynamic_facetable, or searchable for each - attribute. - - The key is catalog attribute's name. For example: ``color``, - ``brands``, ``attributes.custom_attribute``, such as - ``attributes.xyz``. - - The maximum number of catalog attributes allowed in a - request is 1000. - attribute_config_level (google.cloud.retail_v2beta.types.AttributeConfigLevel): - Output only. The - [AttributeConfigLevel][google.cloud.retail.v2beta.AttributeConfigLevel] - used for this catalog. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - catalog_attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='CatalogAttribute', - ) - attribute_config_level = proto.Field( - proto.ENUM, - number=3, - enum=common.AttributeConfigLevel, - ) - - -class CompletionConfig(proto.Message): - r"""Catalog level autocomplete config for customers to customize - autocomplete feature's settings. - - Attributes: - name (str): - Required. Immutable. Fully qualified name - ``projects/*/locations/*/catalogs/*/completionConfig`` - matching_order (str): - Specifies the matching order for autocomplete suggestions, - e.g., a query consisting of 'sh' with 'out-of-order' - specified would suggest "women's shoes", whereas a query of - 'red s' with 'exact-prefix' specified would suggest "red - shoes". Currently supported values: - - - 'out-of-order' - - 'exact-prefix' - - Default value: 'exact-prefix'. - max_suggestions (int): - The maximum number of autocomplete - suggestions returned per term. The maximum - allowed max suggestions is 20. Default value is - 20. If left unset or set to 0, then will - fallback to default value. - min_prefix_length (int): - The minimum number of characters needed to be - typed in order to get suggestions. Default value - is 2. If left unset or set to 0, then will - fallback to default value. - auto_learning (bool): - If set to true, the auto learning function is enabled. Auto - learning uses user data to generate suggestions using ML - techniques. Default value is false. Only after enabling auto - learning can users use ``cloud-retail`` data in - [CompleteQueryRequest][google.cloud.retail.v2beta.CompleteQueryRequest]. - suggestions_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the - autocomplete phrases uploaded by the customer. - last_suggestions_import_operation (str): - Output only. Name of the LRO corresponding to the latest - suggestion terms list import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - denylist_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the / - autocomplete denylist phrases uploaded by the - customer. - last_denylist_import_operation (str): - Output only. LRO corresponding to the latest denylist - import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - allowlist_input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): - Output only. The input config for the import - of the source data that contains the - autocomplete allowlist phrases uploaded by the - customer. - last_allowlist_import_operation (str): - Output only. LRO corresponding to the latest allowlist - import. - - Can use - [GetOperation][google.longrunning.Operations.GetOperation] - API to retrieve the latest state of the Long Running - Operation. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - matching_order = proto.Field( - proto.STRING, - number=2, - ) - max_suggestions = proto.Field( - proto.INT32, - number=3, - ) - min_prefix_length = proto.Field( - proto.INT32, - number=4, - ) - auto_learning = proto.Field( - proto.BOOL, - number=11, - ) - suggestions_input_config = proto.Field( - proto.MESSAGE, - number=5, - message=import_config.CompletionDataInputConfig, - ) - last_suggestions_import_operation = proto.Field( - proto.STRING, - number=6, - ) - denylist_input_config = proto.Field( - proto.MESSAGE, - number=7, - message=import_config.CompletionDataInputConfig, - ) - last_denylist_import_operation = proto.Field( - proto.STRING, - number=8, - ) - allowlist_input_config = proto.Field( - proto.MESSAGE, - number=9, - message=import_config.CompletionDataInputConfig, - ) - last_allowlist_import_operation = proto.Field( - proto.STRING, - number=10, - ) - - -class MerchantCenterLink(proto.Message): - r"""Represents a link between a Merchant Center account and a - branch. Once a link is established, products from the linked - merchant center account will be streamed to the linked branch. - - Attributes: - merchant_center_account_id (int): - Required. The linked `Merchant center account - id `__. - The account must be a standalone account or a sub-account of - a MCA. - branch_id (str): - The branch id (e.g. 0/1/2) within this catalog that products - from merchant_center_account_id are streamed to. When - updating this field, an empty value will use the currently - configured default branch. However, changing the default - branch later on won't change the linked branch here. - - A single branch id can only have one linked merchant center - account id. - destinations (Sequence[str]): - String representing the destination to import for, all if - left empty. List of possible values can be found here. - [https://support.google.com/merchants/answer/7501026] List - of allowed string values: "Shopping_ads", - "Buy_on_google_listings", "Display_ads", "Local_inventory - \_ads", "Free_listings", "Free_local_listings" NOTE: The - string values are case sensitive. - region_code (str): - Region code of offers to accept. 2-letter Uppercase ISO - 3166-1 alpha-2 code. List of values can be found - `here `__ - under the ``region`` tag. If left blank no region filtering - will be performed. - - Example value: ``US``. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. ISO - 639-1. - - This specifies the language of offers in Merchant Center - that will be accepted. If empty no language filtering will - be performed. - - Example value: ``en``. - """ - - merchant_center_account_id = proto.Field( - proto.INT64, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - destinations = proto.RepeatedField( - proto.STRING, - number=3, - ) - region_code = proto.Field( - proto.STRING, - number=4, - ) - language_code = proto.Field( - proto.STRING, - number=5, - ) - - -class MerchantCenterLinkingConfig(proto.Message): - r"""Configures Merchant Center linking. - Links contained in the config will be used to sync data from a - Merchant Center account to a Cloud Retail branch. - - Attributes: - links (Sequence[google.cloud.retail_v2beta.types.MerchantCenterLink]): - Links between Merchant Center accounts and - branches. - """ - - links = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='MerchantCenterLink', - ) - - -class Catalog(proto.Message): - r"""The catalog configuration. - - Attributes: - name (str): - Required. Immutable. The fully qualified - resource name of the catalog. - display_name (str): - Required. Immutable. The catalog display name. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - product_level_config (google.cloud.retail_v2beta.types.ProductLevelConfig): - Required. The product level configuration. - merchant_center_linking_config (google.cloud.retail_v2beta.types.MerchantCenterLinkingConfig): - The Merchant Center linking configuration. - Once a link is added, the data stream from - Merchant Center to Cloud Retail will be enabled - automatically. The requester must have access to - the merchant center account in order to make - changes to this field. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - product_level_config = proto.Field( - proto.MESSAGE, - number=4, - message='ProductLevelConfig', - ) - merchant_center_linking_config = proto.Field( - proto.MESSAGE, - number=6, - message='MerchantCenterLinkingConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py deleted file mode 100644 index c49ba005..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/catalog_service.py +++ /dev/null @@ -1,453 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'ListCatalogsRequest', - 'ListCatalogsResponse', - 'UpdateCatalogRequest', - 'SetDefaultBranchRequest', - 'GetDefaultBranchRequest', - 'GetDefaultBranchResponse', - 'GetCompletionConfigRequest', - 'UpdateCompletionConfigRequest', - 'GetAttributesConfigRequest', - 'UpdateAttributesConfigRequest', - 'AddCatalogAttributeRequest', - 'RemoveCatalogAttributeRequest', - 'ReplaceCatalogAttributeRequest', - }, -) - - -class ListCatalogsRequest(proto.Message): - r"""Request for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - - Attributes: - parent (str): - Required. The account resource name with an associated - location. - - If the caller does not have permission to list - [Catalog][google.cloud.retail.v2beta.Catalog]s under this - location, regardless of whether or not this location exists, - a PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of - [Catalog][google.cloud.retail.v2beta.Catalog]s to return. If - unspecified, defaults to 50. The maximum allowed value is - 1000. Values above 1000 will be coerced to 1000. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [ListCatalogsResponse.next_page_token][google.cloud.retail.v2beta.ListCatalogsResponse.next_page_token], - received from a previous - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListCatalogsResponse(proto.Message): - r"""Response for - [CatalogService.ListCatalogs][google.cloud.retail.v2beta.CatalogService.ListCatalogs] - method. - - Attributes: - catalogs (Sequence[google.cloud.retail_v2beta.types.Catalog]): - All the customer's - [Catalog][google.cloud.retail.v2beta.Catalog]s. - next_page_token (str): - A token that can be sent as - [ListCatalogsRequest.page_token][google.cloud.retail.v2beta.ListCatalogsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - catalogs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateCatalogRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCatalog][google.cloud.retail.v2beta.CatalogService.UpdateCatalog] - method. - - Attributes: - catalog (google.cloud.retail_v2beta.types.Catalog): - Required. The [Catalog][google.cloud.retail.v2beta.Catalog] - to update. - - If the caller does not have permission to update the - [Catalog][google.cloud.retail.v2beta.Catalog], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Catalog][google.cloud.retail.v2beta.Catalog] 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 - [Catalog][google.cloud.retail.v2beta.Catalog] to update. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - catalog = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.Catalog, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class SetDefaultBranchRequest(proto.Message): - r"""Request message to set a specified branch as new default_branch. - - Attributes: - catalog (str): - Full resource name of the catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - branch_id (str): - The final component of the resource name of a branch. - - This field must be one of "0", "1" or "2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If there are no sufficient active products in the targeted - branch and - [force][google.cloud.retail.v2beta.SetDefaultBranchRequest.force] - is not set, a FAILED_PRECONDITION error is returned. - note (str): - Some note on this request, this can be retrieved by - [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch] - before next valid default branch set occurs. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - force (bool): - If set to true, it permits switching to a branch with - [branch_id][google.cloud.retail.v2beta.SetDefaultBranchRequest.branch_id] - even if it has no sufficient active products. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - branch_id = proto.Field( - proto.STRING, - number=2, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - force = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetDefaultBranchRequest(proto.Message): - r"""Request message to show which branch is currently the default - branch. - - Attributes: - catalog (str): - The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - - -class GetDefaultBranchResponse(proto.Message): - r"""Response message of - [CatalogService.GetDefaultBranch][google.cloud.retail.v2beta.CatalogService.GetDefaultBranch]. - - Attributes: - branch (str): - Full resource name of the branch id currently - set as default branch. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when this branch is set to default. - note (str): - This corresponds to - [SetDefaultBranchRequest.note][google.cloud.retail.v2beta.SetDefaultBranchRequest.note] - field, when this branch was set as default. - """ - - branch = proto.Field( - proto.STRING, - number=1, - ) - set_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - note = proto.Field( - proto.STRING, - number=3, - ) - - -class GetCompletionConfigRequest(proto.Message): - r"""Request for - [CatalogService.GetCompletionConfig][google.cloud.retail.v2beta.CatalogService.GetCompletionConfig] - method. - - Attributes: - name (str): - Required. Full CompletionConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateCompletionConfigRequest(proto.Message): - r"""Request for - [CatalogService.UpdateCompletionConfig][google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig] - method. - - Attributes: - completion_config (google.cloud.retail_v2beta.types.CompletionConfig): - Required. The - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. - - If the caller does not have permission to update the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig], - then a PERMISSION_DENIED error is returned. - - If the - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - 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 - [CompletionConfig][google.cloud.retail.v2beta.CompletionConfig] - to update. The following are the only supported fields: - - - [CompletionConfig.matching_order][google.cloud.retail.v2beta.CompletionConfig.matching_order] - - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions] - - [CompletionConfig.min_prefix_length][google.cloud.retail.v2beta.CompletionConfig.min_prefix_length] - - [CompletionConfig.auto_learning][google.cloud.retail.v2beta.CompletionConfig.auto_learning] - - If not set, all supported fields are updated. - """ - - completion_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.CompletionConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetAttributesConfigRequest(proto.Message): - r"""Request for - [CatalogService.GetAttributesConfig][google.cloud.retail.v2beta.CatalogService.GetAttributesConfig] - method. - - Attributes: - name (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateAttributesConfigRequest(proto.Message): - r"""Request for - [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig] - method. - - Attributes: - attributes_config (google.cloud.retail_v2beta.types.AttributesConfig): - Required. The - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [AttributesConfig][google.cloud.retail.v2beta.AttributesConfig] - to update. The following is the only supported field: - - - [AttributesConfig.catalog_attributes][google.cloud.retail.v2beta.AttributesConfig.catalog_attributes] - - If not set, all supported fields are updated. - """ - - attributes_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_catalog.AttributesConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class AddCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.AddCatalogAttribute][google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - catalog_attribute (google.cloud.retail_v2beta.types.CatalogAttribute): - Required. The - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to add. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - catalog_attribute = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_catalog.CatalogAttribute, - ) - - -class RemoveCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.RemoveCatalogAttribute][google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - key (str): - Required. The attribute name key of the - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to remove. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - key = proto.Field( - proto.STRING, - number=2, - ) - - -class ReplaceCatalogAttributeRequest(proto.Message): - r"""Request for - [CatalogService.ReplaceCatalogAttribute][google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute] - method. - - Attributes: - attributes_config (str): - Required. Full AttributesConfig resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig - catalog_attribute (google.cloud.retail_v2beta.types.CatalogAttribute): - Required. The updated - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute]. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - to update. The following are NOT supported: - - - [CatalogAttribute.key][google.cloud.retail.v2beta.CatalogAttribute.key] - - If not set, all supported fields are updated. - """ - - attributes_config = proto.Field( - proto.STRING, - number=1, - ) - catalog_attribute = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_catalog.CatalogAttribute, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py deleted file mode 100644 index c40843c0..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/common.py +++ /dev/null @@ -1,1178 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'AttributeConfigLevel', - 'SolutionType', - 'SearchSolutionUseCase', - 'Condition', - 'Rule', - 'Audience', - 'ColorInfo', - 'CustomAttribute', - 'FulfillmentInfo', - 'Image', - 'Interval', - 'PriceInfo', - 'Rating', - 'UserInfo', - 'LocalInventory', - }, -) - - -class AttributeConfigLevel(proto.Enum): - r"""At which level we offer configuration for attributes.""" - ATTRIBUTE_CONFIG_LEVEL_UNSPECIFIED = 0 - PRODUCT_LEVEL_ATTRIBUTE_CONFIG = 1 - CATALOG_LEVEL_ATTRIBUTE_CONFIG = 2 - - -class SolutionType(proto.Enum): - r"""The type of solution.""" - SOLUTION_TYPE_UNSPECIFIED = 0 - SOLUTION_TYPE_RECOMMENDATION = 1 - SOLUTION_TYPE_SEARCH = 2 - - -class SearchSolutionUseCase(proto.Enum): - r"""The use case of Cloud Retail Search.""" - SEARCH_SOLUTION_USE_CASE_UNSPECIFIED = 0 - SEARCH_SOLUTION_USE_CASE_SEARCH = 1 - SEARCH_SOLUTION_USE_CASE_BROWSE = 2 - - -class Condition(proto.Message): - r"""Metadata that is used to define a condition that triggers an action. - A valid condition must specify at least one of 'query_terms' or - 'products_filter'. If multiple fields are specified, the condition - is met if all the fields are satisfied e.g. if a set of query terms - and product_filter are set, then only items matching the - product_filter for requests with a query matching the query terms - wil get boosted. - - Attributes: - query_terms (Sequence[google.cloud.retail_v2beta.types.Condition.QueryTerm]): - A list (up to 10 entries) of terms to match - the query on. If not specified, match all - queries. If many query terms are specified, the - condition is matched if any of the terms is a - match (i.e. using the OR operator). - active_time_range (Sequence[google.cloud.retail_v2beta.types.Condition.TimeRange]): - Range of time(s) specifying when Condition is - active. Condition true if any time range - matches. - """ - - class QueryTerm(proto.Message): - r"""Query terms that we want to match on. - - Attributes: - value (str): - The value of the term to match on. - Value cannot be empty. - Value can have at most 3 terms if specified as a - partial match. Each space separated string is - considered as one term. Example) "a b c" is 3 - terms and allowed, " a b c d" is 4 terms and not - allowed for partial match. - full_match (bool): - Whether this is supposed to be a full or - partial match. - """ - - value = proto.Field( - proto.STRING, - number=1, - ) - full_match = proto.Field( - proto.BOOL, - number=2, - ) - - class TimeRange(proto.Message): - r"""Used for time-dependent conditions. - Example: Want to have rule applied for week long sale. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start of time range. Range is inclusive. - end_time (google.protobuf.timestamp_pb2.Timestamp): - End of time range. Range is inclusive. - """ - - start_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - query_terms = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=QueryTerm, - ) - active_time_range = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=TimeRange, - ) - - -class Rule(proto.Message): - r"""A rule is a condition-action pair - - - A condition defines when a rule is to be triggered. - - An action specifies what occurs on that trigger. Currently only - boost rules are supported. Currently only supported by the search - endpoint. - - 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: - boost_action (google.cloud.retail_v2beta.types.Rule.BoostAction): - A boost action. - - This field is a member of `oneof`_ ``action``. - redirect_action (google.cloud.retail_v2beta.types.Rule.RedirectAction): - Redirects a shopper to a specific page. - - This field is a member of `oneof`_ ``action``. - oneway_synonyms_action (google.cloud.retail_v2beta.types.Rule.OnewaySynonymsAction): - Treats specific term as a synonym with a - group of terms. Group of terms will not be - treated as synonyms with the specific term. - - This field is a member of `oneof`_ ``action``. - do_not_associate_action (google.cloud.retail_v2beta.types.Rule.DoNotAssociateAction): - Prevents term from being associated with - other terms. - - This field is a member of `oneof`_ ``action``. - replacement_action (google.cloud.retail_v2beta.types.Rule.ReplacementAction): - Replaces specific terms in the query. - - This field is a member of `oneof`_ ``action``. - ignore_action (google.cloud.retail_v2beta.types.Rule.IgnoreAction): - Ignores specific terms from query during - search. - - This field is a member of `oneof`_ ``action``. - filter_action (google.cloud.retail_v2beta.types.Rule.FilterAction): - Filters results. - - This field is a member of `oneof`_ ``action``. - twoway_synonyms_action (google.cloud.retail_v2beta.types.Rule.TwowaySynonymsAction): - Treats a set of terms as synonyms of one - another. - - This field is a member of `oneof`_ ``action``. - condition (google.cloud.retail_v2beta.types.Condition): - Required. The condition that triggers the - rule. If the condition is empty, the rule will - always apply. - """ - - class BoostAction(proto.Message): - r"""A boost action to apply to results matching condition - specified above. - - Attributes: - boost (float): - Strength of the condition boost, which must be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - products_filter (str): - The filter can have a max size of 5000 characters. An - expression which specifies which products to apply an action - to. The syntax and supported fields are the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": *(id: - ANY("product_1", "product_2"))* *AND* *(colorFamilies: - ANY("Red", "Blue"))* - """ - - boost = proto.Field( - proto.FLOAT, - number=1, - ) - products_filter = proto.Field( - proto.STRING, - number=2, - ) - - class FilterAction(proto.Message): - r"""- Rule Condition: - - - No [Condition][query_terms] provided is a global match. - - 1 or more [Condition][query_terms] provided is combined with - OR operator. - - - Action Input: The request query and filter that will be applied - to the retrieved products, in addition to any filters already - provided with the SearchRequest. The AND operator is used to - combine the query's existing filters with the filter rule(s). - NOTE: May result in 0 results when filters conflict. - - Action Result: Filters the returned objects to be ONLY those that - passed the filter. - - Attributes: - filter (str): - A filter to apply on the matching condition results. - Supported features: - - - [filter][google.cloud.retail.v2beta.Rule.FilterAction.filter] - must be set. - - Filter syntax is identical to - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter]. - See more details at the Retail Search `user - guide `__. - - To filter products with product ID "product_1" or - "product_2", and color "Red" or "Blue": *(id: - ANY("product_1", "product_2"))* *AND* *(colorFamilies: - ANY("Red", "Blue"))* - """ - - filter = proto.Field( - proto.STRING, - number=1, - ) - - class RedirectAction(proto.Message): - r"""Redirects a shopper to a specific page. - - - Rule Condition: - - - Must specify [Condition][query_terms]. - - - Action Input: Request Query - - Action Result: Redirects shopper to provided uri. - - Attributes: - redirect_uri (str): - URL must have length equal or less than 2000 - characters. - """ - - redirect_uri = proto.Field( - proto.STRING, - number=1, - ) - - class TwowaySynonymsAction(proto.Message): - r"""Creates a set of terms that will be treated as synonyms of each - other. Example: synonyms of "sneakers" and "shoes". - - - "sneakers" will use a synonym of "shoes". - - "shoes" will use a synonym of "sneakers". - - Attributes: - synonyms (Sequence[str]): - Defines a set of synonyms. - Can specify up to 100 synonyms. - Must specify at least 2 synonyms. - """ - - synonyms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class OnewaySynonymsAction(proto.Message): - r"""Maps a set of terms to a set of synonyms. Set of synonyms will be - treated as synonyms of each query term only. ``query_terms`` will - not be treated as synonyms of each other. Example: "sneakers" will - use a synonym of "shoes". "shoes" will not use a synonym of - "sneakers". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. - Will treat synonyms as their synonyms. - Not themselves synonyms of the synonyms. - Can specify up to 100 terms. - synonyms (Sequence[str]): - Defines a set of synonyms. - Cannot contain duplicates. - Can specify up to 100 synonyms. - oneway_terms (Sequence[str]): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=3, - ) - synonyms = proto.RepeatedField( - proto.STRING, - number=4, - ) - oneway_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class DoNotAssociateAction(proto.Message): - r"""Prevents ``query_term`` from being associated with specified terms - during search. Example: Don't associate "gShoe" and "cheap". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. Will not consider - do_not_associate_terms for search if in search query. Can - specify up to 100 terms. - do_not_associate_terms (Sequence[str]): - Cannot contain duplicates or the query term. - Can specify up to 100 terms. - terms (Sequence[str]): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - do_not_associate_terms = proto.RepeatedField( - proto.STRING, - number=3, - ) - terms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class ReplacementAction(proto.Message): - r"""Replaces a term in the query. Multiple replacement candidates can be - specified. All ``query_terms`` will be replaced with the replacement - term. Example: Replace "gShoe" with "google shoe". - - Attributes: - query_terms (Sequence[str]): - Terms from the search query. - Will be replaced by replacement term. - Can specify up to 100 terms. - replacement_term (str): - Term that will be used for replacement. - term (str): - Will be [deprecated = true] post migration; - """ - - query_terms = proto.RepeatedField( - proto.STRING, - number=2, - ) - replacement_term = proto.Field( - proto.STRING, - number=3, - ) - term = proto.Field( - proto.STRING, - number=1, - ) - - class IgnoreAction(proto.Message): - r"""Prevents a term in the query from being used in search. - Example: Don't search for "shoddy". - - Attributes: - ignore_terms (Sequence[str]): - Terms to ignore in the search query. - """ - - ignore_terms = proto.RepeatedField( - proto.STRING, - number=1, - ) - - boost_action = proto.Field( - proto.MESSAGE, - number=2, - oneof='action', - message=BoostAction, - ) - redirect_action = proto.Field( - proto.MESSAGE, - number=3, - oneof='action', - message=RedirectAction, - ) - oneway_synonyms_action = proto.Field( - proto.MESSAGE, - number=6, - oneof='action', - message=OnewaySynonymsAction, - ) - do_not_associate_action = proto.Field( - proto.MESSAGE, - number=7, - oneof='action', - message=DoNotAssociateAction, - ) - replacement_action = proto.Field( - proto.MESSAGE, - number=8, - oneof='action', - message=ReplacementAction, - ) - ignore_action = proto.Field( - proto.MESSAGE, - number=9, - oneof='action', - message=IgnoreAction, - ) - filter_action = proto.Field( - proto.MESSAGE, - number=10, - oneof='action', - message=FilterAction, - ) - twoway_synonyms_action = proto.Field( - proto.MESSAGE, - number=11, - oneof='action', - message=TwowaySynonymsAction, - ) - condition = proto.Field( - proto.MESSAGE, - number=1, - message='Condition', - ) - - -class Audience(proto.Message): - r"""An intended audience of the - [Product][google.cloud.retail.v2beta.Product] for whom it's sold. - - Attributes: - genders (Sequence[str]): - The genders of the audience. Strongly encouraged to use the - standard values: "male", "female", "unisex". - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `gender `__. - Schema.org property - `Product.audience.suggestedGender `__. - age_groups (Sequence[str]): - The age groups of the audience. Strongly encouraged to use - the standard values: "newborn" (up to 3 months old), - "infant" (3–12 months old), "toddler" (1–5 years old), - "kids" (5–13 years old), "adult" (typically teens or older). - - At most 5 values are allowed. Each value must be a UTF-8 - encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `age_group `__. - Schema.org property - `Product.audience.suggestedMinAge `__ - and - `Product.audience.suggestedMaxAge `__. - """ - - genders = proto.RepeatedField( - proto.STRING, - number=1, - ) - age_groups = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class ColorInfo(proto.Message): - r"""The color information of a - [Product][google.cloud.retail.v2beta.Product]. - - Attributes: - color_families (Sequence[str]): - The standard color families. Strongly recommended to use the - following standard color groups: "Red", "Pink", "Orange", - "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown", - "White", "Gray", "Black" and "Mixed". Normally it is - expected to have only 1 color family. May consider using - single "Mixed" instead of multiple values. - - A maximum of 5 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - colors (Sequence[str]): - The color display names, which may be different from - standard color family names, such as the color aliases used - in the website frontend. Normally it is expected to have - only 1 color. May consider using single "Mixed" instead of - multiple values. - - A maximum of 25 colors are allowed. Each value must be a - UTF-8 encoded string with a length limit of 128 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - """ - - color_families = proto.RepeatedField( - proto.STRING, - number=1, - ) - colors = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class CustomAttribute(proto.Message): - r"""A custom attribute that is not explicitly modeled in - [Product][google.cloud.retail.v2beta.Product]. - - Attributes: - text (Sequence[str]): - The textual values of this custom attribute. For example, - ``["yellow", "green"]`` when the key is "color". - - Empty string is not allowed. Otherwise, an INVALID_ARGUMENT - error is returned. - - Exactly one of - [text][google.cloud.retail.v2beta.CustomAttribute.text] or - [numbers][google.cloud.retail.v2beta.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - numbers (Sequence[float]): - The numerical values of this custom attribute. For example, - ``[2.3, 15.4]`` when the key is "lengths_cm". - - Exactly one of - [text][google.cloud.retail.v2beta.CustomAttribute.text] or - [numbers][google.cloud.retail.v2beta.CustomAttribute.numbers] - should be set. Otherwise, an INVALID_ARGUMENT error is - returned. - searchable (bool): - This field will only be used when - [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] - of the [Catalog][google.cloud.retail.v2beta.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are searchable by text queries in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2beta.UserEvent]. - - Only set if type - [text][google.cloud.retail.v2beta.CustomAttribute.text] is - set. Otherwise, a INVALID_ARGUMENT error is returned. - - This field is a member of `oneof`_ ``_searchable``. - indexable (bool): - This field will only be used when - [AttributesConfig.attribute_config_level][google.cloud.retail.v2beta.AttributesConfig.attribute_config_level] - of the [Catalog][google.cloud.retail.v2beta.Catalog] is - 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom attribute - values are indexed, so that it can be filtered, faceted or - boosted in - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - This field is ignored in a - [UserEvent][google.cloud.retail.v2beta.UserEvent]. - - See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter], - [SearchRequest.facet_specs][google.cloud.retail.v2beta.SearchRequest.facet_specs] - and - [SearchRequest.boost_spec][google.cloud.retail.v2beta.SearchRequest.boost_spec] - for more details. - - This field is a member of `oneof`_ ``_indexable``. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - numbers = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - searchable = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - indexable = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - -class FulfillmentInfo(proto.Message): - r"""Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - Attributes: - type_ (str): - The fulfillment type, including commonly used types (such as - pickup in store and same day delivery), and custom types. - Customers have to map custom types to their display names - before rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - place_ids (Sequence[str]): - The IDs for this - [type][google.cloud.retail.v2beta.FulfillmentInfo.type], - such as the store IDs for - [FulfillmentInfo.type.pickup-in-store][google.cloud.retail.v2beta.FulfillmentInfo.type] - or the region IDs for - [FulfillmentInfo.type.same-day-delivery][google.cloud.retail.v2beta.FulfillmentInfo.type]. - - A maximum of 3000 values are allowed. Each value must be a - string with a length limit of 30 characters, matching the - pattern ``[a-zA-Z0-9_-]+``, such as "store1" or "REGION-2". - Otherwise, an INVALID_ARGUMENT error is returned. - """ - - type_ = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class Image(proto.Message): - r"""[Product][google.cloud.retail.v2beta.Product] image. Recommendations - AI and Retail Search do not use product images to improve prediction - and search results. However, product images can be returned in - results, and are shown in prediction or search previews in the - console. - - Attributes: - uri (str): - Required. URI of the image. - - This field must be a valid UTF-8 encoded URI with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - height (int): - Height of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - width (int): - Width of the image in number of pixels. - - This field must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - height = proto.Field( - proto.INT32, - number=2, - ) - width = proto.Field( - proto.INT32, - number=3, - ) - - -class Interval(proto.Message): - r"""A floating point interval. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - minimum (float): - Inclusive lower bound. - - This field is a member of `oneof`_ ``min``. - exclusive_minimum (float): - Exclusive lower bound. - - This field is a member of `oneof`_ ``min``. - maximum (float): - Inclusive upper bound. - - This field is a member of `oneof`_ ``max``. - exclusive_maximum (float): - Exclusive upper bound. - - This field is a member of `oneof`_ ``max``. - """ - - minimum = proto.Field( - proto.DOUBLE, - number=1, - oneof='min', - ) - exclusive_minimum = proto.Field( - proto.DOUBLE, - number=2, - oneof='min', - ) - maximum = proto.Field( - proto.DOUBLE, - number=3, - oneof='max', - ) - exclusive_maximum = proto.Field( - proto.DOUBLE, - number=4, - oneof='max', - ) - - -class PriceInfo(proto.Message): - r"""The price information of a - [Product][google.cloud.retail.v2beta.Product]. - - Attributes: - currency_code (str): - The 3-letter currency code defined in `ISO - 4217 `__. - - If this field is an unrecognizable currency code, an - INVALID_ARGUMENT error is returned. - - The - [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s with the same - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] - must share the same - [currency_code][google.cloud.retail.v2beta.PriceInfo.currency_code]. - Otherwise, a FAILED_PRECONDITION error is returned. - price (float): - Price of the product. - - Google Merchant Center property - `price `__. - Schema.org property - `Offer.price `__. - original_price (float): - Price of the product without any discount. If zero, by - default set to be the - [price][google.cloud.retail.v2beta.PriceInfo.price]. - cost (float): - The costs associated with the sale of a particular product. - Used for gross profit reporting. - - - Profit = - [price][google.cloud.retail.v2beta.PriceInfo.price] - - [cost][google.cloud.retail.v2beta.PriceInfo.cost] - - Google Merchant Center property - `cost_of_goods_sold `__. - price_effective_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2beta.PriceInfo.price] starts - to be effective. This can be set as a future timestamp, and - the [price][google.cloud.retail.v2beta.PriceInfo.price] is - only used for search after - [price_effective_time][google.cloud.retail.v2beta.PriceInfo.price_effective_time]. - If so, the - [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - is used before - [price_effective_time][google.cloud.retail.v2beta.PriceInfo.price_effective_time]. - - Do not set if - [price][google.cloud.retail.v2beta.PriceInfo.price] is - always effective because it will cause additional latency - during search. - price_expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the - [price][google.cloud.retail.v2beta.PriceInfo.price] stops to - be effective. The - [price][google.cloud.retail.v2beta.PriceInfo.price] is used - for search before - [price_expire_time][google.cloud.retail.v2beta.PriceInfo.price_expire_time]. - If this field is set, the - [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - must be set and - [original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - is used after - [price_expire_time][google.cloud.retail.v2beta.PriceInfo.price_expire_time]. - - Do not set if - [price][google.cloud.retail.v2beta.PriceInfo.price] is - always effective because it will cause additional latency - during search. - price_range (google.cloud.retail_v2beta.types.PriceInfo.PriceRange): - Output only. The price range of all the child - [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s grouped - together on the - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]. Only - populated for - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct]. - Do not set this field in API requests. - """ - - class PriceRange(proto.Message): - r"""The price range of all - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] having the same - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. - - Attributes: - price (google.cloud.retail_v2beta.types.Interval): - The inclusive - [Product.pricing_info.price][google.cloud.retail.v2beta.PriceInfo.price] - interval of all - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] having the - same - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. - original_price (google.cloud.retail_v2beta.types.Interval): - The inclusive - [Product.pricing_info.original_price][google.cloud.retail.v2beta.PriceInfo.original_price] - internal of all - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] having the - same - [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id]. - """ - - price = proto.Field( - proto.MESSAGE, - number=1, - message='Interval', - ) - original_price = proto.Field( - proto.MESSAGE, - number=2, - message='Interval', - ) - - currency_code = proto.Field( - proto.STRING, - number=1, - ) - price = proto.Field( - proto.FLOAT, - number=2, - ) - original_price = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - price_effective_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - price_expire_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - price_range = proto.Field( - proto.MESSAGE, - number=7, - message=PriceRange, - ) - - -class Rating(proto.Message): - r"""The rating of a [Product][google.cloud.retail.v2beta.Product]. - - Attributes: - rating_count (int): - The total number of ratings. This value is independent of - the value of - [rating_histogram][google.cloud.retail.v2beta.Rating.rating_histogram]. - - This value must be nonnegative. Otherwise, an - INVALID_ARGUMENT error is returned. - average_rating (float): - The average rating of the - [Product][google.cloud.retail.v2beta.Product]. - - The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT - error is returned. - rating_histogram (Sequence[int]): - List of rating counts per rating value (index = rating - 1). - The list is empty if there is no rating. If the list is - non-empty, its size is always 5. Otherwise, an - INVALID_ARGUMENT error is returned. - - For example, [41, 14, 13, 47, 303]. It means that the - [Product][google.cloud.retail.v2beta.Product] got 41 ratings - with 1 star, 14 ratings with 2 star, and so on. - """ - - rating_count = proto.Field( - proto.INT32, - number=1, - ) - average_rating = proto.Field( - proto.FLOAT, - number=2, - ) - rating_histogram = proto.RepeatedField( - proto.INT32, - number=3, - ) - - -class UserInfo(proto.Message): - r"""Information of an end user. - - Attributes: - user_id (str): - Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. - - Always use a hashed value for this ID. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - ip_address (str): - The end user's IP address. This field is used to extract - location information for personalization. - - This field must be either an IPv4 address (e.g. - "104.133.9.80") or an IPv6 address (e.g. - "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an - INVALID_ARGUMENT error is returned. - - This should not be set when: - - - setting - [SearchRequest.user_info][google.cloud.retail.v2beta.SearchRequest.user_info]. - - using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2beta.UserInfo.direct_user_request] - is set. - user_agent (str): - User agent as included in the HTTP header. Required for - getting - [SearchResponse.sponsored_results][google.cloud.retail.v2beta.SearchResponse.sponsored_results]. - - The field must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This should not be set when using the client side event - reporting with GTM or JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent] - or if - [direct_user_request][google.cloud.retail.v2beta.UserInfo.direct_user_request] - is set. - direct_user_request (bool): - True if the request is made directly from the end user, in - which case the - [ip_address][google.cloud.retail.v2beta.UserInfo.ip_address] - and - [user_agent][google.cloud.retail.v2beta.UserInfo.user_agent] - can be populated from the HTTP request. This flag should be - set only if the API request is made directly from the end - user such as a mobile app (and not if a gateway or a server - is processing and pushing the user events). - - This should not be set when using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.retail.v2beta.UserEventService.CollectUserEvent]. - """ - - user_id = proto.Field( - proto.STRING, - number=1, - ) - ip_address = proto.Field( - proto.STRING, - number=2, - ) - user_agent = proto.Field( - proto.STRING, - number=3, - ) - direct_user_request = proto.Field( - proto.BOOL, - number=4, - ) - - -class LocalInventory(proto.Message): - r"""The inventory information at a place (e.g. a store) - identified by a place ID. - - Attributes: - place_id (str): - The place ID for the current set of inventory - information. - price_info (google.cloud.retail_v2beta.types.PriceInfo): - Product price and cost information. - - Google Merchant Center property - `price `__. - attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): - Additional local inventory attributes, for example, store - name, promotion tags, etc. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - At most 30 attributes are allowed. - - The key must be a UTF-8 encoded string with a length - limit of 32 characters. - - The key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, key0LikeThis - or KEY_1_LIKE_THIS. - - The attribute values must be of the same type (text or - number). - - Only 1 value is allowed for each attribute. - - For text values, the length limit is 256 UTF-8 - characters. - - The attribute does not support search. The ``searchable`` - field should be unset or set to false. - - The max summed total bytes of custom attribute keys and - values per product is 5MiB. - fulfillment_types (Sequence[str]): - Input only. Supported fulfillment types. Valid fulfillment - type values include commonly used types (such as pickup in - store and same day delivery), and custom types. Customers - have to map custom types to their display names before - rendering UI. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - All the elements must be distinct. Otherwise, an - INVALID_ARGUMENT error is returned. - """ - - place_id = proto.Field( - proto.STRING, - number=1, - ) - price_info = proto.Field( - proto.MESSAGE, - number=2, - message='PriceInfo', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='CustomAttribute', - ) - fulfillment_types = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py deleted file mode 100644 index 47e39772..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/completion_service.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'CompleteQueryRequest', - 'CompleteQueryResponse', - }, -) - - -class CompleteQueryRequest(proto.Message): - r"""Auto-complete parameters. - - Attributes: - catalog (str): - Required. Catalog for which the completion is performed. - - Full resource name of catalog, such as - ``projects/*/locations/global/catalogs/default_catalog``. - query (str): - Required. The query used to generate - suggestions. - The maximum number of allowed characters is 255. - visitor_id (str): - Required field. A unique identifier for tracking visitors. - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - language_codes (Sequence[str]): - The language filters applied to the output suggestions. If - set, it should contain the language of the query. If not - set, suggestions are returned without considering language - restrictions. This is the BCP-47 language code, such as - "en-US" or "sr-Latn". For more information, see `Tags for - Identifying - Languages `__. The - maximum number of language codes is 3. - device_type (str): - The device type context for completion suggestions. It is - useful to apply different suggestions on different device - types, e.g. ``DESKTOP``, ``MOBILE``. If it is empty, the - suggestions are across all device types. - - Supported formats: - - - ``UNKNOWN_DEVICE_TYPE`` - - - ``DESKTOP`` - - - ``MOBILE`` - - - A customized string starts with ``OTHER_``, e.g. - ``OTHER_IPHONE``. - dataset (str): - Determines which dataset to use for fetching completion. - "user-data" will use the imported dataset through - [CompletionService.ImportCompletionData][google.cloud.retail.v2beta.CompletionService.ImportCompletionData]. - "cloud-retail" will use the dataset generated by cloud - retail based on user events. If leave empty, it will use the - "user-data". - - Current supported values: - - - user-data - - - cloud-retail This option requires additional - allowlisting. Before using cloud-retail, contact Cloud - Retail support team first. - max_suggestions (int): - Completion max suggestions. If left unset or set to 0, then - will fallback to the configured value - [CompletionConfig.max_suggestions][google.cloud.retail.v2beta.CompletionConfig.max_suggestions]. - - The maximum allowed max suggestions is 20. If it is set - higher, it will be capped by 20. - """ - - catalog = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - visitor_id = proto.Field( - proto.STRING, - number=7, - ) - language_codes = proto.RepeatedField( - proto.STRING, - number=3, - ) - device_type = proto.Field( - proto.STRING, - number=4, - ) - dataset = proto.Field( - proto.STRING, - number=6, - ) - max_suggestions = proto.Field( - proto.INT32, - number=5, - ) - - -class CompleteQueryResponse(proto.Message): - r"""Response of the auto-complete query. - - Attributes: - completion_results (Sequence[google.cloud.retail_v2beta.types.CompleteQueryResponse.CompletionResult]): - Results of the matching suggestions. The - result list is ordered and the first result is - top suggestion. - attribution_token (str): - A unique complete token. This should be included in the - [UserEvent.completion_detail][google.cloud.retail.v2beta.UserEvent.completion_detail] - for search events resulting from this completion, which - enables accurate attribution of complete model performance. - recent_search_results (Sequence[google.cloud.retail_v2beta.types.CompleteQueryResponse.RecentSearchResult]): - Matched recent searches of this user. The maximum number of - recent searches is 10. This field is a restricted feature. - Contact Retail Search support team if you are interested in - enabling it. - - This feature is only available when - [CompleteQueryRequest.visitor_id][google.cloud.retail.v2beta.CompleteQueryRequest.visitor_id] - field is set and - [UserEvent][google.cloud.retail.v2beta.UserEvent] is - imported. The recent searches satisfy the follow rules: - - - They are ordered from latest to oldest. - - They are matched with - [CompleteQueryRequest.query][google.cloud.retail.v2beta.CompleteQueryRequest.query] - case insensitively. - - They are transformed to lower cases. - - They are UTF-8 safe. - - Recent searches are deduplicated. More recent searches will - be reserved when duplication happens. - """ - - class CompletionResult(proto.Message): - r"""Resource that represents completion results. - - Attributes: - suggestion (str): - The suggestion for the query. - attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): - Custom attributes for the suggestion term. - - - For "user-data", the attributes are additional custom - attributes ingested through BigQuery. - - For "cloud-retail", the attributes are product attributes - generated by Cloud Retail. - """ - - suggestion = proto.Field( - proto.STRING, - number=1, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=common.CustomAttribute, - ) - - class RecentSearchResult(proto.Message): - r"""Recent search of this user. - - Attributes: - recent_search (str): - The recent search query. - """ - - recent_search = proto.Field( - proto.STRING, - number=1, - ) - - completion_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=CompletionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - recent_search_results = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=RecentSearchResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py deleted file mode 100644 index 0c7cdc3d..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'Control', - }, -) - - -class Control(proto.Message): - r"""Configures dynamic serving time metadata that is used to pre - and post process search/recommendation model results. - - 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: - facet_spec (google.cloud.retail_v2beta.types.SearchRequest.FacetSpec): - A facet specification to perform faceted - search. - - This field is a member of `oneof`_ ``control``. - rule (google.cloud.retail_v2beta.types.Rule): - A rule control - a condition-action pair. - Enacts a set action when the condition is - triggered. For example: Boost "gShoe" when query - full matches "Running Shoes". - - This field is a member of `oneof`_ ``control``. - name (str): - Immutable. Fully qualified name - projects/\ */locations/global/catalogs/*/controls/\* - display_name (str): - Required. The human readable control display name. Used in - Retail UI. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is thrown. - associated_serving_config_ids (Sequence[str]): - Output only. List of serving configuration - ids that that are associated with this control. - Note the association is managed via the - ServingConfig, this is an output only - denormalizeed view. Assumed to be in the same - catalog. - solution_types (Sequence[google.cloud.retail_v2beta.types.SolutionType]): - Required. Immutable. The solution types that the serving - config is used for. Currently we support setting only one - type of solution at creation time. - - Only ``SOLUTION_TYPE_SEARCH`` value is supported at the - moment. If no solution type is provided at creation time, - will default to SOLUTION_TYPE_SEARCH. - """ - - facet_spec = proto.Field( - proto.MESSAGE, - number=3, - oneof='control', - message=search_service.SearchRequest.FacetSpec, - ) - rule = proto.Field( - proto.MESSAGE, - number=4, - oneof='control', - message=common.Rule, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - associated_serving_config_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - solution_types = proto.RepeatedField( - proto.ENUM, - number=6, - enum=common.SolutionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py deleted file mode 100644 index 17120bb5..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/control_service.py +++ /dev/null @@ -1,197 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import control as gcr_control -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'CreateControlRequest', - 'UpdateControlRequest', - 'DeleteControlRequest', - 'GetControlRequest', - 'ListControlsRequest', - 'ListControlsResponse', - }, -) - - -class CreateControlRequest(proto.Message): - r"""Request for CreateControl method. - - Attributes: - parent (str): - Required. Full resource name of parent catalog. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - control (google.cloud.retail_v2beta.types.Control): - Required. The Control to create. - control_id (str): - Required. The ID to use for the Control, which will become - the final component of the Control's resource name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-_/. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - control = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_control.Control, - ) - control_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateControlRequest(proto.Message): - r"""Request for UpdateControl method. - - Attributes: - control (google.cloud.retail_v2beta.types.Control): - Required. The Control to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Control][google.cloud.retail.v2beta.Control] to update. The - following are NOT supported: - - - [Control.name][google.cloud.retail.v2beta.Control.name] - - If not set or empty, all supported fields are updated. - """ - - control = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_control.Control, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteControlRequest(proto.Message): - r"""Request for DeleteControl method. - - Attributes: - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetControlRequest(proto.Message): - r"""Request for GetControl method. - - Attributes: - name (str): - Required. The resource name of the Control to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListControlsRequest(proto.Message): - r"""Request for ListControls method. - - Attributes: - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - page_size (int): - Optional. Maximum number of results to - return. If unspecified, defaults to 50. Max - allowed value is 1000. - page_token (str): - Optional. A page token, received from a previous - ``ListControls`` call. Provide this to retrieve the - subsequent page. - filter (str): - Optional. A filter to apply on the list results. Supported - features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2beta.ListControlsRequest.filter] - is unset. - - List controls that are used in a single ServingConfig: - 'serving_config = "boosted_home_page_cvr"' - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListControlsResponse(proto.Message): - r"""Response for ListControls method. - - Attributes: - controls (Sequence[google.cloud.retail_v2beta.types.Control]): - All the Controls for a given catalog. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - controls = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_control.Control, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py deleted file mode 100644 index b020964a..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/export_config.py +++ /dev/null @@ -1,134 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'ExportErrorsConfig', - 'ExportMetadata', - 'ExportProductsResponse', - 'ExportUserEventsResponse', - }, -) - - -class ExportErrorsConfig(proto.Message): - r"""Configuration of destination for Export related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage path for import errors. This must be an - empty, existing Cloud Storage bucket. Export errors will be - written to a file in this bucket, one per line, as a - JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ExportMetadata(proto.Message): - r"""Metadata related to the progress of the Export operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class ExportProductsResponse(proto.Message): - r"""Response of the ExportProductsRequest. If the long running - operation is done, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2beta.types.ExportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExportErrorsConfig', - ) - - -class ExportUserEventsResponse(proto.Message): - r"""Response of the ExportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2beta.types.ExportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExportErrorsConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py deleted file mode 100644 index a32de943..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/import_config.py +++ /dev/null @@ -1,691 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import user_event -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'GcsSource', - 'BigQuerySource', - 'ProductInlineSource', - 'UserEventInlineSource', - 'ImportErrorsConfig', - 'ImportProductsRequest', - 'ImportUserEventsRequest', - 'ImportCompletionDataRequest', - 'ProductInputConfig', - 'UserEventInputConfig', - 'CompletionDataInputConfig', - 'ImportMetadata', - 'ImportProductsResponse', - 'ImportUserEventsResponse', - 'UserEventImportSummary', - 'ImportCompletionDataResponse', - }, -) - - -class GcsSource(proto.Message): - r"""Google Cloud Storage location for input content. - format. - - Attributes: - input_uris (Sequence[str]): - Required. Google Cloud Storage URIs to input files. URI can - be up to 2000 characters long. URIs can match the full - object path (for example, - ``gs://bucket/directory/object.json``) or a pattern matching - one or more files, such as ``gs://bucket/directory/*.json``. - A request can contain at most 100 files, and each file can - be up to 2 GB. See `Importing product - information `__ - for the expected file format and setup instructions. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2beta.Product] per line. - Each product must have a valid - [Product.id][google.cloud.retail.v2beta.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2beta.UserEvent] per - line. - - ``user_event_ga360``: Using - https://support.google.com/analytics/answer/3437719. - - Supported values for control imports: - - - 'control' (default): One JSON - [Control][google.cloud.retail.v2beta.Control] per line. - - Supported values for catalog attribute imports: - - - 'catalog_attribute' (default): One CSV - [CatalogAttribute][google.cloud.retail.v2beta.CatalogAttribute] - per line. - """ - - input_uris = proto.RepeatedField( - proto.STRING, - number=1, - ) - data_schema = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""BigQuery source import data from. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - partition_date (google.type.date_pb2.Date): - BigQuery time partitioned table's \_PARTITIONDATE in - YYYY-MM-DD format. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2beta.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - - This field is a member of `oneof`_ ``partition``. - project_id (str): - The project ID (can be project # or ID) that - the BigQuery source is in with a length limit of - 128 characters. If not specified, inherits the - project ID from the parent request. - dataset_id (str): - Required. The BigQuery data set to copy the - data from with a length limit of 1,024 - characters. - table_id (str): - Required. The BigQuery table to copy the data - from with a length limit of 1,024 characters. - gcs_staging_dir (str): - Intermediate Cloud Storage directory used for - the import with a length limit of 2,000 - characters. Can be specified if one wants to - have the BigQuery export to a specific Cloud - Storage directory. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for product imports: - - - ``product`` (default): One JSON - [Product][google.cloud.retail.v2beta.Product] per line. - Each product must have a valid - [Product.id][google.cloud.retail.v2beta.Product.id]. - - ``product_merchant_center``: See `Importing catalog data - from Merchant - Center `__. - - Supported values for user events imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.retail.v2beta.UserEvent] per - line. - - ``user_event_ga360``: The schema is available here: - https://support.google.com/analytics/answer/3437719. - - ``user_event_ga4``: This feature is in private preview. - Please contact the support team for importing Google - Analytics 4 events. The schema is available here: - https://support.google.com/analytics/answer/7029846. - - Supported values for auto-completion imports: - - - ``suggestions`` (default): One JSON completion suggestion - per line. - - ``denylist``: One JSON deny suggestion per line. - - ``allowlist``: One JSON allow suggestion per line. - """ - - partition_date = proto.Field( - proto.MESSAGE, - number=6, - oneof='partition', - message=date_pb2.Date, - ) - project_id = proto.Field( - proto.STRING, - number=5, - ) - dataset_id = proto.Field( - proto.STRING, - number=1, - ) - table_id = proto.Field( - proto.STRING, - number=2, - ) - gcs_staging_dir = proto.Field( - proto.STRING, - number=3, - ) - data_schema = proto.Field( - proto.STRING, - number=4, - ) - - -class ProductInlineSource(proto.Message): - r"""The inline source for the input config for ImportProducts - method. - - Attributes: - products (Sequence[google.cloud.retail_v2beta.types.Product]): - Required. A list of products to update/create. Each product - must have a valid - [Product.id][google.cloud.retail.v2beta.Product.id]. - Recommended max of 100 items. - """ - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=product.Product, - ) - - -class UserEventInlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (Sequence[google.cloud.retail_v2beta.types.UserEvent]): - Required. A list of user events to import. - Recommended max of 10k items. - """ - - user_events = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - -class ImportErrorsConfig(proto.Message): - r"""Configuration of destination for Import related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Google Cloud Storage prefix for import errors. This must be - an empty, existing Cloud Storage directory. Import errors - will be written to sharded files in this directory, one per - line, as a JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportProductsRequest(proto.Message): - r"""Request message for Import methods. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`` - - If no updateMask is specified, requires products.create - permission. If updateMask is specified, requires - products.update permission. - request_id (str): - Deprecated. This field has no effect. - input_config (google.cloud.retail_v2beta.types.ProductInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - imported 'products' to update. If not set, will - by default update all fields. - reconciliation_mode (google.cloud.retail_v2beta.types.ImportProductsRequest.ReconciliationMode): - The mode of reconciliation between existing products and the - products to be imported. Defaults to - [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2beta.ImportProductsRequest.ReconciliationMode.INCREMENTAL]. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - - Only supported when - [ImportProductsRequest.reconciliation_mode][google.cloud.retail.v2beta.ImportProductsRequest.reconciliation_mode] - is set to ``FULL``. - """ - class ReconciliationMode(proto.Enum): - r"""Indicates how imported products are reconciled with the - existing products created or imported before. - """ - RECONCILIATION_MODE_UNSPECIFIED = 0 - INCREMENTAL = 1 - FULL = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - request_id = proto.Field( - proto.STRING, - number=6, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='ProductInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - reconciliation_mode = proto.Field( - proto.ENUM, - number=5, - enum=ReconciliationMode, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=7, - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog`` - input_config (google.cloud.retail_v2beta.types.UserEventInputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): - The desired location of errors incurred - during the Import. Cannot be set for inline user - event imports. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='UserEventInputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=3, - message='ImportErrorsConfig', - ) - - -class ImportCompletionDataRequest(proto.Message): - r"""Request message for ImportCompletionData methods. - - Attributes: - parent (str): - Required. The catalog which the suggestions dataset belongs - to. - - Format: - ``projects/1234/locations/global/catalogs/default_catalog``. - input_config (google.cloud.retail_v2beta.types.CompletionDataInputConfig): - Required. The desired input location of the - data. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - input_config = proto.Field( - proto.MESSAGE, - number=2, - message='CompletionDataInputConfig', - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=3, - ) - - -class ProductInputConfig(proto.Message): - r"""The input config source for products. - - 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: - product_inline_source (google.cloud.retail_v2beta.types.ProductInlineSource): - The Inline source for the input content for - products. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2beta.types.GcsSource): - Google Cloud Storage location for the input - content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - product_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='ProductInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class UserEventInputConfig(proto.Message): - r"""The input config source for user events. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - user_event_inline_source (google.cloud.retail_v2beta.types.UserEventInlineSource): - Required. The Inline source for the input - content for UserEvents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.retail_v2beta.types.GcsSource): - Required. Google Cloud Storage location for - the input content. - - This field is a member of `oneof`_ ``source``. - big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): - Required. BigQuery input source. - - This field is a member of `oneof`_ ``source``. - """ - - user_event_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='UserEventInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - big_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='BigQuerySource', - ) - - -class CompletionDataInputConfig(proto.Message): - r"""The input config source for completion data. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - big_query_source (google.cloud.retail_v2beta.types.BigQuerySource): - Required. BigQuery input source. - Add the IAM permission "BigQuery Data Viewer" - for - cloud-retail-customer-data-access@system.gserviceaccount.com - before using this feature otherwise an error is - thrown. - - This field is a member of `oneof`_ ``source``. - """ - - big_query_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='BigQuerySource', - ) - - -class ImportMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - request_id (str): - Deprecated. This field is never set. - notification_pubsub_topic (str): - Pub/Sub topic for receiving notification. If this field is - set, when the import is finished, a notification will be - sent to specified Pub/Sub topic. The message data will be - JSON string of a [Operation][google.longrunning.Operation]. - Format of the Pub/Sub topic is - ``projects/{project}/topics/{topic}``. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=3, - ) - failure_count = proto.Field( - proto.INT64, - number=4, - ) - request_id = proto.Field( - proto.STRING, - number=5, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=6, - ) - - -class ImportProductsResponse(proto.Message): - r"""Response of the - [ImportProductsRequest][google.cloud.retail.v2beta.ImportProductsRequest]. - If the long running operation is done, then this message is returned - by the google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.retail_v2beta.types.ImportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - import_summary (google.cloud.retail_v2beta.types.UserEventImportSummary): - Aggregated statistics of user event import - status. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - import_summary = proto.Field( - proto.MESSAGE, - number=3, - message='UserEventImportSummary', - ) - - -class UserEventImportSummary(proto.Message): - r"""A summary of import result. The UserEventImportSummary - summarizes the import status for user events. - - Attributes: - joined_events_count (int): - Count of user events imported with complete - existing catalog information. - unjoined_events_count (int): - Count of user events imported, but with - catalog information not found in the imported - catalog. - """ - - joined_events_count = proto.Field( - proto.INT64, - number=1, - ) - unjoined_events_count = proto.Field( - proto.INT64, - number=2, - ) - - -class ImportCompletionDataResponse(proto.Message): - r"""Response of the - [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest]. - 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 (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py deleted file mode 100644 index f31ba819..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/prediction_service.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import user_event as gcr_user_event -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'PredictRequest', - 'PredictResponse', - }, -) - - -class PredictRequest(proto.Message): - r"""Request message for Predict method. - - Attributes: - placement (str): - Required. Full resource name of the format: - {name=projects/*/locations/global/catalogs/default_catalog/placements/*} - The ID of the Recommendations AI placement. Before you can - request predictions from your model, you must create at - least one placement for it. For more information, see - `Managing - placements `__. - - The full list of available placements can be seen at - https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements - user_event (google.cloud.retail_v2beta.types.UserEvent): - Required. Context about the user, what they - are looking at and what action they took to - trigger the predict request. Note that this user - event detail won't be ingested to userEvent - logs. Thus, a separate userEvent write request - is required for event logging. - page_size (int): - Maximum number of results to return per page. - Set this property to the number of prediction - results needed. If zero, the service will choose - a reasonable default. The maximum allowed value - is 100. Values above 100 will be coerced to 100. - page_token (str): - The previous PredictResponse.next_page_token. - filter (str): - Filter for restricting prediction results with a length - limit of 5,000 characters. Accepts values for tags and the - ``filterOutOfStockItems`` flag. - - - Tag expressions. Restricts predictions to products that - match all of the specified tags. Boolean operators ``OR`` - and ``NOT`` are supported if the expression is enclosed - in parentheses, and must be separated from the tag values - by a space. ``-"tagA"`` is also supported and is - equivalent to ``NOT "tagA"``. Tag values must be double - quoted UTF-8 encoded strings with a size limit of 1,000 - characters. - - Note: "Recently viewed" models don't support tag - filtering at the moment. - - - filterOutOfStockItems. Restricts predictions to products - that do not have a stockState value of OUT_OF_STOCK. - - Examples: - - - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT - "promotional") - - filterOutOfStockItems tag=(-"promotional") - - filterOutOfStockItems - - If your filter blocks all prediction results, the API will - return generic (unfiltered) popular products. If you only - want results strictly matching the filters, set - ``strictFiltering`` to True in ``PredictRequest.params`` to - receive empty results instead. Note that the API will never - return items with storageStatus of "EXPIRED" or "DELETED" - regardless of filter choices. - validate_only (bool): - Use validate only mode for this prediction - query. If set to true, a dummy model will be - used that returns arbitrary products. Note that - the validate only mode should only be used for - testing the API, or if the model is not ready. - params (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional domain specific parameters for the predictions. - - Allowed values: - - - ``returnProduct``: Boolean. If set to true, the - associated product object will be returned in the - ``results.metadata`` field in the prediction response. - - ``returnScore``: Boolean. If set to true, the prediction - 'score' corresponding to each returned product will be - set in the ``results.metadata`` field in the prediction - response. The given 'score' indicates the probability of - an product being clicked/purchased given the user's - context and history. - - ``strictFiltering``: Boolean. True by default. If set to - false, the service will return generic (unfiltered) - popular products instead of empty if your filter blocks - all prediction results. - - ``priceRerankLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of - {'no-price-reranking', 'low-price-reranking', - 'medium-price-reranking', 'high-price-reranking'}. This - gives request-level control and adjusts prediction - results based on product price. - - ``diversityLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of {'no-diversity', - 'low-diversity', 'medium-diversity', 'high-diversity', - 'auto-diversity'}. This gives request-level control and - adjusts prediction results based on product category. - labels (Mapping[str, str]): - The labels applied to a resource must meet the following - requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters, and cannot be empty. Values can - be empty, and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - """ - - placement = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - validate_only = proto.Field( - proto.BOOL, - number=6, - ) - params = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class PredictResponse(proto.Message): - r"""Response message for predict method. - - Attributes: - results (Sequence[google.cloud.retail_v2beta.types.PredictResponse.PredictionResult]): - A list of recommended products. The order - represents the ranking (from the most relevant - product to the least). - attribution_token (str): - A unique attribution token. This should be included in the - [UserEvent][google.cloud.retail.v2beta.UserEvent] logs - resulting from this recommendation, which enables accurate - attribution of recommendation model performance. - missing_ids (Sequence[str]): - IDs of products in the request that were - missing from the inventory. - validate_only (bool): - True if the validateOnly property was set in - the request. - """ - - class PredictionResult(proto.Message): - r"""PredictionResult represents the recommendation prediction - results. - - Attributes: - id (str): - ID of the recommended product - metadata (Mapping[str, google.protobuf.struct_pb2.Value]): - Additional product metadata / annotations. - - Possible values: - - - ``product``: JSON representation of the product. Will be - set if ``returnProduct`` is set to true in - ``PredictRequest.params``. - - ``score``: Prediction score in double value. Will be set - if ``returnScore`` is set to true in - ``PredictRequest.params``. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - metadata = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=PredictionResult, - ) - attribution_token = proto.Field( - proto.STRING, - number=2, - ) - missing_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py deleted file mode 100644 index bd0de773..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product.py +++ /dev/null @@ -1,705 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import promotion -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'Product', - }, -) - - -class Product(proto.Message): - r"""Product captures all metadata information of items to be - recommended or searched. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - expire_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this product becomes unavailable for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - If it is set, the - [Product][google.cloud.retail.v2beta.Product] is not - available for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - after - [expire_time][google.cloud.retail.v2beta.Product.expire_time]. - However, the product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - [expire_time][google.cloud.retail.v2beta.Product.expire_time] - must be later than - [available_time][google.cloud.retail.v2beta.Product.available_time] - and - [publish_time][google.cloud.retail.v2beta.Product.publish_time], - otherwise an INVALID_ARGUMENT error is thrown. - - Corresponding properties: Google Merchant Center property - `expiration_date `__. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Input only. The TTL (time to live) of the product. - - If it is set, it must be a non-negative value, and - [expire_time][google.cloud.retail.v2beta.Product.expire_time] - is set as current timestamp plus - [ttl][google.cloud.retail.v2beta.Product.ttl]. The derived - [expire_time][google.cloud.retail.v2beta.Product.expire_time] - is returned in the output and - [ttl][google.cloud.retail.v2beta.Product.ttl] is left blank - when retrieving the - [Product][google.cloud.retail.v2beta.Product]. - - If it is set, the product is not available for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - after current timestamp plus - [ttl][google.cloud.retail.v2beta.Product.ttl]. However, the - product can still be retrieved by - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct] - and - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts]. - - This field is a member of `oneof`_ ``expiration``. - name (str): - Immutable. Full resource name of the product, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id``. - id (str): - Immutable. [Product][google.cloud.retail.v2beta.Product] - identifier, which is the final component of - [name][google.cloud.retail.v2beta.Product.name]. For - example, this field is "id_1", if - [name][google.cloud.retail.v2beta.Product.name] is - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1``. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `id `__. - Schema.org property - `Product.sku `__. - type_ (google.cloud.retail_v2beta.types.Product.Type): - Immutable. The type of the product. Default to - [Catalog.product_level_config.ingestion_product_type][google.cloud.retail.v2beta.ProductLevelConfig.ingestion_product_type] - if unset. - primary_product_id (str): - Variant group identifier. Must be an - [id][google.cloud.retail.v2beta.Product.id], with the same - parent branch with this product. Otherwise, an error is - thrown. - - For - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]s, this field - can only be empty or set to the same value as - [id][google.cloud.retail.v2beta.Product.id]. - - For VARIANT [Product][google.cloud.retail.v2beta.Product]s, - this field cannot be empty. A maximum of 2,000 products are - allowed to share the same - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `item_group_id `__. - Schema.org property - `Product.inProductGroupWithID `__. - collection_member_ids (Sequence[str]): - The [id][google.cloud.retail.v2beta.Product.id] of the - collection members when - [type][google.cloud.retail.v2beta.Product.type] is - [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION]. - - Non-existent product ids are allowed. The - [type][google.cloud.retail.v2beta.Product.type] of the - members must be either - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - or - [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - otherwise and INVALID_ARGUMENT error is thrown. Should not - set it for other types. A maximum of 1000 values are - allowed. Otherwise, an INVALID_ARGUMENT error is return. - gtin (str): - The Global Trade Item Number (GTIN) of the product. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - This field must be a Unigram. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `gtin `__. - Schema.org property - `Product.isbn `__, - `Product.gtin8 `__, - `Product.gtin12 `__, - `Product.gtin13 `__, or - `Product.gtin14 `__. - - If the value is not a valid GTIN, an INVALID_ARGUMENT error - is returned. - categories (Sequence[str]): - Product categories. This field is repeated for supporting - one product belonging to several parallel categories. - Strongly recommended using the full path for better search / - recommendation quality. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - For example, if a shoes product belongs to both ["Shoes & - Accessories" -> "Shoes"] and ["Sports & Fitness" -> - "Athletic Clothing" -> "Shoes"], it could be represented as: - - :: - - "categories": [ - "Shoes & Accessories > Shoes", - "Sports & Fitness > Athletic Clothing > Shoes" - ] - - Must be set for - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] otherwise an - INVALID_ARGUMENT error is returned. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2beta.Product]. Empty values - are not allowed. Each value must be a UTF-8 encoded string - with a length limit of 5,000 characters. Otherwise, an - INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `google_product_category `__. - Schema.org property [Product.category] - (https://schema.org/category). - title (str): - Required. Product title. - - This field must be a UTF-8 encoded string with a length - limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `title `__. - Schema.org property - `Product.name `__. - brands (Sequence[str]): - The brands of the product. - - A maximum of 30 brands are allowed. Each brand must be a - UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `brand `__. - Schema.org property - `Product.brand `__. - description (str): - Product description. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `description `__. - Schema.org property - `Product.description `__. - language_code (str): - Language of the title/description and other string - attributes. Use language tags defined by `BCP - 47 `__. - - For product prediction, this field is ignored and the model - automatically detects the text language. The - [Product][google.cloud.retail.v2beta.Product] can include - text in different languages, but duplicating - [Product][google.cloud.retail.v2beta.Product]s to provide - text in multiple languages can result in degraded model - performance. - - For product search this field is in use. It defaults to - "en-US" if unset. - attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): - Highly encouraged. Extra product attributes to be included. - For example, for products, this could include the store - name, vendor, style, color, etc. These are very strong - signals for recommendation model, thus we highly recommend - providing the attributes here. - - Features that can take on one of a limited number of - possible values. Two types of features can be set are: - - Textual features. some examples would be the brand/maker of - a product, or country of a customer. Numerical features. - Some examples would be the height/weight of a product, or - age of a customer. - - For example: - ``{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }``. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - Max entries count: 200. - - The key must be a UTF-8 encoded string with a length - limit of 128 characters. - - For indexable attribute, the key must match the pattern: - ``[a-zA-Z0-9][a-zA-Z0-9_]*``. For example, - ``key0LikeThis`` or ``KEY_1_LIKE_THIS``. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a - non-empty UTF-8 encoded string with a length limit of 256 - characters. - - For number attributes, at most 400 values are allowed. - tags (Sequence[str]): - Custom tags associated with the product. - - At most 250 values are allowed per - [Product][google.cloud.retail.v2beta.Product]. This value - must be a UTF-8 encoded string with a length limit of 1,000 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This tag can be used for filtering recommendation results by - passing the tag as part of the - [PredictRequest.filter][google.cloud.retail.v2beta.PredictRequest.filter]. - - Corresponding properties: Google Merchant Center property - `custom_label_0–4 `__. - price_info (google.cloud.retail_v2beta.types.PriceInfo): - Product price and cost information. - - Corresponding properties: Google Merchant Center property - `price `__. - rating (google.cloud.retail_v2beta.types.Rating): - The rating of this product. - available_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when this - [Product][google.cloud.retail.v2beta.Product] becomes - available for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - availability (google.cloud.retail_v2beta.types.Product.Availability): - The online availability of the - [Product][google.cloud.retail.v2beta.Product]. Default to - [Availability.IN_STOCK][google.cloud.retail.v2beta.Product.Availability.IN_STOCK]. - - Corresponding properties: Google Merchant Center property - `availability `__. - Schema.org property - `Offer.availability `__. - available_quantity (google.protobuf.wrappers_pb2.Int32Value): - The available quantity of the item. - fulfillment_info (Sequence[google.cloud.retail_v2beta.types.FulfillmentInfo]): - Fulfillment information, such as the store IDs for in-store - pickup or region IDs for different shipping methods. - - All the elements must have distinct - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type]. - Otherwise, an INVALID_ARGUMENT error is returned. - uri (str): - Canonical URL directly linking to the product detail page. - - It is strongly recommended to provide a valid uri for the - product, otherwise the service performance could be - significantly degraded. - - This field must be a UTF-8 encoded string with a length - limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - - Corresponding properties: Google Merchant Center property - `link `__. - Schema.org property `Offer.url `__. - images (Sequence[google.cloud.retail_v2beta.types.Image]): - Product images for the product. We highly recommend putting - the main image first. - - A maximum of 300 images are allowed. - - Corresponding properties: Google Merchant Center property - `image_link `__. - Schema.org property - `Product.image `__. - audience (google.cloud.retail_v2beta.types.Audience): - The target group associated with a given - audience (e.g. male, veterans, car owners, - musicians, etc.) of the product. - color_info (google.cloud.retail_v2beta.types.ColorInfo): - The color of the product. - - Corresponding properties: Google Merchant Center property - `color `__. - Schema.org property - `Product.color `__. - sizes (Sequence[str]): - The size of the product. To represent different size systems - or size types, consider using this format: - [[[size_system:]size_type:]size_value]. - - For example, in "US:MENS:M", "US" represents size system; - "MENS" represents size type; "M" represents size value. In - "GIRLS:27", size system is empty; "GIRLS" represents size - type; "27" represents size value. In "32 inches", both size - system and size type are empty, while size value is "32 - inches". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2beta.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `size `__, - `size_type `__, - and - `size_system `__. - Schema.org property - `Product.size `__. - materials (Sequence[str]): - The material of the product. For example, "leather", - "wooden". - - A maximum of 20 values are allowed. Each value must be a - UTF-8 encoded string with a length limit of 200 characters. - Otherwise, an INVALID_ARGUMENT error is returned. - - Corresponding properties: Google Merchant Center property - `material `__. - Schema.org property - `Product.material `__. - patterns (Sequence[str]): - The pattern or graphic print of the product. For example, - "striped", "polka dot", "paisley". - - A maximum of 20 values are allowed per - [Product][google.cloud.retail.v2beta.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `pattern `__. - Schema.org property - `Product.pattern `__. - conditions (Sequence[str]): - The condition of the product. Strongly encouraged to use the - standard values: "new", "refurbished", "used". - - A maximum of 1 value is allowed per - [Product][google.cloud.retail.v2beta.Product]. Each value - must be a UTF-8 encoded string with a length limit of 128 - characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - Corresponding properties: Google Merchant Center property - `condition `__. - Schema.org property - `Offer.itemCondition `__. - promotions (Sequence[google.cloud.retail_v2beta.types.Promotion]): - The promotions applied to the product. A maximum of 10 - values are allowed per - [Product][google.cloud.retail.v2beta.Product]. Only - [Promotion.promotion_id][google.cloud.retail.v2beta.Promotion.promotion_id] - will be used, other fields will be ignored if set. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the product is published by the retailer - for the first time, which indicates the freshness of the - products. Note that this field is different from - [available_time][google.cloud.retail.v2beta.Product.available_time], - given it purely describes product freshness regardless of - when it is available on search and recommendation. - retrievable_fields (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the - [Product][google.cloud.retail.v2beta.Product]s are returned - in - [SearchResponse][google.cloud.retail.v2beta.SearchResponse]. - - Supported fields for all - [type][google.cloud.retail.v2beta.Product.type]s: - - - [audience][google.cloud.retail.v2beta.Product.audience] - - [availability][google.cloud.retail.v2beta.Product.availability] - - [brands][google.cloud.retail.v2beta.Product.brands] - - [color_info][google.cloud.retail.v2beta.Product.color_info] - - [conditions][google.cloud.retail.v2beta.Product.conditions] - - [gtin][google.cloud.retail.v2beta.Product.gtin] - - [materials][google.cloud.retail.v2beta.Product.materials] - - [name][google.cloud.retail.v2beta.Product.name] - - [patterns][google.cloud.retail.v2beta.Product.patterns] - - [price_info][google.cloud.retail.v2beta.Product.price_info] - - [rating][google.cloud.retail.v2beta.Product.rating] - - [sizes][google.cloud.retail.v2beta.Product.sizes] - - [title][google.cloud.retail.v2beta.Product.title] - - [uri][google.cloud.retail.v2beta.Product.uri] - - Supported fields only for - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION]: - - - [categories][google.cloud.retail.v2beta.Product.categories] - - [description][google.cloud.retail.v2beta.Product.description] - - [images][google.cloud.retail.v2beta.Product.images] - - Supported fields only for - [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT]: - - - Only the first image in - [images][google.cloud.retail.v2beta.Product.images] - - To mark - [attributes][google.cloud.retail.v2beta.Product.attributes] - as retrievable, include paths of the form "attributes.key" - where "key" is the key of a custom attribute, as specified - in - [attributes][google.cloud.retail.v2beta.Product.attributes]. - - For - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - and - [Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION], - the following fields are always returned in - [SearchResponse][google.cloud.retail.v2beta.SearchResponse] - by default: - - - [name][google.cloud.retail.v2beta.Product.name] - - For - [Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT], - the following fields are always returned in by default: - - - [name][google.cloud.retail.v2beta.Product.name] - - [color_info][google.cloud.retail.v2beta.Product.color_info] - - Maximum number of paths is 30. Otherwise, an - INVALID_ARGUMENT error is returned. - - Note: Returning more fields in - [SearchResponse][google.cloud.retail.v2beta.SearchResponse] - may increase response payload size and serving latency. - variants (Sequence[google.cloud.retail_v2beta.types.Product]): - Output only. Product variants grouped together on primary - product which share similar product attributes. It's - automatically grouped by - [primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] - for all the product variants. Only populated for - [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]s. - - Note: This field is OUTPUT_ONLY for - [ProductService.GetProduct][google.cloud.retail.v2beta.ProductService.GetProduct]. - Do not set this field in API requests. - """ - class Type(proto.Enum): - r"""The type of this product.""" - TYPE_UNSPECIFIED = 0 - PRIMARY = 1 - VARIANT = 2 - COLLECTION = 3 - - class Availability(proto.Enum): - r"""Product availability. If this field is unspecified, the - product is assumed to be in stock. - """ - AVAILABILITY_UNSPECIFIED = 0 - IN_STOCK = 1 - OUT_OF_STOCK = 2 - PREORDER = 3 - BACKORDER = 4 - - expire_time = proto.Field( - proto.MESSAGE, - number=16, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl = proto.Field( - proto.MESSAGE, - number=17, - oneof='expiration', - message=duration_pb2.Duration, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - type_ = proto.Field( - proto.ENUM, - number=3, - enum=Type, - ) - primary_product_id = proto.Field( - proto.STRING, - number=4, - ) - collection_member_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - gtin = proto.Field( - proto.STRING, - number=6, - ) - categories = proto.RepeatedField( - proto.STRING, - number=7, - ) - title = proto.Field( - proto.STRING, - number=8, - ) - brands = proto.RepeatedField( - proto.STRING, - number=9, - ) - description = proto.Field( - proto.STRING, - number=10, - ) - language_code = proto.Field( - proto.STRING, - number=11, - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=12, - message=common.CustomAttribute, - ) - tags = proto.RepeatedField( - proto.STRING, - number=13, - ) - price_info = proto.Field( - proto.MESSAGE, - number=14, - message=common.PriceInfo, - ) - rating = proto.Field( - proto.MESSAGE, - number=15, - message=common.Rating, - ) - available_time = proto.Field( - proto.MESSAGE, - number=18, - message=timestamp_pb2.Timestamp, - ) - availability = proto.Field( - proto.ENUM, - number=19, - enum=Availability, - ) - available_quantity = proto.Field( - proto.MESSAGE, - number=20, - message=wrappers_pb2.Int32Value, - ) - fulfillment_info = proto.RepeatedField( - proto.MESSAGE, - number=21, - message=common.FulfillmentInfo, - ) - uri = proto.Field( - proto.STRING, - number=22, - ) - images = proto.RepeatedField( - proto.MESSAGE, - number=23, - message=common.Image, - ) - audience = proto.Field( - proto.MESSAGE, - number=24, - message=common.Audience, - ) - color_info = proto.Field( - proto.MESSAGE, - number=25, - message=common.ColorInfo, - ) - sizes = proto.RepeatedField( - proto.STRING, - number=26, - ) - materials = proto.RepeatedField( - proto.STRING, - number=27, - ) - patterns = proto.RepeatedField( - proto.STRING, - number=28, - ) - conditions = proto.RepeatedField( - proto.STRING, - number=29, - ) - promotions = proto.RepeatedField( - proto.MESSAGE, - number=34, - message=promotion.Promotion, - ) - publish_time = proto.Field( - proto.MESSAGE, - number=33, - message=timestamp_pb2.Timestamp, - ) - retrievable_fields = proto.Field( - proto.MESSAGE, - number=30, - message=field_mask_pb2.FieldMask, - ) - variants = proto.RepeatedField( - proto.MESSAGE, - number=31, - message='Product', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py deleted file mode 100644 index 06a23d13..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/product_service.py +++ /dev/null @@ -1,844 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'CreateProductRequest', - 'GetProductRequest', - 'UpdateProductRequest', - 'DeleteProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'SetInventoryRequest', - 'SetInventoryMetadata', - 'SetInventoryResponse', - 'AddFulfillmentPlacesRequest', - 'AddFulfillmentPlacesMetadata', - 'AddFulfillmentPlacesResponse', - 'AddLocalInventoriesRequest', - 'AddLocalInventoriesMetadata', - 'AddLocalInventoriesResponse', - 'RemoveLocalInventoriesRequest', - 'RemoveLocalInventoriesMetadata', - 'RemoveLocalInventoriesResponse', - 'RemoveFulfillmentPlacesRequest', - 'RemoveFulfillmentPlacesMetadata', - 'RemoveFulfillmentPlacesResponse', - }, -) - - -class CreateProductRequest(proto.Message): - r"""Request message for [CreateProduct][] method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch``. - product (google.cloud.retail_v2beta.types.Product): - Required. The [Product][google.cloud.retail.v2beta.Product] - to create. - product_id (str): - Required. The ID to use for the - [Product][google.cloud.retail.v2beta.Product], which will - become the final component of the - [Product.name][google.cloud.retail.v2beta.Product.name]. - - If the caller does not have permission to create the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - This field must be unique among all - [Product][google.cloud.retail.v2beta.Product]s with the same - [parent][google.cloud.retail.v2beta.CreateProductRequest.parent]. - Otherwise, an ALREADY_EXISTS error is returned. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - product_id = proto.Field( - proto.STRING, - number=3, - ) - - -class GetProductRequest(proto.Message): - r"""Request message for [GetProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the requested - [Product][google.cloud.retail.v2beta.Product] does not - exist, a NOT_FOUND error is returned. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateProductRequest(proto.Message): - r"""Request message for [UpdateProduct][] method. - - Attributes: - product (google.cloud.retail_v2beta.types.Product): - Required. The product to update/create. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not exist and - [allow_missing][google.cloud.retail.v2beta.UpdateProductRequest.allow_missing] - is not set, a NOT_FOUND error is returned. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Product][google.cloud.retail.v2beta.Product] to update. The - immutable and output only fields are NOT supported. If not - set, all supported fields (the fields that are neither - immutable nor output only) are updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - a new [Product][google.cloud.retail.v2beta.Product] will be - created. In this situation, ``update_mask`` is ignored. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteProductRequest(proto.Message): - r"""Request message for [DeleteProduct][] method. - - Attributes: - name (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to delete the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - delete does not exist, a NOT_FOUND error is returned. - - The [Product][google.cloud.retail.v2beta.Product] to delete - can neither be a - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product] member nor a - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] with more than - one - [variants][google.cloud.retail.v2beta.Product.Type.VARIANT]. - Otherwise, an INVALID_ARGUMENT error is returned. - - All inventory information for the named - [Product][google.cloud.retail.v2beta.Product] will be - deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProductsRequest(proto.Message): - r"""Request message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - - Attributes: - parent (str): - Required. The parent branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - Use ``default_branch`` as the branch ID, to list products - under the default branch. - - If the caller does not have permission to list - [Product][google.cloud.retail.v2beta.Product]s under this - branch, regardless of whether or not this branch exists, a - PERMISSION_DENIED error is returned. - page_size (int): - Maximum number of - [Product][google.cloud.retail.v2beta.Product]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 - [ListProductsResponse.next_page_token][google.cloud.retail.v2beta.ListProductsResponse.next_page_token], - received from a previous - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - filter (str): - A filter to apply on the list results. Supported features: - - - List all the products under the parent branch if - [filter][google.cloud.retail.v2beta.ListProductsRequest.filter] - is unset. - - List - [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s sharing - the same - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product]. For - example: ``primary_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2beta.Product]s - bundled in a - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product]. For - example: ``collection_product_id = "some_product_id"`` - - List [Product][google.cloud.retail.v2beta.Product]s with - a partibular type. For example: ``type = "PRIMARY"`` - ``type = "VARIANT"`` ``type = "COLLECTION"`` - - If the field is unrecognizable, an INVALID_ARGUMENT error is - returned. - - If the specified - [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - [Product][google.cloud.retail.v2beta.Product] or - [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] - [Product][google.cloud.retail.v2beta.Product] does not - exist, a NOT_FOUND error is returned. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields of [Product][google.cloud.retail.v2beta.Product] - to return in the responses. If not set or empty, the - following fields are returned: - - - [Product.name][google.cloud.retail.v2beta.Product.name] - - [Product.id][google.cloud.retail.v2beta.Product.id] - - [Product.title][google.cloud.retail.v2beta.Product.title] - - [Product.uri][google.cloud.retail.v2beta.Product.uri] - - [Product.images][google.cloud.retail.v2beta.Product.images] - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.brands][google.cloud.retail.v2beta.Product.brands] - - If "*" is provided, all fields are returned. - [Product.name][google.cloud.retail.v2beta.Product.name] is - always returned no matter what mask is set. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class ListProductsResponse(proto.Message): - r"""Response message for - [ProductService.ListProducts][google.cloud.retail.v2beta.ProductService.ListProducts] - method. - - Attributes: - products (Sequence[google.cloud.retail_v2beta.types.Product]): - The [Product][google.cloud.retail.v2beta.Product]s. - next_page_token (str): - A token that can be sent as - [ListProductsRequest.page_token][google.cloud.retail.v2beta.ListProductsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - products = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class SetInventoryRequest(proto.Message): - r"""Request message for [SetInventory][] method. - - Attributes: - inventory (google.cloud.retail_v2beta.types.Product): - Required. The inventory information to update. The allowable - fields to update are: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - The updated inventory fields must be specified in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask]. - - If [SetInventoryRequest.inventory.name][] is empty or - invalid, an INVALID_ARGUMENT error is returned. - - If the caller does not have permission to update the - [Product][google.cloud.retail.v2beta.Product] named in - [Product.name][google.cloud.retail.v2beta.Product.name], - regardless of whether or not it exists, a PERMISSION_DENIED - error is returned. - - If the [Product][google.cloud.retail.v2beta.Product] to - update does not have existing inventory information, the - provided inventory information will be inserted. - - If the [Product][google.cloud.retail.v2beta.Product] to - update has existing inventory information, the provided - inventory information will be merged while respecting the - last update time for each inventory field, using the - provided or default value for - [SetInventoryRequest.set_time][google.cloud.retail.v2beta.SetInventoryRequest.set_time]. - - The caller can replace place IDs for a subset of fulfillment - types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types and - corresponding place IDs to update in - [SetInventoryRequest.inventory.fulfillment_info][] - - The caller can clear all place IDs from a subset of - fulfillment types in the following ways: - - - Adds "fulfillment_info" in - [SetInventoryRequest.set_mask][google.cloud.retail.v2beta.SetInventoryRequest.set_mask] - - Specifies only the desired fulfillment types to clear in - [SetInventoryRequest.inventory.fulfillment_info][] - - Checks that only the desired fulfillment info types have - empty - [SetInventoryRequest.inventory.fulfillment_info.place_ids][] - - The last update time is recorded for the following inventory - fields: - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - [Product.availability][google.cloud.retail.v2beta.Product.availability] - - [Product.available_quantity][google.cloud.retail.v2beta.Product.available_quantity] - - [Product.fulfillment_info][google.cloud.retail.v2beta.Product.fulfillment_info] - - If a full overwrite of inventory information while ignoring - timestamps is needed, [UpdateProduct][] should be invoked - instead. - set_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided - [Product][google.cloud.retail.v2beta.Product] to update. - - At least one field must be provided. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - set_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the request is issued, used to - prevent out-of-order updates on inventory fields - with the last update time recorded. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] with name - [Product.name][google.cloud.retail.v2beta.Product.name] is - not found, the inventory update will still be processed and - retained for at most 1 day until the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - inventory = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - set_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - set_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=4, - ) - - -class SetInventoryMetadata(proto.Message): - r"""Metadata related to the progress of the SetInventory operation. - Currently empty because there is no meaningful metadata populated - from the [SetInventory][] method. - - """ - - -class SetInventoryResponse(proto.Message): - r"""Response of the SetInventoryRequest. Currently empty because there - is no meaningful response populated from the [SetInventory][] - method. - - """ - - -class AddFulfillmentPlacesRequest(proto.Message): - r"""Request message for [AddFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery" to be added for this - [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type]. - Duplicate IDs will be automatically ignored. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - - If the total number of place IDs exceeds 2000 for this - [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type] - after adding, then the update will be rejected. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - the fulfillment information will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - add_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class AddFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the AddFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [AddFulfillmentPlaces][] method. - - """ - - -class AddFulfillmentPlacesResponse(proto.Message): - r"""Response of the AddFulfillmentPlacesRequest. Currently empty because - there is no meaningful response populated from the - [AddFulfillmentPlaces][] method. - - """ - - -class AddLocalInventoriesRequest(proto.Message): - r"""Request message for [AddLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - local_inventories (Sequence[google.cloud.retail_v2beta.types.LocalInventory]): - Required. A list of inventory information at - difference places. Each place is identified by - its place ID. At most 3000 inventories are - allowed per request. - add_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which inventory fields in the provided list of - [LocalInventory][google.cloud.retail.v2beta.LocalInventory] - to update. The field is updated to the provided value. - - If a field is set while the place does not have a previous - local inventory, the local inventory at that store is - created. - - If a field is set while the value of that field is not - provided, the original field value, if it exists, is - deleted. - - If the mask is not set or set with empty paths, all - inventory fields will be updated. - - If an unsupported or unknown field is provided, an - INVALID_ARGUMENT error is returned and the entire update - will be ignored. - add_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory updates are - issued. Used to prevent out-of-order updates on - local inventory fields. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - the local inventory will still be processed and retained for - at most 1 day and processed once the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - local_inventories = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.LocalInventory, - ) - add_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - add_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=6, - ) - - -class AddLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the AddLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [AddLocalInventories][] method. - - """ - - -class AddLocalInventoriesResponse(proto.Message): - r"""Response of the [AddLocalInventories][] API. Currently empty because - there is no meaningful response populated from the - [AddLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesRequest(proto.Message): - r"""Request message for [RemoveLocalInventories][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - place_ids (Sequence[str]): - Required. A list of place IDs to have their - inventory deleted. At most 3000 place IDs are - allowed per request. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the inventory deletions are - issued. Used to prevent out-of-order updates and - deletions on local inventory fields. If not - provided, the internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - the local inventory removal request will still be processed - and retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - - -class RemoveLocalInventoriesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveLocalInventories - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveLocalInventories][] method. - - """ - - -class RemoveLocalInventoriesResponse(proto.Message): - r"""Response of the [RemoveLocalInventories][] API. Currently empty - because there is no meaningful response populated from the - [RemoveLocalInventories][] method. - - """ - - -class RemoveFulfillmentPlacesRequest(proto.Message): - r"""Request message for [RemoveFulfillmentPlaces][] method. - - Attributes: - product (str): - Required. Full resource name of - [Product][google.cloud.retail.v2beta.Product], such as - ``projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id``. - - If the caller does not have permission to access the - [Product][google.cloud.retail.v2beta.Product], regardless of - whether or not it exists, a PERMISSION_DENIED error is - returned. - type_ (str): - Required. The fulfillment type, including commonly used - types (such as pickup in store and same day delivery), and - custom types. - - Supported values: - - - "pickup-in-store" - - "ship-to-store" - - "same-day-delivery" - - "next-day-delivery" - - "custom-type-1" - - "custom-type-2" - - "custom-type-3" - - "custom-type-4" - - "custom-type-5" - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - - This field directly corresponds to - [Product.fulfillment_info.type][]. - place_ids (Sequence[str]): - Required. The IDs for this - [type][google.cloud.retail.v2beta.RemoveFulfillmentPlacesRequest.type], - such as the store IDs for "pickup-in-store" or the region - IDs for "same-day-delivery", to be removed for this - [type][google.cloud.retail.v2beta.RemoveFulfillmentPlacesRequest.type]. - - At least 1 value is required, and a maximum of 2000 values - are allowed. Each value must be a string with a length limit - of 10 characters, matching the pattern ``[a-zA-Z0-9_-]+``, - such as "store1" or "REGION-2". Otherwise, an - INVALID_ARGUMENT error is returned. - remove_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the fulfillment updates are - issued, used to prevent out-of-order updates on - fulfillment information. If not provided, the - internal system time will be used. - allow_missing (bool): - If set to true, and the - [Product][google.cloud.retail.v2beta.Product] is not found, - the fulfillment information will still be processed and - retained for at most 1 day and processed once the - [Product][google.cloud.retail.v2beta.Product] is created. If - set to false, a NOT_FOUND error is returned if the - [Product][google.cloud.retail.v2beta.Product] is not found. - """ - - product = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.STRING, - number=2, - ) - place_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - remove_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - allow_missing = proto.Field( - proto.BOOL, - number=5, - ) - - -class RemoveFulfillmentPlacesMetadata(proto.Message): - r"""Metadata related to the progress of the RemoveFulfillmentPlaces - operation. Currently empty because there is no meaningful metadata - populated from the [RemoveFulfillmentPlaces][] method. - - """ - - -class RemoveFulfillmentPlacesResponse(proto.Message): - r"""Response of the RemoveFulfillmentPlacesRequest. Currently empty - because there is no meaningful response populated from the - [RemoveFulfillmentPlaces][] method. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py deleted file mode 100644 index be192a70..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/promotion.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'Promotion', - }, -) - - -class Promotion(proto.Message): - r"""Promotion information. - - Attributes: - promotion_id (str): - ID of the promotion. For example, "free gift". - - The value must be a UTF-8 encoded string with a length limit - of 128 characters, and match the pattern: - ``[a-zA-Z][a-zA-Z0-9_]*``. For example, id0LikeThis or - ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is - returned. - - Google Merchant Center property - `promotion `__. - """ - - promotion_id = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py deleted file mode 100644 index 95c99126..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/purge_config.py +++ /dev/null @@ -1,107 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'PurgeMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - }, -) - - -class PurgeMetadata(proto.Message): - r"""Metadata related to the progress of the Purge operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - """ - - -class PurgeUserEventsRequest(proto.Message): - r"""Request message for PurgeUserEvents method. - - Attributes: - parent (str): - Required. The resource name of the catalog under which the - events are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}`` - filter (str): - Required. The filter string to specify the events to be - deleted with a length limit of 5,000 characters. Empty - string filter is not allowed. The eligible fields for - filtering are: - - - ``eventType``: Double quoted - [UserEvent.event_type][google.cloud.retail.v2beta.UserEvent.event_type] - string. - - ``eventTime``: in ISO 8601 "zulu" format. - - ``visitorId``: Double quoted string. Specifying this will - delete all events associated with a visitor. - - ``userId``: Double quoted string. Specifying this will - delete all events associated with a user. - - Examples: - - - Deleting all events in a time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - - Deleting specific eventType in time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` - - Deleting all events for a specific visitor: - ``visitorId = "visitor1024"`` - - The filtering fields are assumed to have an implicit AND. - force (bool): - Actually perform the purge. If ``force`` is set to false, - the method will return the expected purge count without - deleting any user events. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeUserEventsResponse(proto.Message): - r"""Response of the PurgeUserEventsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purged_events_count (int): - The total count of events purged as a result - of the operation. - """ - - purged_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py deleted file mode 100644 index 21447a27..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/search_service.py +++ /dev/null @@ -1,1074 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import product as gcr_product -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'SearchRequest', - 'SearchResponse', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - - Attributes: - placement (str): - Required. The resource name of the search engine placement, - such as - ``projects/*/locations/global/catalogs/default_catalog/placements/default_search`` - This field is used to identify the serving configuration - name and the set of models that will be used to make the - search. - branch (str): - The branch resource name, such as - ``projects/*/locations/global/catalogs/default_catalog/branches/0``. - - Use "default_branch" as the branch ID or leave this field - empty, to search products under the default branch. - query (str): - Raw search query. - visitor_id (str): - Required. A unique identifier for tracking visitors. For - example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor logs in or out of the website. - - This should be the same identifier as - [UserEvent.visitor_id][google.cloud.retail.v2beta.UserEvent.visitor_id]. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2beta.types.UserInfo): - User information. - page_size (int): - Maximum number of - [Product][google.cloud.retail.v2beta.Product]s to return. If - unspecified, defaults to a reasonable value. The maximum - allowed value is 120. Values above 120 will be coerced to - 120. - - If this field is negative, an INVALID_ARGUMENT is returned. - page_token (str): - A page token - [SearchResponse.next_page_token][google.cloud.retail.v2beta.SearchResponse.next_page_token], - received from a previous - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - must match the call that provided the page token. Otherwise, - an INVALID_ARGUMENT error is returned. - offset (int): - A 0-indexed integer that specifies the current offset (that - is, starting result location, amongst the - [Product][google.cloud.retail.v2beta.Product]s deemed by the - API as relevant) in search results. This field is only - considered if - [page_token][google.cloud.retail.v2beta.SearchRequest.page_token] - is unset. - - If this field is negative, an INVALID_ARGUMENT is returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. Filter expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - canonical_filter (str): - The default filter that is applied when a user performs a - search without checking any filters on the search page. - - The filter applied to every search request when quality - improvement such as query expansion is needed. For example, - if a query does not have enough results, an expanded query - with - [SearchRequest.canonical_filter][google.cloud.retail.v2beta.SearchRequest.canonical_filter] - will be returned as a supplement of the original query. This - field is strongly recommended to achieve high search - quality. - - See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for more details about filter syntax. - order_by (str): - The order in which products are returned. Products can be - ordered by a field in an - [Product][google.cloud.retail.v2beta.Product] object. Leave - it unset if ordered by relevance. OrderBy expression is - case-sensitive. See more details at this `user - guide `__. - - If this field is unrecognizable, an INVALID_ARGUMENT is - returned. - facet_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.FacetSpec]): - Facet specifications for faceted search. If empty, no facets - are returned. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - dynamic_facet_spec (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec): - Deprecated. Refer to - https://cloud.google.com/retail/docs/configs#dynamic - to enable dynamic facets. Do not set this field. - The specification for dynamically generated - facets. Notice that only textual facets can be - dynamically generated. - boost_spec (google.cloud.retail_v2beta.types.SearchRequest.BoostSpec): - Boost specification to boost certain products. See more - details at this `user - guide `__. - - Notice that if both - [ServingConfig.boost_control_ids][google.cloud.retail.v2beta.ServingConfig.boost_control_ids] - and [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. - query_expansion_spec (google.cloud.retail_v2beta.types.SearchRequest.QueryExpansionSpec): - The query expansion specification that specifies the - conditions under which query expansion will occur. See more - details at this `user - guide `__. - variant_rollup_keys (Sequence[str]): - The keys to fetch and rollup the matching - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s attributes, - [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo] - or - [LocalInventory][google.cloud.retail.v2beta.LocalInventory]s - attributes. The attributes from all the matching - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s or - [LocalInventory][google.cloud.retail.v2beta.LocalInventory]s - are merged and de-duplicated. Notice that rollup attributes - will lead to extra query latency. Maximum number of keys is - 30. - - For - [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], - a fulfillment type and a fulfillment ID must be provided in - the format of "fulfillmentType.fulfillmentId". E.g., in - "pickupInStore.store123", "pickupInStore" is fulfillment - type and "store123" is the store ID. - - Supported keys are: - - - colorFamilies - - price - - originalPrice - - discount - - variantId - - inventory(place_id,price) - - inventory(place_id,original_price) - - inventory(place_id,attributes.key), where key is any key - in the [Product.inventories.attributes][] map. - - attributes.key, where key is any key in the - [Product.attributes][google.cloud.retail.v2beta.Product.attributes] - map. - - pickupInStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "pickup-in-store". - - shipToStore.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "ship-to-store". - - sameDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "same-day-delivery". - - nextDayDelivery.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "next-day-delivery". - - customFulfillment1.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-1". - - customFulfillment2.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-2". - - customFulfillment3.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-3". - - customFulfillment4.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-4". - - customFulfillment5.id, where id is any - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - for - [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - "custom-type-5". - - If this field is set to an invalid value other than these, - an INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. Required for - category navigation queries to achieve good search quality. - The format should be the same as - [UserEvent.page_categories][google.cloud.retail.v2beta.UserEvent.page_categories]; - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - search_mode (google.cloud.retail_v2beta.types.SearchRequest.SearchMode): - The search mode of the search request. If not - specified, a single search request triggers both - product search and faceted search. - personalization_spec (google.cloud.retail_v2beta.types.SearchRequest.PersonalizationSpec): - The specification for personalization. - """ - class SearchMode(proto.Enum): - r"""The search mode of each search request.""" - SEARCH_MODE_UNSPECIFIED = 0 - PRODUCT_SEARCH_ONLY = 1 - FACETED_SEARCH_ONLY = 2 - - class FacetSpec(proto.Message): - r"""A facet specification to perform faceted search. - - Attributes: - facet_key (google.cloud.retail_v2beta.types.SearchRequest.FacetSpec.FacetKey): - Required. The facet key specification. - limit (int): - Maximum of facet values that should be returned for this - facet. If unspecified, defaults to 20. The maximum allowed - value is 300. Values above 300 will be coerced to 300. - - If this field is negative, an INVALID_ARGUMENT is returned. - excluded_filter_keys (Sequence[str]): - List of keys to exclude when faceting. - - By default, - [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] - is not excluded from the filter unless it is listed in this - field. - - For example, suppose there are 100 products with color facet - "Red" and 200 products with color facet "Blue". A query - containing the filter "colorFamilies:ANY("Red")" and have - "colorFamilies" as - [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] - will by default return the "Red" with count 100. - - If this field contains "colorFamilies", then the query - returns both the "Red" with count 100 and "Blue" with count - 200, because the "colorFamilies" key is now excluded from - the filter. - - A maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - enable_dynamic_position (bool): - Enables dynamic position for this facet. If set to true, the - position of this facet among all facets in the response is - determined by Google Retail Search. It will be ordered - together with dynamic facets if dynamic facets is enabled. - If set to false, the position of this facet in the response - will be the same as in the request, and it will be ranked - before the facets with dynamic position enable and all - dynamic facets. - - For example, you may always want to have rating facet - returned in the response, but it's not necessarily to always - display the rating facet at the top. In that case, you can - set enable_dynamic_position to true so that the position of - rating facet in response will be determined by Google Retail - Search. - - Another example, assuming you have the following facets in - the request: - - - "rating", enable_dynamic_position = true - - - "price", enable_dynamic_position = false - - - "brands", enable_dynamic_position = false - - And also you have a dynamic facets enable, which will - generate a facet 'gender'. Then the final order of the - facets in the response can be ("price", "brands", "rating", - "gender") or ("price", "brands", "gender", "rating") depends - on how Google Retail Search orders "gender" and "rating" - facets. However, notice that "price" and "brands" will - always be ranked at 1st and 2nd position since their - enable_dynamic_position are false. - """ - - class FacetKey(proto.Message): - r"""Specifies how a facet is computed. - - Attributes: - key (str): - Required. Supported textual and numerical facet keys in - [Product][google.cloud.retail.v2beta.Product] object, over - which the facet values are computed. Facet key is - case-sensitive. - - Allowed facet keys when - [FacetKey.query][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.query] - is not specified: - - - textual_field = - - - "brands" - - "categories" - - "genders" - - "ageGroups" - - "availability" - - "colorFamilies" - - "colors" - - "sizes" - - "materials" - - "patterns" - - "conditions" - - "attributes.key" - - "pickupInStore" - - "shipToStore" - - "sameDayDelivery" - - "nextDayDelivery" - - "customFulfillment1" - - "customFulfillment2" - - "customFulfillment3" - - "customFulfillment4" - - "customFulfillment5" - - "inventory(place_id,attributes.key)" - - - numerical_field = - - - "price" - - "discount" - - "rating" - - "ratingCount" - - "attributes.key" - - "inventory(place_id,price)" - - "inventory(place_id,original_price)" - - "inventory(place_id,attributes.key)". - intervals (Sequence[google.cloud.retail_v2beta.types.Interval]): - Set only if values should be bucketized into - intervals. Must be set for facets with numerical - values. Must not be set for facet with text - values. Maximum number of intervals is 30. - restricted_values (Sequence[str]): - Only get facet for the given restricted values. For example, - when using "pickupInStore" as key and set restricted values - to ["store123", "store456"], only facets for "store123" and - "store456" are returned. Only supported on textual fields - and fulfillments. Maximum is 20. - - Must be set for the fulfillment facet keys: - - - pickupInStore - - - shipToStore - - - sameDayDelivery - - - nextDayDelivery - - - customFulfillment1 - - - customFulfillment2 - - - customFulfillment3 - - - customFulfillment4 - - - customFulfillment5 - prefixes (Sequence[str]): - Only get facet values that start with the - given string prefix. For example, suppose - "categories" has three values "Women > Shoe", - "Women > Dress" and "Men > Shoe". If set - "prefixes" to "Women", the "categories" facet - will give only "Women > Shoe" and "Women > - Dress". Only supported on textual fields. - Maximum is 10. - contains (Sequence[str]): - Only get facet values that contains the given - strings. For example, suppose "categories" has - three values "Women > Shoe", "Women > Dress" and - "Men > Shoe". If set "contains" to "Shoe", the - "categories" facet will give only "Women > Shoe" - and "Men > Shoe". Only supported on textual - fields. Maximum is 10. - order_by (str): - The order in which [Facet.values][] are returned. - - Allowed values are: - - - "count desc", which means order by - [Facet.FacetValue.count][] descending. - - - "value desc", which means order by - [Facet.FacetValue.value][] descending. Only applies to - textual facets. - - If not set, textual values are sorted in `natural - order `__; - numerical intervals are sorted in the order given by - [FacetSpec.FacetKey.intervals][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.intervals]; - [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] - are sorted in the order given by - [FacetSpec.FacetKey.restricted_values][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.restricted_values]. - query (str): - The query that is used to compute facet for the given facet - key. When provided, it will override the default behavior of - facet computation. The query syntax is the same as a filter - expression. See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for detail syntax and limitations. Notice that there is no - limitation on - [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] - when query is specified. - - In the response, [FacetValue.value][] will be always "1" and - [FacetValue.count][] will be the number of results that - matches the query. - - For example, you can set a customized facet for - "shipToStore", where - [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] - is "customizedShipToStore", and - [FacetKey.query][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.query] - is "availability: ANY("IN_STOCK") AND shipToStore: - ANY("123")". Then the facet will count the products that are - both in stock and ship to store "123". - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - intervals = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Interval, - ) - restricted_values = proto.RepeatedField( - proto.STRING, - number=3, - ) - prefixes = proto.RepeatedField( - proto.STRING, - number=8, - ) - contains = proto.RepeatedField( - proto.STRING, - number=9, - ) - order_by = proto.Field( - proto.STRING, - number=4, - ) - query = proto.Field( - proto.STRING, - number=5, - ) - - facet_key = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.FacetSpec.FacetKey', - ) - limit = proto.Field( - proto.INT32, - number=2, - ) - excluded_filter_keys = proto.RepeatedField( - proto.STRING, - number=3, - ) - enable_dynamic_position = proto.Field( - proto.BOOL, - number=4, - ) - - class DynamicFacetSpec(proto.Message): - r"""The specifications of dynamically generated facets. - - Attributes: - mode (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec.Mode): - Mode of the DynamicFacet feature. Defaults to - [Mode.DISABLED][google.cloud.retail.v2beta.SearchRequest.DynamicFacetSpec.Mode.DISABLED] - if it's unset. - """ - class Mode(proto.Enum): - r"""Enum to control DynamicFacet mode""" - MODE_UNSPECIFIED = 0 - DISABLED = 1 - ENABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.DynamicFacetSpec.Mode', - ) - - class BoostSpec(proto.Message): - r"""Boost specification to boost certain items. - - Attributes: - condition_boost_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - Condition boost specifications. If a product - matches multiple conditions in the - specifictions, boost scores from these - specifications are all applied and combined in a - non-linear way. Maximum number of specifications - is 10. - skip_boost_spec_validation (bool): - Whether to skip boostspec validation. If this field is set - to true, invalid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] - will be ignored and valid - [BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] - will still be applied. - - This field is a member of `oneof`_ ``_skip_boost_spec_validation``. - """ - - class ConditionBoostSpec(proto.Message): - r"""Boost applies to products which match a condition. - - Attributes: - condition (str): - An expression which specifies a boost condition. The syntax - and supported fields are the same as a filter expression. - See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost products with product ID "product_1" or - "product_2", and color "Red" or "Blue": - - - (id: ANY("product_1", "product_2")) AND - (colorFamilies: ANY("Red","Blue")) - boost (float): - Strength of the condition boost, which should be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the item a big promotion. However, it - does not necessarily mean that the boosted item will be the - top result at all times, nor that other items will be - excluded. Results could still be shown even when none of - them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant items. - - Setting to -1.0 gives the item a big demotion. However, - results that are deeply relevant might still be shown. The - item will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - """ - - condition = proto.Field( - proto.STRING, - number=1, - ) - boost = proto.Field( - proto.FLOAT, - number=2, - ) - - condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - skip_boost_spec_validation = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - - class QueryExpansionSpec(proto.Message): - r"""Specification to determine under which conditions query - expansion should occur. - - Attributes: - condition (google.cloud.retail_v2beta.types.SearchRequest.QueryExpansionSpec.Condition): - The condition under which query expansion should occur. - Default to - [Condition.DISABLED][google.cloud.retail.v2beta.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - pin_unexpanded_results (bool): - Whether to pin unexpanded results. If this - field is set to true, unexpanded products are - always at the top of the search results, - followed by the expanded results. - """ - class Condition(proto.Enum): - r"""Enum describing under which condition query expansion should - occur. - """ - CONDITION_UNSPECIFIED = 0 - DISABLED = 1 - AUTO = 3 - - condition = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.QueryExpansionSpec.Condition', - ) - pin_unexpanded_results = proto.Field( - proto.BOOL, - number=2, - ) - - class PersonalizationSpec(proto.Message): - r"""The specification for personalization. - - Attributes: - mode (google.cloud.retail_v2beta.types.SearchRequest.PersonalizationSpec.Mode): - Defaults to - [Mode.AUTO][google.cloud.retail.v2beta.SearchRequest.PersonalizationSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""The personalization mode of each search request.""" - MODE_UNSPECIFIED = 0 - AUTO = 1 - DISABLED = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.PersonalizationSpec.Mode', - ) - - placement = proto.Field( - proto.STRING, - number=1, - ) - branch = proto.Field( - proto.STRING, - number=2, - ) - query = proto.Field( - proto.STRING, - number=3, - ) - visitor_id = proto.Field( - proto.STRING, - number=4, - ) - user_info = proto.Field( - proto.MESSAGE, - number=5, - message=common.UserInfo, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - offset = proto.Field( - proto.INT32, - number=9, - ) - filter = proto.Field( - proto.STRING, - number=10, - ) - canonical_filter = proto.Field( - proto.STRING, - number=28, - ) - order_by = proto.Field( - proto.STRING, - number=11, - ) - facet_specs = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=FacetSpec, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=21, - message=DynamicFacetSpec, - ) - boost_spec = proto.Field( - proto.MESSAGE, - number=13, - message=BoostSpec, - ) - query_expansion_spec = proto.Field( - proto.MESSAGE, - number=14, - message=QueryExpansionSpec, - ) - variant_rollup_keys = proto.RepeatedField( - proto.STRING, - number=17, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=23, - ) - search_mode = proto.Field( - proto.ENUM, - number=31, - enum=SearchMode, - ) - personalization_spec = proto.Field( - proto.MESSAGE, - number=32, - message=PersonalizationSpec, - ) - - -class SearchResponse(proto.Message): - r"""Response message for - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search] - method. - - Attributes: - results (Sequence[google.cloud.retail_v2beta.types.SearchResponse.SearchResult]): - A list of matched items. The order represents - the ranking. - facets (Sequence[google.cloud.retail_v2beta.types.SearchResponse.Facet]): - Results of facets requested by user. - total_size (int): - The estimated total count of matched items irrespective of - pagination. The count of - [results][google.cloud.retail.v2beta.SearchResponse.results] - returned by pagination may be less than the - [total_size][google.cloud.retail.v2beta.SearchResponse.total_size] - that matches. - corrected_query (str): - If spell correction applies, the corrected - query. Otherwise, empty. - attribution_token (str): - A unique search token. This should be included in the - [UserEvent][google.cloud.retail.v2beta.UserEvent] logs - resulting from this search, which enables accurate - attribution of search model performance. - next_page_token (str): - A token that can be sent as - [SearchRequest.page_token][google.cloud.retail.v2beta.SearchRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - query_expansion_info (google.cloud.retail_v2beta.types.SearchResponse.QueryExpansionInfo): - Query expansion information for the returned - results. - redirect_uri (str): - The URI of a customer-defined redirect page. If redirect - action is triggered, no search will be performed, and only - [redirect_uri][google.cloud.retail.v2beta.SearchResponse.redirect_uri] - and - [attribution_token][google.cloud.retail.v2beta.SearchResponse.attribution_token] - will be set in the response. - applied_controls (Sequence[str]): - The fully qualified resource name of applied - `controls `__. - invalid_condition_boost_specs (Sequence[google.cloud.retail_v2beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - The invalid - [SearchRequest.BoostSpec.condition_boost_specs][google.cloud.retail.v2beta.SearchRequest.BoostSpec.condition_boost_specs] - that are not applied during serving. - """ - - class SearchResult(proto.Message): - r"""Represents the search results. - - Attributes: - id (str): - [Product.id][google.cloud.retail.v2beta.Product.id] of the - searched [Product][google.cloud.retail.v2beta.Product]. - product (google.cloud.retail_v2beta.types.Product): - The product data snippet in the search response. Only - [Product.name][google.cloud.retail.v2beta.Product.name] is - guaranteed to be populated. - - [Product.variants][google.cloud.retail.v2beta.Product.variants] - contains the product variants that match the search query. - If there are multiple product variants matching the query, - top 5 most relevant product variants are returned and - ordered by relevancy. - - If relevancy can be deternmined, use - [matching_variant_fields][google.cloud.retail.v2beta.SearchResponse.SearchResult.matching_variant_fields] - to look up matched product variants fields. If relevancy - cannot be determined, e.g. when searching "shoe" all - products in a shoe product can be a match, 5 product - variants are returned but order is meaningless. - matching_variant_count (int): - The count of matched - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product]s. - matching_variant_fields (Mapping[str, google.protobuf.field_mask_pb2.FieldMask]): - If a - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] matches the - search query, this map indicates which - [Product][google.cloud.retail.v2beta.Product] fields are - matched. The key is the - [Product.name][google.cloud.retail.v2beta.Product.name], the - value is a field mask of the matched - [Product][google.cloud.retail.v2beta.Product] fields. If - matched attributes cannot be determined, this map will be - empty. - - For example, a key "sku1" with field mask - "products.color_info" indicates there is a match between - "sku1" [ColorInfo][google.cloud.retail.v2beta.ColorInfo] and - the query. - variant_rollup_values (Mapping[str, google.protobuf.struct_pb2.Value]): - The rollup matching - [variant][google.cloud.retail.v2beta.Product.Type.VARIANT] - [Product][google.cloud.retail.v2beta.Product] attributes. - The key is one of the - [SearchRequest.variant_rollup_keys][google.cloud.retail.v2beta.SearchRequest.variant_rollup_keys]. - The values are the merged and de-duplicated - [Product][google.cloud.retail.v2beta.Product] attributes. - Notice that the rollup values are respect filter. For - example, when filtering by "colorFamilies:ANY("red")" and - rollup "colorFamilies", only "red" is returned. - - For textual and numerical attributes, the rollup values is a - list of string or double values with type - [google.protobuf.ListValue][google.protobuf.ListValue]. For - example, if there are two variants with colors "red" and - "blue", the rollup values are - - :: - - { key: "colorFamilies" - value { - list_value { - values { string_value: "red" } - values { string_value: "blue" } - } - } - } - - For - [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], - the rollup values is a double value with type - [google.protobuf.Value][google.protobuf.Value]. For example, - ``{key: "pickupInStore.store1" value { number_value: 10 }}`` - means a there are 10 variants in this product are available - in the store "store1". - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - product = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_product.Product, - ) - matching_variant_count = proto.Field( - proto.INT32, - number=3, - ) - matching_variant_fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - variant_rollup_values = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - - class Facet(proto.Message): - r"""A facet result. - - Attributes: - key (str): - The key for this facet. E.g., "colorFamilies" - or "price" or "attributes.attr1". - values (Sequence[google.cloud.retail_v2beta.types.SearchResponse.Facet.FacetValue]): - The facet values for this field. - dynamic_facet (bool): - Whether the facet is dynamically generated. - """ - - class FacetValue(proto.Message): - r"""A facet value which contains value names and their count. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Text value of a facet, such as "Black" for - facet "colorFamilies". - - This field is a member of `oneof`_ ``facet_value``. - interval (google.cloud.retail_v2beta.types.Interval): - Interval value for a facet, such as [10, 20) for facet - "price". - - This field is a member of `oneof`_ ``facet_value``. - count (int): - Number of items that have this facet value. - """ - - value = proto.Field( - proto.STRING, - number=1, - oneof='facet_value', - ) - interval = proto.Field( - proto.MESSAGE, - number=2, - oneof='facet_value', - message=common.Interval, - ) - count = proto.Field( - proto.INT64, - number=3, - ) - - key = proto.Field( - proto.STRING, - number=1, - ) - values = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SearchResponse.Facet.FacetValue', - ) - dynamic_facet = proto.Field( - proto.BOOL, - number=3, - ) - - class QueryExpansionInfo(proto.Message): - r"""Information describing query expansion including whether - expansion has occurred. - - Attributes: - expanded_query (bool): - Bool describing whether query expansion has - occurred. - pinned_result_count (int): - Number of pinned results. This field will only be set when - expansion happens and - [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.retail.v2beta.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] - is set to true. - """ - - expanded_query = proto.Field( - proto.BOOL, - number=1, - ) - pinned_result_count = proto.Field( - proto.INT64, - number=2, - ) - - @property - def raw_page(self): - return self - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=SearchResult, - ) - facets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Facet, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - corrected_query = proto.Field( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - next_page_token = proto.Field( - proto.STRING, - number=6, - ) - query_expansion_info = proto.Field( - proto.MESSAGE, - number=7, - message=QueryExpansionInfo, - ) - redirect_uri = proto.Field( - proto.STRING, - number=10, - ) - applied_controls = proto.RepeatedField( - proto.STRING, - number=12, - ) - invalid_condition_boost_specs = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py deleted file mode 100644 index f8b78591..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config.py +++ /dev/null @@ -1,309 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'ServingConfig', - }, -) - - -class ServingConfig(proto.Message): - r"""Configures metadata that is used to generate serving time results - (e.g. search results or recommendation predictions). The - ServingConfig is passed in the search and predict request and - together with the Catalog.default_branch, generates results. - - Attributes: - name (str): - Immutable. Fully qualified name - projects/\ */locations/global/catalogs/*/servingConfig/\* - display_name (str): - Required. The human readable serving config display name. - Used in Retail UI. - - This field must be a UTF-8 encoded string with a length - limit of 128 characters. Otherwise, an INVALID_ARGUMENT - error is returned. - model_id (str): - The id of the model to use at serving time. Currently only - RecommendationModels are supported: - https://cloud.google.com/retail/recommendations-ai/docs/create-models - Can be changed but only to a compatible model (e.g. - others-you-may-like CTR to others-you-may-like CVR). - - Required when - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - price_reranking_level (str): - How much price ranking we want in serving results. Price - reranking causes product items with a similar recommendation - probability to be ordered by price, with the highest-priced - items first. This setting could result in a decrease in - click-through and conversion rates. Allowed values are: - - - 'no-price-reranking' - - 'low-price-raranking' - - 'medium-price-reranking' - - 'high-price-reranking' - - If not specified, we choose default based on model type. - Default value: 'no-price-reranking'. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - facet_control_ids (Sequence[str]): - Facet specifications for faceted search. If empty, no facets - are returned. The ids refer to the ids of - [Control][google.cloud.retail.v2beta.Control] resources with - only the Facet control set. These controls are assumed to be - in the same [Catalog][google.cloud.retail.v2beta.Catalog] as - the - [ServingConfig][google.cloud.retail.v2beta.ServingConfig]. A - maximum of 100 values are allowed. Otherwise, an - INVALID_ARGUMENT error is returned. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - dynamic_facet_spec (google.cloud.retail_v2beta.types.SearchRequest.DynamicFacetSpec): - The specification for dynamically generated facets. Notice - that only textual facets can be dynamically generated. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - boost_control_ids (Sequence[str]): - Condition boost specifications. If a product matches - multiple conditions in the specifications, boost scores from - these specifications are all applied and combined in a - non-linear way. Maximum number of specifications is 100. - - Notice that if both - [ServingConfig.boost_control_ids][google.cloud.retail.v2beta.ServingConfig.boost_control_ids] - and [SearchRequest.boost_spec] are set, the boost conditions - from both places are evaluated. If a search request matches - multiple boost conditions, the final boost score is equal to - the sum of the boost scores from all matched boost - conditions. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - filter_control_ids (Sequence[str]): - Condition filter specifications. If a product matches - multiple conditions in the specifications, filters from - these specifications are all applied and combined via the - AND operator. Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - redirect_control_ids (Sequence[str]): - Condition redirect specifications. Only the first triggered - redirect action is applied, even if multiple apply. Maximum - number of specifications is 1000. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - twoway_synonyms_control_ids (Sequence[str]): - Condition synonyms specifications. If multiple syonyms - conditions match, all matching synonyms control in the list - will execute. Order of controls in the list will not matter. - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - oneway_synonyms_control_ids (Sequence[str]): - Condition oneway synonyms specifications. If multiple oneway - synonyms conditions match, all matching oneway synonyms - controls in the list will execute. Order of controls in the - list will not matter. Maximum number of specifications is - 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - do_not_associate_control_ids (Sequence[str]): - Condition do not associate specifications. If multiple do - not associate conditions match, all matching do not - associate controls in the list will execute. - - - Order does not matter. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - replacement_control_ids (Sequence[str]): - Condition replacement specifications. - - - Applied according to the order in the list. - - A previously replaced term can not be re-replaced. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - ignore_control_ids (Sequence[str]): - Condition ignore specifications. If multiple ignore - conditions match, all matching ignore controls in the list - will execute. - - - Order does not matter. - - Maximum number of specifications is 100. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_SEARCH][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_SEARCH]. - diversity_level (str): - How much diversity to use in recommendation model results - e.g. 'medium-diversity' or 'high-diversity'. Currently - supported values: - - - 'no-diversity' - - 'low-diversity' - - 'medium-diversity' - - 'high-diversity' - - 'auto-diversity' - - If not specified, we choose default based on recommendation - model type. Default value: 'no-diversity'. - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - enable_category_filter_level (str): - Whether to add additional category filters on the - 'similar-items' model. If not specified, we enable it by - default. Allowed values are: - - - 'no-category-match': No additional filtering of original - results from the model and the customer's filters. - - 'relaxed-category-match': Only keep results with - categories that match at least one item categories in the - PredictRequests's context item. - - - If customer also sends filters in the PredictRequest, - then the results will satisfy both conditions (user - given and category match). - - Can only be set if - [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] - is - [SOLUTION_TYPE_RECOMMENDATION][google.cloud.retail.v2main.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. - solution_types (Sequence[google.cloud.retail_v2beta.types.SolutionType]): - Required. Immutable. Specifies the solution - types that a serving config can be associated - with. Currently we support setting only one type - of solution. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - model_id = proto.Field( - proto.STRING, - number=3, - ) - price_reranking_level = proto.Field( - proto.STRING, - number=4, - ) - facet_control_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - dynamic_facet_spec = proto.Field( - proto.MESSAGE, - number=6, - message=search_service.SearchRequest.DynamicFacetSpec, - ) - boost_control_ids = proto.RepeatedField( - proto.STRING, - number=7, - ) - filter_control_ids = proto.RepeatedField( - proto.STRING, - number=9, - ) - redirect_control_ids = proto.RepeatedField( - proto.STRING, - number=10, - ) - twoway_synonyms_control_ids = proto.RepeatedField( - proto.STRING, - number=18, - ) - oneway_synonyms_control_ids = proto.RepeatedField( - proto.STRING, - number=12, - ) - do_not_associate_control_ids = proto.RepeatedField( - proto.STRING, - number=13, - ) - replacement_control_ids = proto.RepeatedField( - proto.STRING, - number=14, - ) - ignore_control_ids = proto.RepeatedField( - proto.STRING, - number=15, - ) - diversity_level = proto.Field( - proto.STRING, - number=8, - ) - enable_category_filter_level = proto.Field( - proto.STRING, - number=16, - ) - solution_types = proto.RepeatedField( - proto.ENUM, - number=19, - enum=common.SolutionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py deleted file mode 100644 index 20edced0..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/serving_config_service.py +++ /dev/null @@ -1,234 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'CreateServingConfigRequest', - 'UpdateServingConfigRequest', - 'DeleteServingConfigRequest', - 'GetServingConfigRequest', - 'ListServingConfigsRequest', - 'ListServingConfigsResponse', - 'AddControlRequest', - 'RemoveControlRequest', - }, -) - - -class CreateServingConfigRequest(proto.Message): - r"""Request for CreateServingConfig method. - - Attributes: - parent (str): - Required. Full resource name of parent. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - serving_config (google.cloud.retail_v2beta.types.ServingConfig): - Required. The ServingConfig to create. - serving_config_id (str): - Required. The ID to use for the ServingConfig, which will - become the final component of the ServingConfig's resource - name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-_/. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - serving_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_serving_config.ServingConfig, - ) - serving_config_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateServingConfigRequest(proto.Message): - r"""Request for UpdateServingConfig method. - - Attributes: - serving_config (google.cloud.retail_v2beta.types.ServingConfig): - Required. The ServingConfig to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [ServingConfig][google.cloud.retail.v2beta.ServingConfig] to - update. The following are NOT supported: - - - [ServingConfig.name][google.cloud.retail.v2beta.ServingConfig.name] - - If not set, all supported fields are updated. - """ - - serving_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_serving_config.ServingConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteServingConfigRequest(proto.Message): - r"""Request for DeleteServingConfig method. - - Attributes: - name (str): - Required. The resource name of the ServingConfig to delete. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetServingConfigRequest(proto.Message): - r"""Request for GetServingConfig method. - - Attributes: - name (str): - Required. The resource name of the ServingConfig to get. - Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListServingConfigsRequest(proto.Message): - r"""Request for ListServingConfigs method. - - Attributes: - parent (str): - Required. The catalog resource name. Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id} - page_size (int): - Optional. Maximum number of results to - return. If unspecified, defaults to 100. If a - value greater than 100 is provided, at most 100 - results are returned. - page_token (str): - Optional. A page token, received from a previous - ``ListServingConfigs`` call. Provide this to retrieve the - subsequent page. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListServingConfigsResponse(proto.Message): - r"""Response for ListServingConfigs method. - - Attributes: - serving_configs (Sequence[google.cloud.retail_v2beta.types.ServingConfig]): - All the ServingConfigs for a given catalog. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - serving_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_serving_config.ServingConfig, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class AddControlRequest(proto.Message): - r"""Request for AddControl method. - - Attributes: - serving_config (str): - Required. The source ServingConfig resource name . Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - control_id (str): - Required. The id of the control to apply. Assumed to be in - the same catalog as the serving config - if id is not found - a NOT_FOUND error is returned. - """ - - serving_config = proto.Field( - proto.STRING, - number=1, - ) - control_id = proto.Field( - proto.STRING, - number=2, - ) - - -class RemoveControlRequest(proto.Message): - r"""Request for RemoveControl method. - - Attributes: - serving_config (str): - Required. The source ServingConfig resource name . Format: - projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id} - control_id (str): - Required. The id of the control to apply. - Assumed to be in the same catalog as the serving - config. - """ - - serving_config = proto.Field( - proto.STRING, - number=1, - ) - control_id = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py deleted file mode 100644 index bf1b1aee..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event.py +++ /dev/null @@ -1,507 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import product as gcr_product -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'UserEvent', - 'ProductDetail', - 'CompletionDetail', - 'PurchaseTransaction', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information Retail API needs - to know about how end users interact with customers' website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - - ``add-to-cart``: Products being added to cart. - - ``category-page-view``: Special pages such as sale or - promotion pages viewed. - - ``detail-page-view``: Products detail page viewed. - - ``home-page-view``: Homepage viewed. - - ``promotion-offered``: Promotion is offered to a user. - - ``promotion-not-offered``: Promotion is not offered to a - user. - - ``purchase-complete``: User finishing a purchase. - - ``search``: Product search. - - ``shopping-cart-page-view``: User viewing a shopping - cart. - visitor_id (str): - Required. A unique identifier for tracking visitors. - - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor log in/out of the website. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - The field should not contain PII or user-data. We recommend - to use Google Analystics `Client - ID `__ - for this field. - session_id (str): - A unique identifier for tracking a visitor session with a - length limit of 128 bytes. A session is an aggregation of an - end user behavior in a time span. - - A general guideline to populate the sesion_id: - - 1. If user has no activity for 30 min, a new session_id - should be assigned. - 2. The session_id should be unique across users, suggest use - uuid or add visitor_id as prefix. - event_time (google.protobuf.timestamp_pb2.Timestamp): - Only required for - [UserEventService.ImportUserEvents][google.cloud.retail.v2beta.UserEventService.ImportUserEvents] - method. Timestamp of when the user event happened. - experiment_ids (Sequence[str]): - A list of identifiers for the independent - experiment groups this user event belongs to. - This is used to distinguish between user events - associated with different experiment setups - (e.g. using Retail API, using different - recommendation models). - attribution_token (str): - Highly recommended for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2beta.PredictionService.Predict]. - This field enables accurate attribution of recommendation - model performance. - - The value must be a valid - [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] - for user events that are the result of - [PredictionService.Predict][google.cloud.retail.v2beta.PredictionService.Predict]. - The value must be a valid - [SearchResponse.attribution_token][google.cloud.retail.v2beta.SearchResponse.attribution_token] - for user events that are the result of - [SearchService.Search][google.cloud.retail.v2beta.SearchService.Search]. - - This token enables us to accurately attribute page view or - purchase back to the event and the particular predict - response containing this clicked/purchased product. If user - clicks on product K in the recommendation results, pass - [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] - as a URL parameter to product K's page. When recording - events on product K's page, log the - [PredictResponse.attribution_token][google.cloud.retail.v2beta.PredictResponse.attribution_token] - to this field. - product_details (Sequence[google.cloud.retail_v2beta.types.ProductDetail]): - The main product details related to the event. - - This field is required for the following event types: - - - ``add-to-cart`` - - ``detail-page-view`` - - ``purchase-complete`` - - ``search`` - - In a ``search`` event, this field represents the products - returned to the end user on the current page (the end user - may have not finished browsing the whole page yet). When a - new page is returned to the end user, after - pagination/filtering/ordering even for the same query, a new - ``search`` event with different - [product_details][google.cloud.retail.v2beta.UserEvent.product_details] - is desired. The end user may have not finished browsing the - whole page yet. - completion_detail (google.cloud.retail_v2beta.types.CompletionDetail): - The main auto-completion details related to the event. - - This field should be set for ``search`` event when - autocomplete function is enabled and the user clicks a - suggestion for search. - attributes (Mapping[str, google.cloud.retail_v2beta.types.CustomAttribute]): - Extra user event features to include in the recommendation - model. - - If you provide custom attributes for ingested user events, - also include them in the user events that you associate with - prediction requests. Custom attribute formatting must be - consistent between imported events and events provided with - prediction requests. This lets the Retail API use those - custom attributes when training models and serving - predictions, which helps improve recommendation quality. - - This field needs to pass all below criteria, otherwise an - INVALID_ARGUMENT error is returned: - - - The key must be a UTF-8 encoded string with a length - limit of 5,000 characters. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a UTF-8 - encoded string with a length limit of 256 characters. - - For number attributes, at most 400 values are allowed. - - For product recommendations, an example of extra user - information is traffic_channel, which is how a user arrives - at the site. Users can arrive at the site by coming to the - site directly, coming through Google search, or in other - ways. - cart_id (str): - The ID or name of the associated shopping cart. This ID is - used to associate multiple items added or present in the - cart before purchase. - - This can only be set for ``add-to-cart``, - ``purchase-complete``, or ``shopping-cart-page-view`` - events. - purchase_transaction (google.cloud.retail_v2beta.types.PurchaseTransaction): - A transaction represents the entire purchase transaction. - - Required for ``purchase-complete`` events. Other event types - should not set this field. Otherwise, an INVALID_ARGUMENT - error is returned. - search_query (str): - The user's search query. - - See - [SearchRequest.query][google.cloud.retail.v2beta.SearchRequest.query] - for definition. - - The value must be a UTF-8 encoded string with a length limit - of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - At least one of - [search_query][google.cloud.retail.v2beta.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2beta.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - products being filtered. - - See - [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - order_by (str): - The order in which products are returned. - - See - [SearchRequest.order_by][google.cloud.retail.v2beta.SearchRequest.order_by] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is - returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - offset (int): - An integer that specifies the current offset for pagination - (the 0-indexed starting location, amongst the products - deemed by the API as relevant). - - See - [SearchRequest.offset][google.cloud.retail.v2beta.SearchRequest.offset] - for definition. - - If this field is negative, an INVALID_ARGUMENT is returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - INVALID_ARGUMENT error is returned. - page_categories (Sequence[str]): - The categories associated with a category page. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: "pageCategories" : ["Sales > 2017 Black - Friday Deals"]. - - Required for ``category-page-view`` events. At least one of - [search_query][google.cloud.retail.v2beta.UserEvent.search_query] - or - [page_categories][google.cloud.retail.v2beta.UserEvent.page_categories] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an INVALID_ARGUMENT error is - returned. - user_info (google.cloud.retail_v2beta.types.UserInfo): - User information. - uri (str): - Complete URL (window.location.href) of the - user's current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. Maximum length - 5,000 characters. - referrer_uri (str): - The referrer URL of the current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. - page_view_id (str): - A unique ID of a web page view. - - This should be kept the same for all user events triggered - from the same pageview. For example, an item detail page - view could trigger multiple events as the user is browsing - the page. The ``pageViewId`` property should be kept the - same for all these events so that they can be grouped - together properly. - - When using the client side event reporting with JavaScript - pixel and Google Tag Manager, this value is filled in - automatically. - """ - - event_type = proto.Field( - proto.STRING, - number=1, - ) - visitor_id = proto.Field( - proto.STRING, - number=2, - ) - session_id = proto.Field( - proto.STRING, - number=21, - ) - event_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - experiment_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - attribution_token = proto.Field( - proto.STRING, - number=5, - ) - product_details = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='ProductDetail', - ) - completion_detail = proto.Field( - proto.MESSAGE, - number=22, - message='CompletionDetail', - ) - attributes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=common.CustomAttribute, - ) - cart_id = proto.Field( - proto.STRING, - number=8, - ) - purchase_transaction = proto.Field( - proto.MESSAGE, - number=9, - message='PurchaseTransaction', - ) - search_query = proto.Field( - proto.STRING, - number=10, - ) - filter = proto.Field( - proto.STRING, - number=16, - ) - order_by = proto.Field( - proto.STRING, - number=17, - ) - offset = proto.Field( - proto.INT32, - number=18, - ) - page_categories = proto.RepeatedField( - proto.STRING, - number=11, - ) - user_info = proto.Field( - proto.MESSAGE, - number=12, - message=common.UserInfo, - ) - uri = proto.Field( - proto.STRING, - number=13, - ) - referrer_uri = proto.Field( - proto.STRING, - number=14, - ) - page_view_id = proto.Field( - proto.STRING, - number=15, - ) - - -class ProductDetail(proto.Message): - r"""Detailed product information associated with a user event. - - Attributes: - product (google.cloud.retail_v2beta.types.Product): - Required. [Product][google.cloud.retail.v2beta.Product] - information. - - Required field(s): - - - [Product.id][google.cloud.retail.v2beta.Product.id] - - Optional override field(s): - - - [Product.price_info][google.cloud.retail.v2beta.Product.price_info] - - If any supported optional fields are provided, we will treat - them as a full override when looking up product information - from the catalog. Thus, it is important to ensure that the - overriding fields are accurate and complete. - - All other product fields are ignored and instead populated - via catalog lookup after event ingestion. - quantity (google.protobuf.wrappers_pb2.Int32Value): - Quantity of the product associated with the user event. - - For example, this field will be 2 if two products are added - to the shopping cart for ``purchase-complete`` event. - Required for ``add-to-cart`` and ``purchase-complete`` event - types. - """ - - product = proto.Field( - proto.MESSAGE, - number=1, - message=gcr_product.Product, - ) - quantity = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -class CompletionDetail(proto.Message): - r"""Detailed completion information including completion - attribution token and clicked completion info. - - Attributes: - completion_attribution_token (str): - Completion attribution token in - [CompleteQueryResponse.attribution_token][google.cloud.retail.v2beta.CompleteQueryResponse.attribution_token]. - selected_suggestion (str): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2beta.CompleteQueryResponse.CompletionResult.suggestion]. - selected_position (int): - End user selected - [CompleteQueryResponse.CompletionResult.suggestion][google.cloud.retail.v2beta.CompleteQueryResponse.CompletionResult.suggestion] - position, starting from 0. - """ - - completion_attribution_token = proto.Field( - proto.STRING, - number=1, - ) - selected_suggestion = proto.Field( - proto.STRING, - number=2, - ) - selected_position = proto.Field( - proto.INT32, - number=3, - ) - - -class PurchaseTransaction(proto.Message): - r"""A transaction represents the entire purchase transaction. - - Attributes: - id (str): - The transaction ID with a length limit of 128 - characters. - revenue (float): - Required. Total non-zero revenue or grand - total associated with the transaction. This - value include shipping, tax, or other - adjustments to total revenue that you want to - include as part of your revenue calculations. - tax (float): - All the taxes associated with the - transaction. - cost (float): - All the costs associated with the products. These can be - manufacturing costs, shipping expenses not borne by the end - user, or any other costs, such that: - - - Profit = - [revenue][google.cloud.retail.v2beta.PurchaseTransaction.revenue] - - - [tax][google.cloud.retail.v2beta.PurchaseTransaction.tax] - - - [cost][google.cloud.retail.v2beta.PurchaseTransaction.cost] - currency_code (str): - Required. Currency code. Use three-character - ISO-4217 code. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - revenue = proto.Field( - proto.FLOAT, - number=2, - ) - tax = proto.Field( - proto.FLOAT, - number=3, - ) - cost = proto.Field( - proto.FLOAT, - number=4, - ) - currency_code = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py b/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py deleted file mode 100644 index 990180c4..00000000 --- a/owl-bot-staging/v2beta/google/cloud/retail_v2beta/types/user_event_service.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.retail_v2beta.types import user_event as gcr_user_event - - -__protobuf__ = proto.module( - package='google.cloud.retail.v2beta', - manifest={ - 'WriteUserEventRequest', - 'CollectUserEventRequest', - 'RejoinUserEventsRequest', - 'RejoinUserEventsResponse', - 'RejoinUserEventsMetadata', - }, -) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (google.cloud.retail_v2beta.types.UserEvent): - Required. User event to write. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - - Attributes: - parent (str): - Required. The parent catalog name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event (str): - Required. URL encoded UserEvent proto with a - length limit of 2,000,000 characters. - uri (str): - The URL including cgi-parameters but - excluding the hash fragment with a length limit - of 5,000 characters. This is often more useful - than the referer URL, because many browsers only - send the domain for 3rd party requests. - ets (int): - The event timestamp in milliseconds. This - prevents browser caching of otherwise identical - get requests. The name is abbreviated to reduce - the payload bytes. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.STRING, - number=2, - ) - uri = proto.Field( - proto.STRING, - number=3, - ) - ets = proto.Field( - proto.INT64, - number=4, - ) - - -class RejoinUserEventsRequest(proto.Message): - r"""Request message for RejoinUserEvents method. - - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog``. - user_event_rejoin_scope (google.cloud.retail_v2beta.types.RejoinUserEventsRequest.UserEventRejoinScope): - The type of the user event rejoin to define the scope and - range of the user events to be rejoined with the latest - product catalog. Defaults to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not - set, or set to an invalid integer value. - """ - class UserEventRejoinScope(proto.Enum): - r"""The scope of user events to be rejoined with the latest product - catalog. If the rejoining aims at reducing number of unjoined - events, set UserEventRejoinScope to UNJOINED_EVENTS. If the - rejoining aims at correcting product catalog information in joined - events, set UserEventRejoinScope to JOINED_EVENTS. If all events - needs to be rejoined, set UserEventRejoinScope to - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED. - """ - USER_EVENT_REJOIN_SCOPE_UNSPECIFIED = 0 - JOINED_EVENTS = 1 - UNJOINED_EVENTS = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event_rejoin_scope = proto.Field( - proto.ENUM, - number=2, - enum=UserEventRejoinScope, - ) - - -class RejoinUserEventsResponse(proto.Message): - r"""Response message for RejoinUserEvents method. - - Attributes: - rejoined_user_events_count (int): - Number of user events that were joined with - latest product catalog. - """ - - rejoined_user_events_count = proto.Field( - proto.INT64, - number=1, - ) - - -class RejoinUserEventsMetadata(proto.Message): - r"""Metadata for RejoinUserEvents method. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta/mypy.ini b/owl-bot-staging/v2beta/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v2beta/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2beta/noxfile.py b/owl-bot-staging/v2beta/noxfile.py deleted file mode 100644 index 5abd48a4..00000000 --- a/owl-bot-staging/v2beta/noxfile.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.6", - "3.7", - "3.8", - "3.9", - "3.10", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==19.10b0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.9" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/retail_v2beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py deleted file mode 100644 index 09847366..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_AddCatalogAttribute_async] -from google.cloud import retail_v2beta - - -async def sample_add_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_AddCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py deleted file mode 100644 index 4f05ae26..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync] -from google.cloud import retail_v2beta - - -def sample_add_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.AddCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.add_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py deleted file mode 100644 index 637bfe3a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetAttributesConfig_async] -from google.cloud import retail_v2beta - - -async def sample_get_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetAttributesConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py deleted file mode 100644 index c347bee2..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_attributes_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetAttributesConfig_sync] -from google.cloud import retail_v2beta - - -def sample_get_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetAttributesConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetAttributesConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py deleted file mode 100644 index 2133e940..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetCompletionConfig_async] -from google.cloud import retail_v2beta - - -async def sample_get_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetCompletionConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py deleted file mode 100644 index bb9bf00d..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_completion_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetCompletionConfig_sync] -from google.cloud import retail_v2beta - - -def sample_get_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetCompletionConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetCompletionConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py deleted file mode 100644 index e598ec09..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_async.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetDefaultBranch_async] -from google.cloud import retail_v2beta - - -async def sample_get_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetDefaultBranchRequest( - ) - - # Make the request - response = await client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetDefaultBranch_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py deleted file mode 100644 index 6adcb072..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_get_default_branch_sync.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_GetDefaultBranch_sync] -from google.cloud import retail_v2beta - - -def sample_get_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetDefaultBranchRequest( - ) - - # Make the request - response = client.get_default_branch(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_GetDefaultBranch_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py deleted file mode 100644 index b4e3df0e..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_ListCatalogs_async] -from google.cloud import retail_v2beta - - -async def sample_list_catalogs(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_CatalogService_ListCatalogs_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py deleted file mode 100644 index d938f3ae..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_list_catalogs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCatalogs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_ListCatalogs_sync] -from google.cloud import retail_v2beta - - -def sample_list_catalogs(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListCatalogsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_catalogs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_CatalogService_ListCatalogs_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py deleted file mode 100644 index 032fb3c6..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async] -from google.cloud import retail_v2beta - - -async def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = await client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py deleted file mode 100644 index f1ecc22b..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync] -from google.cloud import retail_v2beta - - -def sample_remove_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveCatalogAttributeRequest( - attributes_config="attributes_config_value", - key="key_value", - ) - - # Make the request - response = client.remove_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py deleted file mode 100644 index 8a87262f..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReplaceCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async] -from google.cloud import retail_v2beta - - -async def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = await client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py deleted file mode 100644 index 24b38d05..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReplaceCatalogAttribute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync] -from google.cloud import retail_v2beta - - -def sample_replace_catalog_attribute(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog_attribute = retail_v2beta.CatalogAttribute() - catalog_attribute.key = "key_value" - - request = retail_v2beta.ReplaceCatalogAttributeRequest( - attributes_config="attributes_config_value", - catalog_attribute=catalog_attribute, - ) - - # Make the request - response = client.replace_catalog_attribute(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py deleted file mode 100644 index 6eec0779..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_async.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_SetDefaultBranch_async] -from google.cloud import retail_v2beta - - -async def sample_set_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.SetDefaultBranchRequest( - ) - - # Make the request - await client.set_default_branch(request=request) - - -# [END retail_v2beta_generated_CatalogService_SetDefaultBranch_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py deleted file mode 100644 index a3deb8fd..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_set_default_branch_sync.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetDefaultBranch -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_SetDefaultBranch_sync] -from google.cloud import retail_v2beta - - -def sample_set_default_branch(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.SetDefaultBranchRequest( - ) - - # Make the request - client.set_default_branch(request=request) - - -# [END retail_v2beta_generated_CatalogService_SetDefaultBranch_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py deleted file mode 100644 index b4a235ec..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async] -from google.cloud import retail_v2beta - - -async def sample_update_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - attributes_config = retail_v2beta.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2beta.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = await client.update_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py deleted file mode 100644 index 8f82ee5d..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_attributes_config_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttributesConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync] -from google.cloud import retail_v2beta - - -def sample_update_attributes_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - attributes_config = retail_v2beta.AttributesConfig() - attributes_config.name = "name_value" - - request = retail_v2beta.UpdateAttributesConfigRequest( - attributes_config=attributes_config, - ) - - # Make the request - response = client.update_attributes_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py deleted file mode 100644 index 772504ff..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateCatalog_async] -from google.cloud import retail_v2beta - - -async def sample_update_catalog(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - catalog = retail_v2beta.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2beta.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = await client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateCatalog_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py deleted file mode 100644 index ed59d356..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_catalog_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCatalog -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateCatalog_sync] -from google.cloud import retail_v2beta - - -def sample_update_catalog(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - catalog = retail_v2beta.Catalog() - catalog.name = "name_value" - catalog.display_name = "display_name_value" - - request = retail_v2beta.UpdateCatalogRequest( - catalog=catalog, - ) - - # Make the request - response = client.update_catalog(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateCatalog_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py deleted file mode 100644 index 377166a7..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async] -from google.cloud import retail_v2beta - - -async def sample_update_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceAsyncClient() - - # Initialize request argument(s) - completion_config = retail_v2beta.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2beta.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = await client.update_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py deleted file mode 100644 index f641f121..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_catalog_service_update_completion_config_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCompletionConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync] -from google.cloud import retail_v2beta - - -def sample_update_completion_config(): - # Create a client - client = retail_v2beta.CatalogServiceClient() - - # Initialize request argument(s) - completion_config = retail_v2beta.CompletionConfig() - completion_config.name = "name_value" - - request = retail_v2beta.UpdateCompletionConfigRequest( - completion_config=completion_config, - ) - - # Make the request - response = client.update_completion_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py deleted file mode 100644 index 96fdc6a6..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CompletionService_CompleteQuery_async] -from google.cloud import retail_v2beta - - -async def sample_complete_query(): - # Create a client - client = retail_v2beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py deleted file mode 100644 index afb0ba7d..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_complete_query_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CompletionService_CompleteQuery_sync] -from google.cloud import retail_v2beta - - -def sample_complete_query(): - # Create a client - client = retail_v2beta.CompletionServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.CompleteQueryRequest( - catalog="catalog_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py deleted file mode 100644 index 912753e9..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CompletionService_ImportCompletionData_async] -from google.cloud import retail_v2beta - - -async def sample_import_completion_data(): - # Create a client - client = retail_v2beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2beta.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CompletionService_ImportCompletionData_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py deleted file mode 100644 index 2cbd277d..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_completion_service_import_completion_data_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCompletionData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_CompletionService_ImportCompletionData_sync] -from google.cloud import retail_v2beta - - -def sample_import_completion_data(): - # Create a client - client = retail_v2beta.CompletionServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.CompletionDataInputConfig() - input_config.big_query_source.dataset_id = "dataset_id_value" - input_config.big_query_source.table_id = "table_id_value" - - request = retail_v2beta.ImportCompletionDataRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_completion_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_CompletionService_ImportCompletionData_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py deleted file mode 100644 index 51e0cb4f..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_CreateControl_async] -from google.cloud import retail_v2beta - - -async def sample_create_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = await client.create_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_CreateControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py deleted file mode 100644 index 8d16b152..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_create_control_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_CreateControl_sync] -from google.cloud import retail_v2beta - - -def sample_create_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateControlRequest( - parent="parent_value", - control=control, - control_id="control_id_value", - ) - - # Make the request - response = client.create_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_CreateControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py deleted file mode 100644 index cb18f6ba..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_DeleteControl_async] -from google.cloud import retail_v2beta - - -async def sample_delete_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteControlRequest( - name="name_value", - ) - - # Make the request - await client.delete_control(request=request) - - -# [END retail_v2beta_generated_ControlService_DeleteControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py deleted file mode 100644 index 8a0d4f56..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_delete_control_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_DeleteControl_sync] -from google.cloud import retail_v2beta - - -def sample_delete_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteControlRequest( - name="name_value", - ) - - # Make the request - client.delete_control(request=request) - - -# [END retail_v2beta_generated_ControlService_DeleteControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py deleted file mode 100644 index f9eeb9fd..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_GetControl_async] -from google.cloud import retail_v2beta - - -async def sample_get_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetControlRequest( - name="name_value", - ) - - # Make the request - response = await client.get_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_GetControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py deleted file mode 100644 index ee0de08a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_get_control_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_GetControl_sync] -from google.cloud import retail_v2beta - - -def sample_get_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetControlRequest( - name="name_value", - ) - - # Make the request - response = client.get_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_GetControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py deleted file mode 100644 index 9a645706..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListControls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_ListControls_async] -from google.cloud import retail_v2beta - - -async def sample_list_controls(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_ControlService_ListControls_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py deleted file mode 100644 index 97c8ba62..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_list_controls_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListControls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_ListControls_sync] -from google.cloud import retail_v2beta - - -def sample_list_controls(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListControlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_controls(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_ControlService_ListControls_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py deleted file mode 100644 index 9a42018c..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_UpdateControl_async] -from google.cloud import retail_v2beta - - -async def sample_update_control(): - # Create a client - client = retail_v2beta.ControlServiceAsyncClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateControlRequest( - control=control, - ) - - # Make the request - response = await client.update_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_UpdateControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py deleted file mode 100644 index 2a306202..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_control_service_update_control_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ControlService_UpdateControl_sync] -from google.cloud import retail_v2beta - - -def sample_update_control(): - # Create a client - client = retail_v2beta.ControlServiceClient() - - # Initialize request argument(s) - control = retail_v2beta.Control() - control.facet_spec.facet_key.key = "key_value" - control.display_name = "display_name_value" - control.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateControlRequest( - control=control, - ) - - # Make the request - response = client.update_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ControlService_UpdateControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py deleted file mode 100644 index fd37548f..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_PredictionService_Predict_async] -from google.cloud import retail_v2beta - - -async def sample_predict(): - # Create a client - client = retail_v2beta.PredictionServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = await client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py deleted file mode 100644 index 6975056e..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_prediction_service_predict_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Predict -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_PredictionService_Predict_sync] -from google.cloud import retail_v2beta - - -def sample_predict(): - # Create a client - client = retail_v2beta.PredictionServiceClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.PredictRequest( - placement="placement_value", - user_event=user_event, - ) - - # Make the request - response = client.predict(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py deleted file mode 100644 index 92a7a7e1..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async] -from google.cloud import retail_v2beta - - -async def sample_add_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py deleted file mode 100644 index d828edde..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync] -from google.cloud import retail_v2beta - - -def sample_add_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.add_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py deleted file mode 100644 index ebcf5c80..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_AddLocalInventories_async] -from google.cloud import retail_v2beta - - -async def sample_add_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_AddLocalInventories_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py deleted file mode 100644 index 9d3d9ab0..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_add_local_inventories_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_AddLocalInventories_sync] -from google.cloud import retail_v2beta - - -def sample_add_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddLocalInventoriesRequest( - product="product_value", - ) - - # Make the request - operation = client.add_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_AddLocalInventories_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py deleted file mode 100644 index 2bba20c0..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_CreateProduct_async] -from google.cloud import retail_v2beta - - -async def sample_create_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = await client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_CreateProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py deleted file mode 100644 index 32bd03e2..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_create_product_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_CreateProduct_sync] -from google.cloud import retail_v2beta - - -def sample_create_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.CreateProductRequest( - parent="parent_value", - product=product, - product_id="product_id_value", - ) - - # Make the request - response = client.create_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_CreateProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py deleted file mode 100644 index 8f9591fa..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_DeleteProduct_async] -from google.cloud import retail_v2beta - - -async def sample_delete_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteProductRequest( - name="name_value", - ) - - # Make the request - await client.delete_product(request=request) - - -# [END retail_v2beta_generated_ProductService_DeleteProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py deleted file mode 100644 index 56630734..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_delete_product_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_DeleteProduct_sync] -from google.cloud import retail_v2beta - - -def sample_delete_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteProductRequest( - name="name_value", - ) - - # Make the request - client.delete_product(request=request) - - -# [END retail_v2beta_generated_ProductService_DeleteProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py deleted file mode 100644 index f8dcfc01..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_GetProduct_async] -from google.cloud import retail_v2beta - - -async def sample_get_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_GetProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py deleted file mode 100644 index ab5cd918..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_get_product_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_GetProduct_sync] -from google.cloud import retail_v2beta - - -def sample_get_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_GetProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py deleted file mode 100644 index aa4256cc..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_ImportProducts_async] -from google.cloud import retail_v2beta - - -async def sample_import_products(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2beta.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_ImportProducts_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py deleted file mode 100644 index b4bc8314..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_import_products_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_ImportProducts_sync] -from google.cloud import retail_v2beta - - -def sample_import_products(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.ProductInputConfig() - input_config.product_inline_source.products.title = "title_value" - - request = retail_v2beta.ImportProductsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_products(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_ImportProducts_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py deleted file mode 100644 index e259ecd6..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_ListProducts_async] -from google.cloud import retail_v2beta - - -async def sample_list_products(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_ProductService_ListProducts_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py deleted file mode 100644 index 5cb40315..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_list_products_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_ListProducts_sync] -from google.cloud import retail_v2beta - - -def sample_list_products(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_ProductService_ListProducts_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py deleted file mode 100644 index 1b18eb50..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async] -from google.cloud import retail_v2beta - - -async def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py deleted file mode 100644 index f430e360..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveFulfillmentPlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync] -from google.cloud import retail_v2beta - - -def sample_remove_fulfillment_places(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveFulfillmentPlacesRequest( - product="product_value", - type_="type__value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_fulfillment_places(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py deleted file mode 100644 index 55fba819..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_RemoveLocalInventories_async] -from google.cloud import retail_v2beta - - -async def sample_remove_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_RemoveLocalInventories_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py deleted file mode 100644 index 31d1e58e..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_remove_local_inventories_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_RemoveLocalInventories_sync] -from google.cloud import retail_v2beta - - -def sample_remove_local_inventories(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveLocalInventoriesRequest( - product="product_value", - place_ids=['place_ids_value_1', 'place_ids_value_2'], - ) - - # Make the request - operation = client.remove_local_inventories(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_RemoveLocalInventories_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py deleted file mode 100644 index 9b467025..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_SetInventory_async] -from google.cloud import retail_v2beta - - -async def sample_set_inventory(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - inventory = retail_v2beta.Product() - inventory.title = "title_value" - - request = retail_v2beta.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_SetInventory_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py deleted file mode 100644 index d1061827..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_set_inventory_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_SetInventory_sync] -from google.cloud import retail_v2beta - - -def sample_set_inventory(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - inventory = retail_v2beta.Product() - inventory.title = "title_value" - - request = retail_v2beta.SetInventoryRequest( - inventory=inventory, - ) - - # Make the request - operation = client.set_inventory(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_SetInventory_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py deleted file mode 100644 index 8d9590cd..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_UpdateProduct_async] -from google.cloud import retail_v2beta - - -async def sample_update_product(): - # Create a client - client = retail_v2beta.ProductServiceAsyncClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.UpdateProductRequest( - product=product, - ) - - # Make the request - response = await client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_UpdateProduct_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py deleted file mode 100644 index fc614e58..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_product_service_update_product_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ProductService_UpdateProduct_sync] -from google.cloud import retail_v2beta - - -def sample_update_product(): - # Create a client - client = retail_v2beta.ProductServiceClient() - - # Initialize request argument(s) - product = retail_v2beta.Product() - product.title = "title_value" - - request = retail_v2beta.UpdateProductRequest( - product=product, - ) - - # Make the request - response = client.update_product(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ProductService_UpdateProduct_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py deleted file mode 100644 index 967c9102..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_async.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_SearchService_Search_async] -from google.cloud import retail_v2beta - - -async def sample_search(): - # Create a client - client = retail_v2beta.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_SearchService_Search_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py deleted file mode 100644 index 1e6a5045..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_search_service_search_sync.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_SearchService_Search_sync] -from google.cloud import retail_v2beta - - -def sample_search(): - # Create a client - client = retail_v2beta.SearchServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.SearchRequest( - placement="placement_value", - visitor_id="visitor_id_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py deleted file mode 100644 index d6554386..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_AddControl_async] -from google.cloud import retail_v2beta - - -async def sample_add_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.add_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_AddControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py deleted file mode 100644 index e61e4e2a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_add_control_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AddControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_AddControl_sync] -from google.cloud import retail_v2beta - - -def sample_add_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.AddControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.add_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_AddControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py deleted file mode 100644 index b09fadf2..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_CreateServingConfig_async] -from google.cloud import retail_v2beta - - -async def sample_create_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = await client.create_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_CreateServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py deleted file mode 100644 index 5d4c0993..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_create_serving_config_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync] -from google.cloud import retail_v2beta - - -def sample_create_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.CreateServingConfigRequest( - parent="parent_value", - serving_config=serving_config, - serving_config_id="serving_config_id_value", - ) - - # Make the request - response = client.create_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py deleted file mode 100644 index c0b03659..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_async.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async] -from google.cloud import retail_v2beta - - -async def sample_delete_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_serving_config(request=request) - - -# [END retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py deleted file mode 100644 index 1db19c0a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync] -from google.cloud import retail_v2beta - - -def sample_delete_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.DeleteServingConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_serving_config(request=request) - - -# [END retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py deleted file mode 100644 index 64f6aeef..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_GetServingConfig_async] -from google.cloud import retail_v2beta - - -async def sample_get_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_GetServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py deleted file mode 100644 index 1cfab934..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_get_serving_config_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_GetServingConfig_sync] -from google.cloud import retail_v2beta - - -def sample_get_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.GetServingConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_GetServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py deleted file mode 100644 index 7ad0a3aa..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServingConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_ListServingConfigs_async] -from google.cloud import retail_v2beta - - -async def sample_list_serving_configs(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END retail_v2beta_generated_ServingConfigService_ListServingConfigs_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py deleted file mode 100644 index 6a3e7e2a..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServingConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync] -from google.cloud import retail_v2beta - - -def sample_list_serving_configs(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.ListServingConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_serving_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py deleted file mode 100644 index c9994a00..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_RemoveControl_async] -from google.cloud import retail_v2beta - - -async def sample_remove_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = await client.remove_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_RemoveControl_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py deleted file mode 100644 index db6dfa93..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_remove_control_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RemoveControl -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_RemoveControl_sync] -from google.cloud import retail_v2beta - - -def sample_remove_control(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RemoveControlRequest( - serving_config="serving_config_value", - control_id="control_id_value", - ) - - # Make the request - response = client.remove_control(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_RemoveControl_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py deleted file mode 100644 index 2a6bd3a0..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async] -from google.cloud import retail_v2beta - - -async def sample_update_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceAsyncClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = await client.update_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py deleted file mode 100644 index f6441e46..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_serving_config_service_update_serving_config_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServingConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync] -from google.cloud import retail_v2beta - - -def sample_update_serving_config(): - # Create a client - client = retail_v2beta.ServingConfigServiceClient() - - # Initialize request argument(s) - serving_config = retail_v2beta.ServingConfig() - serving_config.display_name = "display_name_value" - serving_config.solution_types = "SOLUTION_TYPE_SEARCH" - - request = retail_v2beta.UpdateServingConfigRequest( - serving_config=serving_config, - ) - - # Make the request - response = client.update_serving_config(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py deleted file mode 100644 index ce80fabf..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_CollectUserEvent_async] -from google.cloud import retail_v2beta - - -async def sample_collect_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py deleted file mode 100644 index ff7df192..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_collect_user_event_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_CollectUserEvent_sync] -from google.cloud import retail_v2beta - - -def sample_collect_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py deleted file mode 100644 index 259c3424..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_ImportUserEvents_async] -from google.cloud import retail_v2beta - - -async def sample_import_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - input_config = retail_v2beta.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2beta.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py deleted file mode 100644 index 89e0ec02..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_import_user_events_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_ImportUserEvents_sync] -from google.cloud import retail_v2beta - - -def sample_import_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - input_config = retail_v2beta.UserEventInputConfig() - input_config.user_event_inline_source.user_events.event_type = "event_type_value" - input_config.user_event_inline_source.user_events.visitor_id = "visitor_id_value" - - request = retail_v2beta.ImportUserEventsRequest( - parent="parent_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py deleted file mode 100644 index 6f97cab1..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_PurgeUserEvents_async] -from google.cloud import retail_v2beta - - -async def sample_purge_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py deleted file mode 100644 index 212d2693..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_purge_user_events_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_PurgeUserEvents_sync] -from google.cloud import retail_v2beta - - -def sample_purge_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py deleted file mode 100644 index 8a95e668..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_RejoinUserEvents_async] -from google.cloud import retail_v2beta - - -async def sample_rejoin_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = retail_v2beta.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_RejoinUserEvents_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py deleted file mode 100644 index ebd635b8..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RejoinUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_RejoinUserEvents_sync] -from google.cloud import retail_v2beta - - -def sample_rejoin_user_events(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - request = retail_v2beta.RejoinUserEventsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.rejoin_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_RejoinUserEvents_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py deleted file mode 100644 index 71317cac..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_WriteUserEvent_async] -from google.cloud import retail_v2beta - - -async def sample_write_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py deleted file mode 100644 index e93e4df4..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/retail_v2beta_generated_user_event_service_write_user_event_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-retail - - -# [START retail_v2beta_generated_UserEventService_WriteUserEvent_sync] -from google.cloud import retail_v2beta - - -def sample_write_user_event(): - # Create a client - client = retail_v2beta.UserEventServiceClient() - - # Initialize request argument(s) - user_event = retail_v2beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.visitor_id = "visitor_id_value" - - request = retail_v2beta.WriteUserEventRequest( - parent="parent_value", - user_event=user_event, - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END retail_v2beta_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json b/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json deleted file mode 100644 index 591f20ca..00000000 --- a/owl-bot-staging/v2beta/samples/generated_samples/snippet_metadata_retail_v2beta.json +++ /dev/null @@ -1,6913 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.retail.v2beta", - "version": "v2beta" - } - ], - "language": "PYTHON", - "name": "google-cloud-retail" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.add_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "AddCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "add_catalog_attribute" - }, - "description": "Sample for AddCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_AddCatalogAttribute_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_add_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.add_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.AddCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "AddCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "add_catalog_attribute" - }, - "description": "Sample for AddCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_AddCatalogAttribute_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_add_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetAttributesConfigRequest" - }, - { - "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.retail_v2beta.types.AttributesConfig", - "shortName": "get_attributes_config" - }, - "description": "Sample for GetAttributesConfig", - "file": "retail_v2beta_generated_catalog_service_get_attributes_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetAttributesConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_attributes_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetAttributesConfigRequest" - }, - { - "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.retail_v2beta.types.AttributesConfig", - "shortName": "get_attributes_config" - }, - "description": "Sample for GetAttributesConfig", - "file": "retail_v2beta_generated_catalog_service_get_attributes_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetAttributesConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_attributes_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_completion_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetCompletionConfigRequest" - }, - { - "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.retail_v2beta.types.CompletionConfig", - "shortName": "get_completion_config" - }, - "description": "Sample for GetCompletionConfig", - "file": "retail_v2beta_generated_catalog_service_get_completion_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetCompletionConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_completion_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_completion_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetCompletionConfigRequest" - }, - { - "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.retail_v2beta.types.CompletionConfig", - "shortName": "get_completion_config" - }, - "description": "Sample for GetCompletionConfig", - "file": "retail_v2beta_generated_catalog_service_get_completion_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetCompletionConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_completion_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2beta_generated_catalog_service_get_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetDefaultBranch_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.get_default_branch", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.GetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "GetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.GetDefaultBranchResponse", - "shortName": "get_default_branch" - }, - "description": "Sample for GetDefaultBranch", - "file": "retail_v2beta_generated_catalog_service_get_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_GetDefaultBranch_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_get_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListCatalogsRequest" - }, - { - "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.retail_v2beta.services.catalog_service.pagers.ListCatalogsAsyncPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2beta_generated_catalog_service_list_catalogs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_ListCatalogs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_list_catalogs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.list_catalogs", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.ListCatalogs", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ListCatalogs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListCatalogsRequest" - }, - { - "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.retail_v2beta.services.catalog_service.pagers.ListCatalogsPager", - "shortName": "list_catalogs" - }, - "description": "Sample for ListCatalogs", - "file": "retail_v2beta_generated_catalog_service_list_catalogs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_ListCatalogs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_list_catalogs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.remove_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "RemoveCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "remove_catalog_attribute" - }, - "description": "Sample for RemoveCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.remove_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.RemoveCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "RemoveCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "remove_catalog_attribute" - }, - "description": "Sample for RemoveCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_RemoveCatalogAttribute_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_remove_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.replace_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ReplaceCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "replace_catalog_attribute" - }, - "description": "Sample for ReplaceCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.replace_catalog_attribute", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.ReplaceCatalogAttribute", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "ReplaceCatalogAttribute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ReplaceCatalogAttributeRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.AttributesConfig", - "shortName": "replace_catalog_attribute" - }, - "description": "Sample for ReplaceCatalogAttribute", - "file": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_ReplaceCatalogAttribute_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_replace_catalog_attribute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2beta_generated_catalog_service_set_default_branch_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_SetDefaultBranch_async", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_set_default_branch_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.set_default_branch", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.SetDefaultBranch", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "SetDefaultBranch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SetDefaultBranchRequest" - }, - { - "name": "catalog", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "set_default_branch" - }, - "description": "Sample for SetDefaultBranch", - "file": "retail_v2beta_generated_catalog_service_set_default_branch_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_SetDefaultBranch_sync", - "segments": [ - { - "end": 41, - "start": 27, - "type": "FULL" - }, - { - "end": 41, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_set_default_branch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest" - }, - { - "name": "attributes_config", - "type": "google.cloud.retail_v2beta.types.AttributesConfig" - }, - { - "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.retail_v2beta.types.AttributesConfig", - "shortName": "update_attributes_config" - }, - "description": "Sample for UpdateAttributesConfig", - "file": "retail_v2beta_generated_catalog_service_update_attributes_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateAttributesConfig_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_attributes_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_attributes_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateAttributesConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateAttributesConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateAttributesConfigRequest" - }, - { - "name": "attributes_config", - "type": "google.cloud.retail_v2beta.types.AttributesConfig" - }, - { - "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.retail_v2beta.types.AttributesConfig", - "shortName": "update_attributes_config" - }, - "description": "Sample for UpdateAttributesConfig", - "file": "retail_v2beta_generated_catalog_service_update_attributes_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateAttributesConfig_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_attributes_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2beta.types.Catalog" - }, - { - "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.retail_v2beta.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2beta_generated_catalog_service_update_catalog_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateCatalog_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_catalog_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_catalog", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCatalog", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCatalog" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateCatalogRequest" - }, - { - "name": "catalog", - "type": "google.cloud.retail_v2beta.types.Catalog" - }, - { - "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.retail_v2beta.types.Catalog", - "shortName": "update_catalog" - }, - "description": "Sample for UpdateCatalog", - "file": "retail_v2beta_generated_catalog_service_update_catalog_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateCatalog_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_catalog_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient", - "shortName": "CatalogServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceAsyncClient.update_completion_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest" - }, - { - "name": "completion_config", - "type": "google.cloud.retail_v2beta.types.CompletionConfig" - }, - { - "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.retail_v2beta.types.CompletionConfig", - "shortName": "update_completion_config" - }, - "description": "Sample for UpdateCompletionConfig", - "file": "retail_v2beta_generated_catalog_service_update_completion_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateCompletionConfig_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_completion_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient", - "shortName": "CatalogServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CatalogServiceClient.update_completion_config", - "method": { - "fullName": "google.cloud.retail.v2beta.CatalogService.UpdateCompletionConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.CatalogService", - "shortName": "CatalogService" - }, - "shortName": "UpdateCompletionConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateCompletionConfigRequest" - }, - { - "name": "completion_config", - "type": "google.cloud.retail_v2beta.types.CompletionConfig" - }, - { - "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.retail_v2beta.types.CompletionConfig", - "shortName": "update_completion_config" - }, - "description": "Sample for UpdateCompletionConfig", - "file": "retail_v2beta_generated_catalog_service_update_completion_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CatalogService_UpdateCompletionConfig_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_catalog_service_update_completion_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2beta.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2beta_generated_completion_service_complete_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CompletionService_CompleteQuery_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_completion_service_complete_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CompletionServiceClient.complete_query", - "method": { - "fullName": "google.cloud.retail.v2beta.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.retail.v2beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "retail_v2beta_generated_completion_service_complete_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CompletionService_CompleteQuery_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_completion_service_complete_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.CompletionServiceAsyncClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2beta.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2beta_generated_completion_service_import_completion_data_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CompletionService_ImportCompletionData_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_completion_service_import_completion_data_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.CompletionServiceClient.import_completion_data", - "method": { - "fullName": "google.cloud.retail.v2beta.CompletionService.ImportCompletionData", - "service": { - "fullName": "google.cloud.retail.v2beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "ImportCompletionData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportCompletionDataRequest" - }, - { - "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_completion_data" - }, - "description": "Sample for ImportCompletionData", - "file": "retail_v2beta_generated_completion_service_import_completion_data_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_CompletionService_ImportCompletionData_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_completion_service_import_completion_data_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.create_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.CreateControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "CreateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateControlRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "control", - "type": "google.cloud.retail_v2beta.types.Control" - }, - { - "name": "control_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.retail_v2beta.types.Control", - "shortName": "create_control" - }, - "description": "Sample for CreateControl", - "file": "retail_v2beta_generated_control_service_create_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_CreateControl_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_create_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.create_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.CreateControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "CreateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateControlRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "control", - "type": "google.cloud.retail_v2beta.types.Control" - }, - { - "name": "control_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.retail_v2beta.types.Control", - "shortName": "create_control" - }, - "description": "Sample for CreateControl", - "file": "retail_v2beta_generated_control_service_create_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_CreateControl_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_create_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.delete_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.DeleteControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "DeleteControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteControlRequest" - }, - { - "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_control" - }, - "description": "Sample for DeleteControl", - "file": "retail_v2beta_generated_control_service_delete_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_DeleteControl_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_delete_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.delete_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.DeleteControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "DeleteControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteControlRequest" - }, - { - "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_control" - }, - "description": "Sample for DeleteControl", - "file": "retail_v2beta_generated_control_service_delete_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_DeleteControl_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_delete_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.get_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.GetControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "GetControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetControlRequest" - }, - { - "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.retail_v2beta.types.Control", - "shortName": "get_control" - }, - "description": "Sample for GetControl", - "file": "retail_v2beta_generated_control_service_get_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_GetControl_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_get_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.get_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.GetControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "GetControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetControlRequest" - }, - { - "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.retail_v2beta.types.Control", - "shortName": "get_control" - }, - "description": "Sample for GetControl", - "file": "retail_v2beta_generated_control_service_get_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_GetControl_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_get_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.list_controls", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.ListControls", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "ListControls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListControlsRequest" - }, - { - "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.retail_v2beta.services.control_service.pagers.ListControlsAsyncPager", - "shortName": "list_controls" - }, - "description": "Sample for ListControls", - "file": "retail_v2beta_generated_control_service_list_controls_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_ListControls_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_list_controls_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.list_controls", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.ListControls", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "ListControls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListControlsRequest" - }, - { - "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.retail_v2beta.services.control_service.pagers.ListControlsPager", - "shortName": "list_controls" - }, - "description": "Sample for ListControls", - "file": "retail_v2beta_generated_control_service_list_controls_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_ListControls_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_list_controls_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient", - "shortName": "ControlServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceAsyncClient.update_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.UpdateControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "UpdateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateControlRequest" - }, - { - "name": "control", - "type": "google.cloud.retail_v2beta.types.Control" - }, - { - "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.retail_v2beta.types.Control", - "shortName": "update_control" - }, - "description": "Sample for UpdateControl", - "file": "retail_v2beta_generated_control_service_update_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_UpdateControl_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_update_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ControlServiceClient", - "shortName": "ControlServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ControlServiceClient.update_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ControlService.UpdateControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ControlService", - "shortName": "ControlService" - }, - "shortName": "UpdateControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateControlRequest" - }, - { - "name": "control", - "type": "google.cloud.retail_v2beta.types.Control" - }, - { - "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.retail_v2beta.types.Control", - "shortName": "update_control" - }, - "description": "Sample for UpdateControl", - "file": "retail_v2beta_generated_control_service_update_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ControlService_UpdateControl_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_control_service_update_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.PredictionServiceAsyncClient", - "shortName": "PredictionServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.PredictionServiceAsyncClient.predict", - "method": { - "fullName": "google.cloud.retail.v2beta.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2beta.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2beta_generated_prediction_service_predict_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_PredictionService_Predict_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_prediction_service_predict_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.PredictionServiceClient", - "shortName": "PredictionServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.PredictionServiceClient.predict", - "method": { - "fullName": "google.cloud.retail.v2beta.PredictionService.Predict", - "service": { - "fullName": "google.cloud.retail.v2beta.PredictionService", - "shortName": "PredictionService" - }, - "shortName": "Predict" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.PredictRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.PredictResponse", - "shortName": "predict" - }, - "description": "Sample for Predict", - "file": "retail_v2beta_generated_prediction_service_predict_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_PredictionService_Predict_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_prediction_service_predict_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2beta_generated_product_service_add_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_add_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.add_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.AddFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "add_fulfillment_places" - }, - "description": "Sample for AddFulfillmentPlaces", - "file": "retail_v2beta_generated_product_service_add_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_AddFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_add_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2beta_generated_product_service_add_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_AddLocalInventories_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_add_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.add_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.AddLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "AddLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddLocalInventoriesRequest" - }, - { - "name": "product", - "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": "add_local_inventories" - }, - "description": "Sample for AddLocalInventories", - "file": "retail_v2beta_generated_product_service_add_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_AddLocalInventories_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_add_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "name": "product_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.retail_v2beta.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2beta_generated_product_service_create_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_CreateProduct_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_create_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.create_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.CreateProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "CreateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateProductRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "product", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "name": "product_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.retail_v2beta.types.Product", - "shortName": "create_product" - }, - "description": "Sample for CreateProduct", - "file": "retail_v2beta_generated_product_service_create_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_CreateProduct_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_create_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2beta_generated_product_service_delete_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_DeleteProduct_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_delete_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.delete_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.DeleteProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "DeleteProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteProductRequest" - }, - { - "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_product" - }, - "description": "Sample for DeleteProduct", - "file": "retail_v2beta_generated_product_service_delete_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_DeleteProduct_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_delete_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetProductRequest" - }, - { - "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.retail_v2beta.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2beta_generated_product_service_get_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_GetProduct_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_get_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.get_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.GetProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetProductRequest" - }, - { - "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.retail_v2beta.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "retail_v2beta_generated_product_service_get_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_GetProduct_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_get_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2beta_generated_product_service_import_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_ImportProducts_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_import_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.import_products", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.ImportProducts", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "ImportProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportProductsRequest" - }, - { - "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_products" - }, - "description": "Sample for ImportProducts", - "file": "retail_v2beta_generated_product_service_import_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_ImportProducts_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_import_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListProductsRequest" - }, - { - "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.retail_v2beta.services.product_service.pagers.ListProductsAsyncPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2beta_generated_product_service_list_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_ListProducts_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_list_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.list_products", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.ListProducts", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListProductsRequest" - }, - { - "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.retail_v2beta.services.product_service.pagers.ListProductsPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "retail_v2beta_generated_product_service_list_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_ListProducts_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_list_products_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2beta_generated_product_service_remove_fulfillment_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_remove_fulfillment_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.remove_fulfillment_places", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.RemoveFulfillmentPlaces", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveFulfillmentPlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveFulfillmentPlacesRequest" - }, - { - "name": "product", - "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": "remove_fulfillment_places" - }, - "description": "Sample for RemoveFulfillmentPlaces", - "file": "retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_RemoveFulfillmentPlaces_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_remove_fulfillment_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2beta_generated_product_service_remove_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_RemoveLocalInventories_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_remove_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.remove_local_inventories", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.RemoveLocalInventories", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "RemoveLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveLocalInventoriesRequest" - }, - { - "name": "product", - "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": "remove_local_inventories" - }, - "description": "Sample for RemoveLocalInventories", - "file": "retail_v2beta_generated_product_service_remove_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_RemoveLocalInventories_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_remove_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2beta_generated_product_service_set_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_SetInventory_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_set_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.set_inventory", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.SetInventory", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "SetInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SetInventoryRequest" - }, - { - "name": "inventory", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "name": "set_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_inventory" - }, - "description": "Sample for SetInventory", - "file": "retail_v2beta_generated_product_service_set_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_SetInventory_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_set_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient", - "shortName": "ProductServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceAsyncClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "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.retail_v2beta.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2beta_generated_product_service_update_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_UpdateProduct_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_update_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ProductServiceClient", - "shortName": "ProductServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ProductServiceClient.update_product", - "method": { - "fullName": "google.cloud.retail.v2beta.ProductService.UpdateProduct", - "service": { - "fullName": "google.cloud.retail.v2beta.ProductService", - "shortName": "ProductService" - }, - "shortName": "UpdateProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateProductRequest" - }, - { - "name": "product", - "type": "google.cloud.retail_v2beta.types.Product" - }, - { - "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.retail_v2beta.types.Product", - "shortName": "update_product" - }, - "description": "Sample for UpdateProduct", - "file": "retail_v2beta_generated_product_service_update_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ProductService_UpdateProduct_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_product_service_update_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.SearchServiceAsyncClient.search", - "method": { - "fullName": "google.cloud.retail.v2beta.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2beta.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2beta_generated_search_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_SearchService_Search_async", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_search_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.SearchServiceClient", - "shortName": "SearchServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.SearchServiceClient.search", - "method": { - "fullName": "google.cloud.retail.v2beta.SearchService.Search", - "service": { - "fullName": "google.cloud.retail.v2beta.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.services.search_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "retail_v2beta_generated_search_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_SearchService_Search_sync", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_search_service_search_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.add_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.AddControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "AddControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "add_control" - }, - "description": "Sample for AddControl", - "file": "retail_v2beta_generated_serving_config_service_add_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_AddControl_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_add_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.add_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.AddControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "AddControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.AddControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "add_control" - }, - "description": "Sample for AddControl", - "file": "retail_v2beta_generated_serving_config_service_add_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_AddControl_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_add_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.create_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.CreateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "CreateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateServingConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2beta.types.ServingConfig" - }, - { - "name": "serving_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "create_serving_config" - }, - "description": "Sample for CreateServingConfig", - "file": "retail_v2beta_generated_serving_config_service_create_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_CreateServingConfig_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_create_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.create_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.CreateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "CreateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CreateServingConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2beta.types.ServingConfig" - }, - { - "name": "serving_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "create_serving_config" - }, - "description": "Sample for CreateServingConfig", - "file": "retail_v2beta_generated_serving_config_service_create_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_CreateServingConfig_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_create_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.delete_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.DeleteServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "DeleteServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteServingConfigRequest" - }, - { - "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_serving_config" - }, - "description": "Sample for DeleteServingConfig", - "file": "retail_v2beta_generated_serving_config_service_delete_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_DeleteServingConfig_async", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_delete_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.delete_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.DeleteServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "DeleteServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.DeleteServingConfigRequest" - }, - { - "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_serving_config" - }, - "description": "Sample for DeleteServingConfig", - "file": "retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_DeleteServingConfig_sync", - "segments": [ - { - "end": 42, - "start": 27, - "type": "FULL" - }, - { - "end": 42, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_delete_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.get_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.GetServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "GetServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetServingConfigRequest" - }, - { - "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.retail_v2beta.types.ServingConfig", - "shortName": "get_serving_config" - }, - "description": "Sample for GetServingConfig", - "file": "retail_v2beta_generated_serving_config_service_get_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_GetServingConfig_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_get_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.get_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.GetServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "GetServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.GetServingConfigRequest" - }, - { - "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.retail_v2beta.types.ServingConfig", - "shortName": "get_serving_config" - }, - "description": "Sample for GetServingConfig", - "file": "retail_v2beta_generated_serving_config_service_get_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_GetServingConfig_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_get_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.list_serving_configs", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.ListServingConfigs", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "ListServingConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListServingConfigsRequest" - }, - { - "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.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager", - "shortName": "list_serving_configs" - }, - "description": "Sample for ListServingConfigs", - "file": "retail_v2beta_generated_serving_config_service_list_serving_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_ListServingConfigs_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_list_serving_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.list_serving_configs", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.ListServingConfigs", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "ListServingConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ListServingConfigsRequest" - }, - { - "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.retail_v2beta.services.serving_config_service.pagers.ListServingConfigsPager", - "shortName": "list_serving_configs" - }, - "description": "Sample for ListServingConfigs", - "file": "retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_ListServingConfigs_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_list_serving_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.remove_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.RemoveControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "RemoveControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "remove_control" - }, - "description": "Sample for RemoveControl", - "file": "retail_v2beta_generated_serving_config_service_remove_control_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_RemoveControl_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_remove_control_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.remove_control", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.RemoveControl", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "RemoveControl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RemoveControlRequest" - }, - { - "name": "serving_config", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.ServingConfig", - "shortName": "remove_control" - }, - "description": "Sample for RemoveControl", - "file": "retail_v2beta_generated_serving_config_service_remove_control_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_RemoveControl_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_remove_control_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceAsyncClient.update_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.UpdateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "UpdateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2beta.types.ServingConfig" - }, - { - "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.retail_v2beta.types.ServingConfig", - "shortName": "update_serving_config" - }, - "description": "Sample for UpdateServingConfig", - "file": "retail_v2beta_generated_serving_config_service_update_serving_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_UpdateServingConfig_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_update_serving_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.ServingConfigServiceClient.update_serving_config", - "method": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService.UpdateServingConfig", - "service": { - "fullName": "google.cloud.retail.v2beta.ServingConfigService", - "shortName": "ServingConfigService" - }, - "shortName": "UpdateServingConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.retail_v2beta.types.ServingConfig" - }, - { - "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.retail_v2beta.types.ServingConfig", - "shortName": "update_serving_config" - }, - "description": "Sample for UpdateServingConfig", - "file": "retail_v2beta_generated_serving_config_service_update_serving_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_ServingConfigService_UpdateServingConfig_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_serving_config_service_update_serving_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2beta_generated_user_event_service_collect_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_CollectUserEvent_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_collect_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.collect_user_event", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "retail_v2beta_generated_user_event_service_collect_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_CollectUserEvent_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_collect_user_event_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2beta_generated_user_event_service_import_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_ImportUserEvents_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_import_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.import_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "retail_v2beta_generated_user_event_service_import_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_ImportUserEvents_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_import_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2beta_generated_user_event_service_purge_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_PurgeUserEvents_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_purge_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.purge_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "retail_v2beta_generated_user_event_service_purge_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_PurgeUserEvents_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_purge_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2beta_generated_user_event_service_rejoin_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_RejoinUserEvents_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_rejoin_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.rejoin_user_events", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.RejoinUserEvents", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "RejoinUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.RejoinUserEventsRequest" - }, - { - "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": "rejoin_user_events" - }, - "description": "Sample for RejoinUserEvents", - "file": "retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_RejoinUserEvents_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_rejoin_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceAsyncClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2beta_generated_user_event_service_write_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_WriteUserEvent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_write_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.retail_v2beta.UserEventServiceClient.write_user_event", - "method": { - "fullName": "google.cloud.retail.v2beta.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.retail.v2beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.retail_v2beta.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.retail_v2beta.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "retail_v2beta_generated_user_event_service_write_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "retail_v2beta_generated_UserEventService_WriteUserEvent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 43, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 44, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ], - "title": "retail_v2beta_generated_user_event_service_write_user_event_sync.py" - } - ] -} diff --git a/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py b/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py deleted file mode 100644 index dbd16de7..00000000 --- a/owl-bot-staging/v2beta/scripts/fixup_retail_v2beta_keywords.py +++ /dev/null @@ -1,218 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class retailCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_catalog_attribute': ('attributes_config', 'catalog_attribute', ), - 'add_control': ('serving_config', 'control_id', ), - 'add_fulfillment_places': ('product', 'type_', 'place_ids', 'add_time', 'allow_missing', ), - 'add_local_inventories': ('product', 'local_inventories', 'add_mask', 'add_time', 'allow_missing', ), - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'complete_query': ('catalog', 'query', 'visitor_id', 'language_codes', 'device_type', 'dataset', 'max_suggestions', ), - 'create_control': ('parent', 'control', 'control_id', ), - 'create_product': ('parent', 'product', 'product_id', ), - 'create_serving_config': ('parent', 'serving_config', 'serving_config_id', ), - 'delete_control': ('name', ), - 'delete_product': ('name', ), - 'delete_serving_config': ('name', ), - 'get_attributes_config': ('name', ), - 'get_completion_config': ('name', ), - 'get_control': ('name', ), - 'get_default_branch': ('catalog', ), - 'get_product': ('name', ), - 'get_serving_config': ('name', ), - 'import_completion_data': ('parent', 'input_config', 'notification_pubsub_topic', ), - 'import_products': ('parent', 'input_config', 'request_id', 'errors_config', 'update_mask', 'reconciliation_mode', 'notification_pubsub_topic', ), - 'import_user_events': ('parent', 'input_config', 'errors_config', ), - 'list_catalogs': ('parent', 'page_size', 'page_token', ), - 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_products': ('parent', 'page_size', 'page_token', 'filter', 'read_mask', ), - 'list_serving_configs': ('parent', 'page_size', 'page_token', ), - 'predict': ('placement', 'user_event', 'page_size', 'page_token', 'filter', 'validate_only', 'params', 'labels', ), - 'purge_user_events': ('parent', 'filter', 'force', ), - 'rejoin_user_events': ('parent', 'user_event_rejoin_scope', ), - 'remove_catalog_attribute': ('attributes_config', 'key', ), - 'remove_control': ('serving_config', 'control_id', ), - 'remove_fulfillment_places': ('product', 'type_', 'place_ids', 'remove_time', 'allow_missing', ), - 'remove_local_inventories': ('product', 'place_ids', 'remove_time', 'allow_missing', ), - 'replace_catalog_attribute': ('attributes_config', 'catalog_attribute', 'update_mask', ), - 'search': ('placement', 'visitor_id', 'branch', 'query', 'user_info', 'page_size', 'page_token', 'offset', 'filter', 'canonical_filter', 'order_by', 'facet_specs', 'dynamic_facet_spec', 'boost_spec', 'query_expansion_spec', 'variant_rollup_keys', 'page_categories', 'search_mode', 'personalization_spec', ), - 'set_default_branch': ('catalog', 'branch_id', 'note', 'force', ), - 'set_inventory': ('inventory', 'set_mask', 'set_time', 'allow_missing', ), - 'update_attributes_config': ('attributes_config', 'update_mask', ), - 'update_catalog': ('catalog', 'update_mask', ), - 'update_completion_config': ('completion_config', 'update_mask', ), - 'update_control': ('control', 'update_mask', ), - 'update_product': ('product', 'update_mask', 'allow_missing', ), - 'update_serving_config': ('serving_config', 'update_mask', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=retailCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the retail client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2beta/setup.py b/owl-bot-staging/v2beta/setup.py deleted file mode 100644 index 1103510b..00000000 --- a/owl-bot-staging/v2beta/setup.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-retail', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-retail", - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 2.8.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'googleapis-common-protos >= 1.55.0, <2.0.0dev', - 'proto-plus >= 1.19.7', - ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v2beta/tests/__init__.py b/owl-bot-staging/v2beta/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/tests/unit/__init__.py b/owl-bot-staging/v2beta/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py b/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py deleted file mode 100644 index f0c0245c..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_catalog_service.py +++ /dev/null @@ -1,3843 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.catalog_service import CatalogServiceAsyncClient -from google.cloud.retail_v2beta.services.catalog_service import CatalogServiceClient -from google.cloud.retail_v2beta.services.catalog_service import pagers -from google.cloud.retail_v2beta.services.catalog_service import transports -from google.cloud.retail_v2beta.types import catalog -from google.cloud.retail_v2beta.types import catalog as gcr_catalog -from google.cloud.retail_v2beta.types import catalog_service -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CatalogServiceClient._get_default_mtls_endpoint(None) is None - assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CatalogServiceGrpcTransport, "grpc"), - (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_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", [ - (CatalogServiceClient, "grpc"), - (CatalogServiceAsyncClient, "grpc_asyncio"), -]) -def test_catalog_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_catalog_service_client_get_transport_class(): - transport = CatalogServiceClient.get_transport_class() - available_transports = [ - transports.CatalogServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CatalogServiceClient.get_transport_class("grpc") - assert transport == transports.CatalogServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_catalog_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CatalogServiceClient, CatalogServiceAsyncClient -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_catalog_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", grpc_helpers), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_catalog_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ListCatalogsRequest, - dict, -]) -def test_list_catalogs(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalogs), - '__call__') as call: - client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - -@pytest.mark.asyncio -async def test_list_catalogs_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogsRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_catalogs_async_from_dict(): - await test_list_catalogs_async(request_type=dict) - - -def test_list_catalogs_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = catalog_service.ListCatalogsResponse() - client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - await client.list_catalogs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_catalogs_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_catalogs( - 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_catalogs_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_catalogs_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_catalogs( - 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_catalogs_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalogs( - catalog_service.ListCatalogsRequest(), - parent='parent_value', - ) - - -def test_list_catalogs_pager(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_catalogs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, catalog.Catalog) - for i in results) -def test_list_catalogs_pages(transport_name: str = "grpc"): - client = CatalogServiceClient( - 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_catalogs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = list(client.list_catalogs(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_catalogs_async_pager(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_catalogs(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, catalog.Catalog) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_catalogs_async_pages(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalogs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - catalog.Catalog(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogsResponse( - catalogs=[], - next_page_token='def', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogsResponse( - catalogs=[ - catalog.Catalog(), - catalog.Catalog(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_catalogs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCatalogRequest, - dict, -]) -def test_update_catalog(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - ) - response = client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_catalog_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_catalog), - '__call__') as call: - client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - -@pytest.mark.asyncio -async def test_update_catalog_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_catalog_async_from_dict(): - await test_update_catalog_async(request_type=dict) - - -def test_update_catalog_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = gcr_catalog.Catalog() - client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_catalog_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogRequest() - - request.catalog.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - await client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog.name=name_value', - ) in kw['metadata'] - - -def test_update_catalog_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_catalog_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_catalog.Catalog() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_catalog.Catalog()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_catalog( - catalog=gcr_catalog.Catalog(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].catalog - mock_val = gcr_catalog.Catalog(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_catalog_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog( - catalog_service.UpdateCatalogRequest(), - catalog=gcr_catalog.Catalog(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.SetDefaultBranchRequest, - dict, -]) -def test_set_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_set_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_set_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.SetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_set_default_branch_async_from_dict(): - await test_set_default_branch_async(request_type=dict) - - -def test_set_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = None - client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.SetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.set_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_set_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_set_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), - '__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.set_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetDefaultBranchRequest, - dict, -]) -def test_get_default_branch(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - ) - response = client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -def test_get_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_default_branch), - '__call__') as call: - client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - -@pytest.mark.asyncio -async def test_get_default_branch_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetDefaultBranchRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse( - branch='branch_value', - note='note_value', - )) - response = await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == 'branch_value' - assert response.note == 'note_value' - - -@pytest.mark.asyncio -async def test_get_default_branch_async_from_dict(): - await test_get_default_branch_async(request_type=dict) - - -def test_get_default_branch_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = catalog_service.GetDefaultBranchResponse() - client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_default_branch_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetDefaultBranchRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - await client.get_default_branch(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -def test_get_default_branch_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - - -def test_get_default_branch_flattened_error(): - client = CatalogServiceClient( - credentials=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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.GetDefaultBranchResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.GetDefaultBranchResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_default_branch( - catalog='catalog_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].catalog - mock_val = 'catalog_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_default_branch_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog='catalog_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetCompletionConfigRequest, - dict, -]) -def test_get_completion_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - ) - response = client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -def test_get_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_completion_config), - '__call__') as call: - client.get_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - -@pytest.mark.asyncio -async def test_get_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCompletionConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - )) - response = await client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -@pytest.mark.asyncio -async def test_get_completion_config_async_from_dict(): - await test_get_completion_config_async(request_type=dict) - - -def test_get_completion_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCompletionConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - call.return_value = catalog.CompletionConfig() - client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_completion_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCompletionConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - await client.get_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_completion_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_completion_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_completion_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_completion_config( - catalog_service.GetCompletionConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_completion_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_completion_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_completion_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_completion_config( - catalog_service.GetCompletionConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateCompletionConfigRequest, - dict, -]) -def test_update_completion_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - ) - response = client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -def test_update_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_completion_config), - '__call__') as call: - client.update_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - -@pytest.mark.asyncio -async def test_update_completion_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCompletionConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig( - name='name_value', - matching_order='matching_order_value', - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation='last_suggestions_import_operation_value', - last_denylist_import_operation='last_denylist_import_operation_value', - last_allowlist_import_operation='last_allowlist_import_operation_value', - )) - response = await client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == 'name_value' - assert response.matching_order == 'matching_order_value' - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert response.last_suggestions_import_operation == 'last_suggestions_import_operation_value' - assert response.last_denylist_import_operation == 'last_denylist_import_operation_value' - assert response.last_allowlist_import_operation == 'last_allowlist_import_operation_value' - - -@pytest.mark.asyncio -async def test_update_completion_config_async_from_dict(): - await test_update_completion_config_async(request_type=dict) - - -def test_update_completion_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCompletionConfigRequest() - - request.completion_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - call.return_value = catalog.CompletionConfig() - client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'completion_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_completion_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCompletionConfigRequest() - - request.completion_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - await client.update_completion_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'completion_config.name=name_value', - ) in kw['metadata'] - - -def test_update_completion_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_completion_config( - completion_config=catalog.CompletionConfig(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].completion_config - mock_val = catalog.CompletionConfig(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_completion_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_completion_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CompletionConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CompletionConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_completion_config( - completion_config=catalog.CompletionConfig(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].completion_config - mock_val = catalog.CompletionConfig(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_completion_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.GetAttributesConfigRequest, - dict, -]) -def test_get_attributes_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_get_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_attributes_config), - '__call__') as call: - client.get_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - -@pytest.mark.asyncio -async def test_get_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetAttributesConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_get_attributes_config_async_from_dict(): - await test_get_attributes_config_async(request_type=dict) - - -def test_get_attributes_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetAttributesConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_attributes_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetAttributesConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.get_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_attributes_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_attributes_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_attributes_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_attributes_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_attributes_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_attributes_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.UpdateAttributesConfigRequest, - dict, -]) -def test_update_attributes_config(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_update_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=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_attributes_config), - '__call__') as call: - client.update_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - -@pytest.mark.asyncio -async def test_update_attributes_config_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateAttributesConfigRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_update_attributes_config_async_from_dict(): - await test_update_attributes_config_async(request_type=dict) - - -def test_update_attributes_config_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateAttributesConfigRequest() - - request.attributes_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_attributes_config_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateAttributesConfigRequest() - - request.attributes_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.update_attributes_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config.name=name_value', - ) in kw['metadata'] - - -def test_update_attributes_config_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_attributes_config( - attributes_config=catalog.AttributesConfig(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].attributes_config - mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error(): - client = CatalogServiceClient( - credentials=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_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_attributes_config_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_attributes_config( - attributes_config=catalog.AttributesConfig(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].attributes_config - mock_val = catalog.AttributesConfig(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_attributes_config_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - catalog_service.AddCatalogAttributeRequest, - dict, -]) -def test_add_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_add_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - client.add_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_add_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.AddCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_add_catalog_attribute_async_from_dict(): - await test_add_catalog_attribute_async(request_type=dict) - - -def test_add_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.AddCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.AddCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.add_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - catalog_service.RemoveCatalogAttributeRequest, - dict, -]) -def test_remove_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_remove_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - client.remove_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.RemoveCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_async_from_dict(): - await test_remove_catalog_attribute_async(request_type=dict) - - -def test_remove_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.RemoveCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.RemoveCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - catalog_service.ReplaceCatalogAttributeRequest, - dict, -]) -def test_replace_catalog_attribute(request_type, transport: str = 'grpc'): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - response = client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -def test_replace_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - client.replace_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ReplaceCatalogAttributeRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig( - name='name_value', - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - )) - response = await client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == 'name_value' - assert response.attribute_config_level == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_async_from_dict(): - await test_replace_catalog_attribute_async(request_type=dict) - - -def test_replace_catalog_attribute_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ReplaceCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - call.return_value = catalog.AttributesConfig() - client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_replace_catalog_attribute_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ReplaceCatalogAttributeRequest() - - request.attributes_config = 'attributes_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.AttributesConfig()) - await client.replace_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'attributes_config=attributes_config_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CatalogServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.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 = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CatalogServiceGrpcTransport, - ) - -def test_catalog_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_catalog_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_catalogs', - 'update_catalog', - 'set_default_branch', - 'get_default_branch', - 'get_completion_config', - 'update_completion_config', - 'get_attributes_config', - 'update_attributes_config', - 'add_catalog_attribute', - 'remove_catalog_attribute', - 'replace_catalog_attribute', - ) - 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_catalog_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.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport( - 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_catalog_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.retail_v2beta.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport() - adc.assert_called_once() - - -def test_catalog_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) - CatalogServiceClient() - 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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -def test_catalog_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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -def test_catalog_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.CatalogServiceGrpcTransport, grpc_helpers), - (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_catalog_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_no_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_catalog_service_host_with_port(transport_name): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_catalog_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcTransport( - 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_catalog_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcAsyncIOTransport( - 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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_attributes_config_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.attributes_config_path(project, location, catalog) - assert expected == actual - - -def test_parse_attributes_config_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CatalogServiceClient.attributes_config_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_attributes_config_path(path) - assert expected == actual - -def test_branch_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = CatalogServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "branch": "clam", - } - path = CatalogServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_branch_path(path) - assert expected == actual - -def test_catalog_path(): - project = "whelk" - location = "octopus" - catalog = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - } - path = CatalogServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_completion_config_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.completion_config_path(project, location, catalog) - assert expected == actual - - -def test_parse_completion_config_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - } - path = CatalogServiceClient.completion_config_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_completion_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CatalogServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = CatalogServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = CatalogServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = CatalogServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CatalogServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = CatalogServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = CatalogServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = CatalogServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = CatalogServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CatalogServiceClient.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 = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CatalogServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = CatalogServiceClient( - 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", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py deleted file mode 100644 index 49aa7f73..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_completion_service.py +++ /dev/null @@ -1,1501 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.completion_service import CompletionServiceAsyncClient -from google.cloud.retail_v2beta.services.completion_service import CompletionServiceClient -from google.cloud.retail_v2beta.services.completion_service import transports -from google.cloud.retail_v2beta.types import completion_service -from google.cloud.retail_v2beta.types import import_config -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CompletionServiceClient._get_default_mtls_endpoint(None) is None - assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CompletionServiceGrpcTransport, "grpc"), - (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), -]) -def test_completion_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_completion_service_client_get_transport_class(): - transport = CompletionServiceClient.get_transport_class() - available_transports = [ - transports.CompletionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CompletionServiceClient.get_transport_class("grpc") - assert transport == transports.CompletionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(CompletionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_completion_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CompletionServiceClient, CompletionServiceAsyncClient -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_completion_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_completion_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CompletionServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - ) - response = client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - -@pytest.mark.asyncio -async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( - attribution_token='attribution_token_value', - )) - response = await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == 'attribution_token_value' - - -@pytest.mark.asyncio -async def test_complete_query_async_from_dict(): - await test_complete_query_async(request_type=dict) - - -def test_complete_query_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = completion_service.CompleteQueryResponse() - client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_complete_query_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.catalog = 'catalog_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) - await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'catalog=catalog_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportCompletionDataRequest, - dict, -]) -def test_import_completion_data(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_completion_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - -@pytest.mark.asyncio -async def test_import_completion_data_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportCompletionDataRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_completion_data_async_from_dict(): - await test_import_completion_data_async(request_type=dict) - - -def test_import_completion_data_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # 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_completion_data_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportCompletionDataRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_completion_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CompletionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CompletionServiceGrpcTransport, - ) - -def test_completion_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_completion_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'complete_query', - 'import_completion_data', - ) - 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_completion_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_completion_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport() - adc.assert_called_once() - - -def test_completion_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CompletionServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionServiceGrpcTransport, grpc_helpers), - (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_completion_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_no_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_completion_service_host_with_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_completion_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_completion_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_completion_service_grpc_lro_client(): - client = CompletionServiceClient( - 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_completion_service_grpc_lro_async_client(): - client = CompletionServiceAsyncClient( - 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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CompletionServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CompletionServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CompletionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CompletionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = CompletionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CompletionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CompletionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CompletionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = CompletionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CompletionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CompletionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CompletionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CompletionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py deleted file mode 100644 index 0c2700da..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_control_service.py +++ /dev/null @@ -1,2604 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.control_service import ControlServiceAsyncClient -from google.cloud.retail_v2beta.services.control_service import ControlServiceClient -from google.cloud.retail_v2beta.services.control_service import pagers -from google.cloud.retail_v2beta.services.control_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import control -from google.cloud.retail_v2beta.types import control as gcr_control -from google.cloud.retail_v2beta.types import control_service -from google.cloud.retail_v2beta.types import search_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ControlServiceClient._get_default_mtls_endpoint(None) is None - assert ControlServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ControlServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ControlServiceClient, "grpc"), - (ControlServiceAsyncClient, "grpc_asyncio"), -]) -def test_control_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ControlServiceGrpcTransport, "grpc"), - (transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_control_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", [ - (ControlServiceClient, "grpc"), - (ControlServiceAsyncClient, "grpc_asyncio"), -]) -def test_control_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_control_service_client_get_transport_class(): - transport = ControlServiceClient.get_transport_class() - available_transports = [ - transports.ControlServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ControlServiceClient.get_transport_class("grpc") - assert transport == transports.ControlServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -def test_control_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(ControlServiceClient, '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(ControlServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "true"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", "false"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_control_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ControlServiceClient, ControlServiceAsyncClient -]) -@mock.patch.object(ControlServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceClient)) -@mock.patch.object(ControlServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ControlServiceAsyncClient)) -def test_control_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc"), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_control_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_control_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_control_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.control_service.transports.ControlServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ControlServiceClient( - 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", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport, "grpc", grpc_helpers), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_control_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.CreateControlRequest, - dict, -]) -def test_create_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_create_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.create_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - -@pytest.mark.asyncio -async def test_create_control_async(transport: str = 'grpc_asyncio', request_type=control_service.CreateControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_create_control_async_from_dict(): - await test_create_control_async(request_type=dict) - - -def test_create_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.CreateControlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - call.return_value = gcr_control.Control() - client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.CreateControlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - await client.create_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_control( - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) - assert arg == mock_val - arg = args[0].control_id - mock_val = 'control_id_value' - assert arg == mock_val - - -def test_create_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.CreateControlRequest(), - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_id_value', - ) - -@pytest.mark.asyncio -async def test_create_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_control( - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))) - assert arg == mock_val - arg = args[0].control_id - mock_val = 'control_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.CreateControlRequest(), - parent='parent_value', - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - control_id='control_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.DeleteControlRequest, - dict, -]) -def test_delete_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.delete_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - -@pytest.mark.asyncio -async def test_delete_control_async(transport: str = 'grpc_asyncio', request_type=control_service.DeleteControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_control_async_from_dict(): - await test_delete_control_async(request_type=dict) - - -def test_delete_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.DeleteControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__call__') as call: - call.return_value = None - client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.DeleteControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__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_control( - 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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.DeleteControlRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_control), - '__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_control( - 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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.DeleteControlRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.UpdateControlRequest, - dict, -]) -def test_update_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_update_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.update_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - -@pytest.mark.asyncio -async def test_update_control_async(transport: str = 'grpc_asyncio', request_type=control_service.UpdateControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_update_control_async_from_dict(): - await test_update_control_async(request_type=dict) - - -def test_update_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.UpdateControlRequest() - - request.control.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - call.return_value = gcr_control.Control() - client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'control.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.UpdateControlRequest() - - request.control.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - await client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'control.name=name_value', - ) in kw['metadata'] - - -def test_update_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_control( - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_control( - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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].control - mock_val = gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control(facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value'))), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.GetControlRequest, - dict, -]) -def test_get_control(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - facet_spec=search_service.SearchRequest.FacetSpec(facet_key=search_service.SearchRequest.FacetSpec.FacetKey(key='key_value')), - ) - response = client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_get_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_control), - '__call__') as call: - client.get_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - -@pytest.mark.asyncio -async def test_get_control_async(transport: str = 'grpc_asyncio', request_type=control_service.GetControlRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control.Control( - name='name_value', - display_name='display_name_value', - associated_serving_config_ids=['associated_serving_config_ids_value'], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.associated_serving_config_ids == ['associated_serving_config_ids_value'] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_get_control_async_from_dict(): - await test_get_control_async(request_type=dict) - - -def test_get_control_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.GetControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - call.return_value = control.Control() - client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_control_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.GetControlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) - await client.get_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_control_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_control( - 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_control_flattened_error(): - client = ControlServiceClient( - credentials=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_control( - control_service.GetControlRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_control_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control.Control() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control.Control()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_control( - 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_control_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_control( - control_service.GetControlRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - control_service.ListControlsRequest, - dict, -]) -def test_list_controls(request_type, transport: str = 'grpc'): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_controls_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=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_controls), - '__call__') as call: - client.list_controls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - -@pytest.mark.asyncio -async def test_list_controls_async(transport: str = 'grpc_asyncio', request_type=control_service.ListControlsRequest): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_controls_async_from_dict(): - await test_list_controls_async(request_type=dict) - - -def test_list_controls_field_headers(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.ListControlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - call.return_value = control_service.ListControlsResponse() - client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_controls_field_headers_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = control_service.ListControlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) - await client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_controls_flattened(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_controls( - 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_controls_flattened_error(): - client = ControlServiceClient( - credentials=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_controls( - control_service.ListControlsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_controls_flattened_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = control_service.ListControlsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(control_service.ListControlsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_controls( - 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_controls_flattened_error_async(): - client = ControlServiceAsyncClient( - credentials=ga_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_controls( - control_service.ListControlsRequest(), - parent='parent_value', - ) - - -def test_list_controls_pager(transport_name: str = "grpc"): - client = ControlServiceClient( - 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_controls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_controls(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, control.Control) - for i in results) -def test_list_controls_pages(transport_name: str = "grpc"): - client = ControlServiceClient( - 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_controls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - pages = list(client.list_controls(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_controls_async_pager(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_controls(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, control.Control) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_controls_async_pages(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_controls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token='abc', - ), - control_service.ListControlsResponse( - controls=[], - next_page_token='def', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token='ghi', - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_controls(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ControlServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ControlServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ControlServiceClient.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 = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ControlServiceGrpcTransport, - ) - -def test_control_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ControlServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_control_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.control_service.transports.ControlServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ControlServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_control', - 'delete_control', - 'update_control', - 'get_control', - 'list_controls', - ) - 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_control_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.retail_v2beta.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ControlServiceTransport( - 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_control_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.retail_v2beta.services.control_service.transports.ControlServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ControlServiceTransport() - adc.assert_called_once() - - -def test_control_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) - ControlServiceClient() - 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.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - ], -) -def test_control_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.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - ], -) -def test_control_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.ControlServiceGrpcTransport, grpc_helpers), - (transports.ControlServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_control_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_control_service_host_no_port(transport_name): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_control_service_host_with_port(transport_name): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_control_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ControlServiceGrpcTransport( - 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_control_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ControlServiceGrpcAsyncIOTransport( - 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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport]) -def test_control_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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = ControlServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = ControlServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_control_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - control = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}".format(project=project, location=location, catalog=catalog, control=control, ) - actual = ControlServiceClient.control_path(project, location, catalog, control) - assert expected == actual - - -def test_parse_control_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "control": "clam", - } - path = ControlServiceClient.control_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_control_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ControlServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ControlServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ControlServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ControlServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ControlServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ControlServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ControlServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ControlServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.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 = ControlServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ControlServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ControlServiceClient.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.ControlServiceTransport, '_prep_wrapped_messages') as prep: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ControlServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ControlServiceClient.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 = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ControlServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ControlServiceClient( - 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", [ - (ControlServiceClient, transports.ControlServiceGrpcTransport), - (ControlServiceAsyncClient, transports.ControlServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py deleted file mode 100644 index 8e7a1380..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_prediction_service.py +++ /dev/null @@ -1,1329 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.prediction_service import PredictionServiceAsyncClient -from google.cloud.retail_v2beta.services.prediction_service import PredictionServiceClient -from google.cloud.retail_v2beta.services.prediction_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import prediction_service -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import promotion -from google.cloud.retail_v2beta.types import user_event -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PredictionServiceClient._get_default_mtls_endpoint(None) is None - assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PredictionServiceGrpcTransport, "grpc"), - (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_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", [ - (PredictionServiceClient, "grpc"), - (PredictionServiceAsyncClient, "grpc_asyncio"), -]) -def test_prediction_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_prediction_service_client_get_transport_class(): - transport = PredictionServiceClient.get_transport_class() - available_transports = [ - transports.PredictionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = PredictionServiceClient.get_transport_class("grpc") - assert transport == transports.PredictionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_prediction_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - PredictionServiceClient, PredictionServiceAsyncClient -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_prediction_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_prediction_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - prediction_service.PredictRequest, - dict, -]) -def test_predict(request_type, transport: str = 'grpc'): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - response = client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - -@pytest.mark.asyncio -async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - )) - response = await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -@pytest.mark.asyncio -async def test_predict_async_from_dict(): - await test_predict_async(request_type=dict) - - -def test_predict_field_headers(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = prediction_service.PredictResponse() - client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_predict_field_headers_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) - await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PredictionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PredictionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.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 = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, - ) - -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'predict', - ) - 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport( - 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport() - adc.assert_called_once() - - -def test_prediction_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) - PredictionServiceClient() - 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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -def test_prediction_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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -def test_prediction_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.PredictionServiceGrpcTransport, grpc_helpers), - (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_prediction_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_no_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_prediction_service_host_with_port(transport_name): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_prediction_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcTransport( - 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_prediction_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcAsyncIOTransport( - 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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_product_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - product = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = PredictionServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - "branch": "winkle", - "product": "nautilus", - } - path = PredictionServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PredictionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = PredictionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = PredictionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = PredictionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PredictionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = PredictionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = PredictionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = PredictionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = PredictionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = PredictionServiceClient.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 = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PredictionServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = PredictionServiceClient( - 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", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py deleted file mode 100644 index 59b69742..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_product_service.py +++ /dev/null @@ -1,4135 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.product_service import ProductServiceAsyncClient -from google.cloud.retail_v2beta.services.product_service import ProductServiceClient -from google.cloud.retail_v2beta.services.product_service import pagers -from google.cloud.retail_v2beta.services.product_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import product as gcr_product -from google.cloud.retail_v2beta.types import product_service -from google.cloud.retail_v2beta.types import promotion -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ProductServiceClient._get_default_mtls_endpoint(None) is None - assert ProductServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProductServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ProductServiceGrpcTransport, "grpc"), - (transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_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", [ - (ProductServiceClient, "grpc"), - (ProductServiceAsyncClient, "grpc_asyncio"), -]) -def test_product_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_product_service_client_get_transport_class(): - transport = ProductServiceClient.get_transport_class() - available_transports = [ - transports.ProductServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ProductServiceClient.get_transport_class("grpc") - assert transport == transports.ProductServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_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(ProductServiceClient, '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(ProductServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "true"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", "false"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ProductServiceClient, ProductServiceAsyncClient -]) -@mock.patch.object(ProductServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceClient)) -@mock.patch.object(ProductServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductServiceAsyncClient)) -def test_product_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc"), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_product_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_product_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.product_service.transports.ProductServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport, "grpc", grpc_helpers), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.CreateProductRequest, - dict, -]) -def test_create_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_create_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - -@pytest.mark.asyncio -async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_service.CreateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_create_product_async_from_dict(): - await test_create_product_async(request_type=dict) - - -def test_create_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.CreateProductRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - - -def test_create_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - -@pytest.mark.asyncio -async def test_create_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_product( - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].product_id - mock_val = 'product_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.CreateProductRequest(), - parent='parent_value', - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - product_id='product_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.GetProductRequest, - dict, -]) -def test_get_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_get_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - -@pytest.mark.asyncio -async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_service.GetProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product.Product( - name='name_value', - id='id_value', - type_=product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_get_product_async_from_dict(): - await test_get_product_async(request_type=dict) - - -def test_get_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = product.Product() - client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.GetProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.GetProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.ListProductsRequest, - dict, -]) -def test_list_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - -@pytest.mark.asyncio -async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_service.ListProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_products_async_from_dict(): - await test_list_products_async(request_type=dict) - - -def test_list_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = product_service.ListProductsResponse() - client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_products( - 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_products_flattened_error(): - client = ProductServiceClient( - credentials=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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_products_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = product_service.ListProductsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_service.ListProductsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_products( - 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_products_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_products( - product_service.ListProductsRequest(), - parent='parent_value', - ) - - -def test_list_products_pager(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_products(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, product.Product) - for i in results) -def test_list_products_pages(transport_name: str = "grpc"): - client = ProductServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = list(client.list_products(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_products_async_pager(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_products(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, product.Product) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_products_async_pages(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token='abc', - ), - product_service.ListProductsResponse( - products=[], - next_page_token='def', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token='ghi', - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_products(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - product_service.UpdateProductRequest, - dict, -]) -def test_update_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - expire_time=timestamp_pb2.Timestamp(seconds=751), - ) - response = client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -def test_update_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - -@pytest.mark.asyncio -async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_service.UpdateProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product( - name='name_value', - id='id_value', - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id='primary_product_id_value', - collection_member_ids=['collection_member_ids_value'], - gtin='gtin_value', - categories=['categories_value'], - title='title_value', - brands=['brands_value'], - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - availability=gcr_product.Product.Availability.IN_STOCK, - uri='uri_value', - sizes=['sizes_value'], - materials=['materials_value'], - patterns=['patterns_value'], - conditions=['conditions_value'], - )) - response = await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == 'primary_product_id_value' - assert response.collection_member_ids == ['collection_member_ids_value'] - assert response.gtin == 'gtin_value' - assert response.categories == ['categories_value'] - assert response.title == 'title_value' - assert response.brands == ['brands_value'] - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == 'uri_value' - assert response.sizes == ['sizes_value'] - assert response.materials == ['materials_value'] - assert response.patterns == ['patterns_value'] - assert response.conditions == ['conditions_value'] - - -@pytest.mark.asyncio -async def test_update_product_async_from_dict(): - await test_update_product_async(request_type=dict) - - -def test_update_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = gcr_product.Product() - client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.UpdateProductRequest() - - request.product.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - await client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product.name=name_value', - ) in kw['metadata'] - - -def test_update_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_product.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_product.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_product( - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - 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].product - mock_val = gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.DeleteProductRequest, - dict, -]) -def test_delete_product(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_product), - '__call__') as call: - client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - -@pytest.mark.asyncio -async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_service.DeleteProductRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_product_async_from_dict(): - await test_delete_product_async(request_type=dict) - - -def test_delete_product_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = None - client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_product_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.DeleteProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_product_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error(): - client = ProductServiceClient( - credentials=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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_product_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product), - '__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_product( - 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_product_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_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_product( - product_service.DeleteProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportProductsRequest, - dict, -]) -def test_import_products(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=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_products), - '__call__') as call: - client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - -@pytest.mark.asyncio -async def test_import_products_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportProductsRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__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_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_products_async_from_dict(): - await test_import_products_async(request_type=dict) - - -def test_import_products_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ImportProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - product_service.SetInventoryRequest, - dict, -]) -def test_set_inventory(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_inventory_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - -@pytest.mark.asyncio -async def test_set_inventory_async(transport: str = 'grpc_asyncio', request_type=product_service.SetInventoryRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_inventory_async_from_dict(): - await test_set_inventory_async(request_type=dict) - - -def test_set_inventory_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_inventory_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.SetInventoryRequest() - - request.inventory.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'inventory.name=name_value', - ) in kw['metadata'] - - -def test_set_inventory_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_set_inventory_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_set_inventory_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_inventory( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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].inventory - mock_val = product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)) - assert arg == mock_val - arg = args[0].set_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_inventory_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddFulfillmentPlacesRequest, - dict, -]) -def test_add_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.AddFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_async_from_dict(): - await test_add_fulfillment_places_async(request_type=dict) - - -def test_add_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), - '__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.add_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveFulfillmentPlacesRequest, - dict, -]) -def test_remove_fulfillment_places(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveFulfillmentPlacesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_async_from_dict(): - await test_remove_fulfillment_places_async(request_type=dict) - - -def test_remove_fulfillment_places_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveFulfillmentPlacesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_fulfillment_places_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_fulfillment_places_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), - '__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.remove_fulfillment_places( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_fulfillment_places_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.AddLocalInventoriesRequest, - dict, -]) -def test_add_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_add_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_add_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.AddLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_add_local_inventories_async_from_dict(): - await test_add_local_inventories_async(request_type=dict) - - -def test_add_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.AddLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.add_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_add_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_add_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), - '__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.add_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product='product_value', - ) - - -@pytest.mark.parametrize("request_type", [ - product_service.RemoveLocalInventoriesRequest, - dict, -]) -def test_remove_local_inventories(request_type, transport: str = 'grpc'): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_remove_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - -@pytest.mark.asyncio -async def test_remove_local_inventories_async(transport: str = 'grpc_asyncio', request_type=product_service.RemoveLocalInventoriesRequest): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_remove_local_inventories_async_from_dict(): - await test_remove_local_inventories_async(request_type=dict) - - -def test_remove_local_inventories_field_headers(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_local_inventories_field_headers_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = product_service.RemoveLocalInventoriesRequest() - - request.product = 'product_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'product=product_value', - ) in kw['metadata'] - - -def test_remove_local_inventories_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - - -def test_remove_local_inventories_flattened_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), - '__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.remove_local_inventories( - product='product_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].product - mock_val = 'product_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_local_inventories_flattened_error_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product='product_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProductServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ProductServiceClient.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 = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProductServiceGrpcTransport, - ) - -def test_product_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_product_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.product_service.transports.ProductServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProductServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_product', - 'get_product', - 'list_products', - 'update_product', - 'delete_product', - 'import_products', - 'set_inventory', - 'add_fulfillment_places', - 'remove_fulfillment_places', - 'add_local_inventories', - 'remove_local_inventories', - ) - 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_product_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.retail_v2beta.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport( - 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_product_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.retail_v2beta.services.product_service.transports.ProductServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductServiceTransport() - adc.assert_called_once() - - -def test_product_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) - ProductServiceClient() - 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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - ], -) -def test_product_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.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - ], -) -def test_product_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.ProductServiceGrpcTransport, grpc_helpers), - (transports.ProductServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_product_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_no_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_product_service_host_with_port(transport_name): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_product_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcTransport( - 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_product_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductServiceGrpcAsyncIOTransport( - 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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport]) -def test_product_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_product_service_grpc_lro_client(): - client = ProductServiceClient( - 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_product_service_grpc_lro_async_client(): - client = ProductServiceAsyncClient( - 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" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = ProductServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = ProductServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = ProductServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = ProductServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProductServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ProductServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProductServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ProductServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProductServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ProductServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ProductServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ProductServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ProductServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ProductServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProductServiceClient.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.ProductServiceTransport, '_prep_wrapped_messages') as prep: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProductServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ProductServiceClient.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 = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ProductServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ProductServiceClient( - 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", [ - (ProductServiceClient, transports.ProductServiceGrpcTransport), - (ProductServiceAsyncClient, transports.ProductServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py deleted file mode 100644 index 3ba459cc..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_search_service.py +++ /dev/null @@ -1,1546 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.search_service import SearchServiceAsyncClient -from google.cloud.retail_v2beta.services.search_service import SearchServiceClient -from google.cloud.retail_v2beta.services.search_service import pagers -from google.cloud.retail_v2beta.services.search_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SearchServiceClient._get_default_mtls_endpoint(None) is None - assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SearchServiceGrpcTransport, "grpc"), - (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), -]) -def test_search_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_search_service_client_get_transport_class(): - transport = SearchServiceClient.get_transport_class() - available_transports = [ - transports.SearchServiceGrpcTransport, - ] - assert transport in available_transports - - transport = SearchServiceClient.get_transport_class("grpc") - assert transport == transports.SearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_search_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SearchServiceClient, SearchServiceAsyncClient -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_search_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SearchServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - search_service.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( - total_size=1086, - corrected_query='corrected_query_value', - attribution_token='attribution_token_value', - next_page_token='next_page_token_value', - redirect_uri='redirect_uri_value', - applied_controls=['applied_controls_value'], - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.total_size == 1086 - assert response.corrected_query == 'corrected_query_value' - assert response.attribution_token == 'attribution_token_value' - assert response.next_page_token == 'next_page_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.applied_controls == ['applied_controls_value'] - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - - -def test_search_field_headers(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = search_service.SearchResponse() - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_field_headers_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.placement = 'placement_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'placement=placement_value', - ) in kw['metadata'] - - -def test_search_pager(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('placement', ''), - )), - ) - pager = client.search(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_async_pager(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, - ) - -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_search_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_search_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport() - adc.assert_called_once() - - -def test_search_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SearchServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SearchServiceGrpcTransport, grpc_helpers), - (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_search_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_no_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_search_service_host_with_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_branch_path(): - project = "squid" - location = "clam" - catalog = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}".format(project=project, location=location, catalog=catalog, branch=branch, ) - actual = SearchServiceClient.branch_path(project, location, catalog, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "branch": "mussel", - } - path = SearchServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_branch_path(path) - assert expected == actual - -def test_product_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - branch = "abalone" - product = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = SearchServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "branch": "oyster", - "product": "nudibranch", - } - path = SearchServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py deleted file mode 100644 index 6471cb0b..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_serving_config_service.py +++ /dev/null @@ -1,3329 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.serving_config_service import ServingConfigServiceAsyncClient -from google.cloud.retail_v2beta.services.serving_config_service import ServingConfigServiceClient -from google.cloud.retail_v2beta.services.serving_config_service import pagers -from google.cloud.retail_v2beta.services.serving_config_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import search_service -from google.cloud.retail_v2beta.types import serving_config -from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config -from google.cloud.retail_v2beta.types import serving_config_service -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ServingConfigServiceClient._get_default_mtls_endpoint(None) is None - assert ServingConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ServingConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServingConfigServiceClient, "grpc"), - (ServingConfigServiceAsyncClient, "grpc_asyncio"), -]) -def test_serving_config_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 == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ServingConfigServiceGrpcTransport, "grpc"), - (transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_serving_config_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", [ - (ServingConfigServiceClient, "grpc"), - (ServingConfigServiceAsyncClient, "grpc_asyncio"), -]) -def test_serving_config_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 == ( - 'retail.googleapis.com:443' - ) - - -def test_serving_config_service_client_get_transport_class(): - transport = ServingConfigServiceClient.get_transport_class() - available_transports = [ - transports.ServingConfigServiceGrpcTransport, - ] - assert transport in available_transports - - transport = ServingConfigServiceClient.get_transport_class("grpc") - assert transport == transports.ServingConfigServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -def test_serving_config_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(ServingConfigServiceClient, '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(ServingConfigServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "true"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", "false"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_serving_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ServingConfigServiceClient, ServingConfigServiceAsyncClient -]) -@mock.patch.object(ServingConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceClient)) -@mock.patch.object(ServingConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServingConfigServiceAsyncClient)) -def test_serving_config_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc"), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_serving_config_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_serving_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_serving_config_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ServingConfigServiceClient( - 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", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport, "grpc", grpc_helpers), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_serving_config_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.CreateServingConfigRequest, - dict, -]) -def test_create_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_create_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.create_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - -@pytest.mark.asyncio -async def test_create_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.CreateServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_create_serving_config_async_from_dict(): - await test_create_serving_config_async(request_type=dict) - - -def test_create_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.CreateServingConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.CreateServingConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_serving_config( - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].serving_config - mock_val = gcr_serving_config.ServingConfig(name='name_value') - assert arg == mock_val - arg = args[0].serving_config_id - mock_val = 'serving_config_id_value' - assert arg == mock_val - - -def test_create_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.CreateServingConfigRequest(), - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_serving_config( - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].serving_config - mock_val = gcr_serving_config.ServingConfig(name='name_value') - assert arg == mock_val - arg = args[0].serving_config_id - mock_val = 'serving_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.CreateServingConfigRequest(), - parent='parent_value', - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - serving_config_id='serving_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.DeleteServingConfigRequest, - dict, -]) -def test_delete_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.delete_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - -@pytest.mark.asyncio -async def test_delete_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.DeleteServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_serving_config_async_from_dict(): - await test_delete_serving_config_async(request_type=dict) - - -def test_delete_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.DeleteServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__call__') as call: - call.return_value = None - client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.DeleteServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__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_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.DeleteServingConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), - '__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_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.DeleteServingConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.UpdateServingConfigRequest, - dict, -]) -def test_update_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_update_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.update_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - -@pytest.mark.asyncio -async def test_update_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.UpdateServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_update_serving_config_async_from_dict(): - await test_update_serving_config_async(request_type=dict) - - -def test_update_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.UpdateServingConfigRequest() - - request.serving_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.UpdateServingConfigRequest() - - request.serving_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.update_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config.name=name_value', - ) in kw['metadata'] - - -def test_update_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_serving_config( - serving_config=gcr_serving_config.ServingConfig(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].serving_config - mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_serving_config( - serving_config=gcr_serving_config.ServingConfig(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].serving_config - mock_val = gcr_serving_config.ServingConfig(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_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.GetServingConfigRequest, - dict, -]) -def test_get_serving_config(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_get_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_config), - '__call__') as call: - client.get_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - -@pytest.mark.asyncio -async def test_get_serving_config_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.GetServingConfigRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_get_serving_config_async_from_dict(): - await test_get_serving_config_async(request_type=dict) - - -def test_get_serving_config_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.GetServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - call.return_value = serving_config.ServingConfig() - client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_serving_config_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.GetServingConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) - await client.get_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_serving_config_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_serving_config_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_config( - serving_config_service.GetServingConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_serving_config_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_serving_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_serving_config_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_config( - serving_config_service.GetServingConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.ListServingConfigsRequest, - dict, -]) -def test_list_serving_configs(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_serving_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=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_serving_configs), - '__call__') as call: - client.list_serving_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - -@pytest.mark.asyncio -async def test_list_serving_configs_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.ListServingConfigsRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_serving_configs_async_from_dict(): - await test_list_serving_configs_async(request_type=dict) - - -def test_list_serving_configs_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.ListServingConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - call.return_value = serving_config_service.ListServingConfigsResponse() - client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_serving_configs_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.ListServingConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) - await client.list_serving_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_serving_configs_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_serving_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_serving_configs_flattened_error(): - client = ServingConfigServiceClient( - credentials=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_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_serving_configs_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = serving_config_service.ListServingConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(serving_config_service.ListServingConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_serving_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_serving_configs_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_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_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent='parent_value', - ) - - -def test_list_serving_configs_pager(transport_name: str = "grpc"): - client = ServingConfigServiceClient( - 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_serving_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_serving_configs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, serving_config.ServingConfig) - for i in results) -def test_list_serving_configs_pages(transport_name: str = "grpc"): - client = ServingConfigServiceClient( - 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_serving_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_serving_configs(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_serving_configs_async_pager(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_serving_configs(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, serving_config.ServingConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_serving_configs_async_pages(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token='abc', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token='def', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token='ghi', - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_serving_configs(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - serving_config_service.AddControlRequest, - dict, -]) -def test_add_control(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_add_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - client.add_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - -@pytest.mark.asyncio -async def test_add_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.AddControlRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_add_control_async_from_dict(): - await test_add_control_async(request_type=dict) - - -def test_add_control_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.AddControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_add_control_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.AddControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.add_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_add_control_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.add_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - - -def test_add_control_flattened_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_control( - serving_config_service.AddControlRequest(), - serving_config='serving_config_value', - ) - -@pytest.mark.asyncio -async def test_add_control_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.add_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_add_control_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.add_control( - serving_config_service.AddControlRequest(), - serving_config='serving_config_value', - ) - - -@pytest.mark.parametrize("request_type", [ - serving_config_service.RemoveControlRequest, - dict, -]) -def test_remove_control(request_type, transport: str = 'grpc'): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - response = client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_remove_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - client.remove_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - -@pytest.mark.asyncio -async def test_remove_control_async(transport: str = 'grpc_asyncio', request_type=serving_config_service.RemoveControlRequest): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig( - name='name_value', - display_name='display_name_value', - model_id='model_id_value', - price_reranking_level='price_reranking_level_value', - facet_control_ids=['facet_control_ids_value'], - boost_control_ids=['boost_control_ids_value'], - filter_control_ids=['filter_control_ids_value'], - redirect_control_ids=['redirect_control_ids_value'], - twoway_synonyms_control_ids=['twoway_synonyms_control_ids_value'], - oneway_synonyms_control_ids=['oneway_synonyms_control_ids_value'], - do_not_associate_control_ids=['do_not_associate_control_ids_value'], - replacement_control_ids=['replacement_control_ids_value'], - ignore_control_ids=['ignore_control_ids_value'], - diversity_level='diversity_level_value', - enable_category_filter_level='enable_category_filter_level_value', - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - )) - response = await client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.model_id == 'model_id_value' - assert response.price_reranking_level == 'price_reranking_level_value' - assert response.facet_control_ids == ['facet_control_ids_value'] - assert response.boost_control_ids == ['boost_control_ids_value'] - assert response.filter_control_ids == ['filter_control_ids_value'] - assert response.redirect_control_ids == ['redirect_control_ids_value'] - assert response.twoway_synonyms_control_ids == ['twoway_synonyms_control_ids_value'] - assert response.oneway_synonyms_control_ids == ['oneway_synonyms_control_ids_value'] - assert response.do_not_associate_control_ids == ['do_not_associate_control_ids_value'] - assert response.replacement_control_ids == ['replacement_control_ids_value'] - assert response.ignore_control_ids == ['ignore_control_ids_value'] - assert response.diversity_level == 'diversity_level_value' - assert response.enable_category_filter_level == 'enable_category_filter_level_value' - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -@pytest.mark.asyncio -async def test_remove_control_async_from_dict(): - await test_remove_control_async(request_type=dict) - - -def test_remove_control_field_headers(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.RemoveControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - call.return_value = gcr_serving_config.ServingConfig() - client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_remove_control_field_headers_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = serving_config_service.RemoveControlRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - await client.remove_control(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_remove_control_flattened(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.remove_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - - -def test_remove_control_flattened_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config='serving_config_value', - ) - -@pytest.mark.asyncio -async def test_remove_control_flattened_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_control), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_serving_config.ServingConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_serving_config.ServingConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.remove_control( - serving_config='serving_config_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].serving_config - mock_val = 'serving_config_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_remove_control_flattened_error_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config='serving_config_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ServingConfigServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = ServingConfigServiceClient.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 = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ServingConfigServiceGrpcTransport, - ) - -def test_serving_config_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ServingConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_serving_config_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ServingConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_serving_config', - 'delete_serving_config', - 'update_serving_config', - 'get_serving_config', - 'list_serving_configs', - 'add_control', - 'remove_control', - ) - 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_serving_config_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.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServingConfigServiceTransport( - 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_serving_config_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.retail_v2beta.services.serving_config_service.transports.ServingConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServingConfigServiceTransport() - adc.assert_called_once() - - -def test_serving_config_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) - ServingConfigServiceClient() - 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.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - ], -) -def test_serving_config_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.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - ], -) -def test_serving_config_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.ServingConfigServiceGrpcTransport, grpc_helpers), - (transports.ServingConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_serving_config_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( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_serving_config_service_host_no_port(transport_name): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_serving_config_service_host_with_port(transport_name): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_serving_config_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServingConfigServiceGrpcTransport( - 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_serving_config_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( - 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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport]) -def test_serving_config_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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = ServingConfigServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = ServingConfigServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - serving_config = "nautilus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}".format(project=project, location=location, catalog=catalog, serving_config=serving_config, ) - actual = ServingConfigServiceClient.serving_config_path(project, location, catalog, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "scallop", - "location": "abalone", - "catalog": "squid", - "serving_config": "clam", - } - path = ServingConfigServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ServingConfigServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ServingConfigServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ServingConfigServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ServingConfigServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ServingConfigServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ServingConfigServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ServingConfigServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ServingConfigServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.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 = ServingConfigServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ServingConfigServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ServingConfigServiceClient.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.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ServingConfigServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ServingConfigServiceClient.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 = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ServingConfigServiceClient( - 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 = [ - 'grpc', - ] - for transport in transports: - client = ServingConfigServiceClient( - 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", [ - (ServingConfigServiceClient, transports.ServingConfigServiceGrpcTransport), - (ServingConfigServiceAsyncClient, transports.ServingConfigServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py b/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py deleted file mode 100644 index cf30324f..00000000 --- a/owl-bot-staging/v2beta/tests/unit/gapic/retail_v2beta/test_user_event_service.py +++ /dev/null @@ -1,2038 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.retail_v2beta.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.retail_v2beta.services.user_event_service import UserEventServiceClient -from google.cloud.retail_v2beta.services.user_event_service import transports -from google.cloud.retail_v2beta.types import common -from google.cloud.retail_v2beta.types import import_config -from google.cloud.retail_v2beta.types import product -from google.cloud.retail_v2beta.types import promotion -from google.cloud.retail_v2beta.types import purge_config -from google.cloud.retail_v2beta.types import user_event -from google.cloud.retail_v2beta.types import user_event_service -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), -]) -def test_user_event_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, UserEventServiceAsyncClient -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - ) - response = client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( - event_type='event_type_value', - visitor_id='visitor_id_value', - session_id='session_id_value', - experiment_ids=['experiment_ids_value'], - attribution_token='attribution_token_value', - cart_id='cart_id_value', - search_query='search_query_value', - filter='filter_value', - order_by='order_by_value', - offset=647, - page_categories=['page_categories_value'], - uri='uri_value', - referrer_uri='referrer_uri_value', - page_view_id='page_view_id_value', - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.visitor_id == 'visitor_id_value' - assert response.session_id == 'session_id_value' - assert response.experiment_ids == ['experiment_ids_value'] - assert response.attribution_token == 'attribution_token_value' - assert response.cart_id == 'cart_id_value' - assert response.search_query == 'search_query_value' - assert response.filter == 'filter_value' - assert response.order_by == 'order_by_value' - assert response.offset == 647 - assert response.page_categories == ['page_categories_value'] - assert response.uri == 'uri_value' - assert response.referrer_uri == 'referrer_uri_value' - assert response.page_view_id == 'page_view_id_value' - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = user_event.UserEvent() - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) - await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeUserEventsRequest, - dict, -]) -def test_purge_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - -@pytest.mark.asyncio -async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_user_events_async_from_dict(): - await test_purge_user_events_async(request_type=dict) - - -def test_purge_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_purge_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.RejoinUserEventsRequest, - dict, -]) -def test_rejoin_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_rejoin_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - -@pytest.mark.asyncio -async def test_rejoin_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.RejoinUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_rejoin_user_events_async_from_dict(): - await test_rejoin_user_events_async(request_type=dict) - - -def test_rejoin_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_rejoin_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.RejoinUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.rejoin_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, -]) -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", -]) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'purge_user_events', - 'import_user_events', - 'rejoin_user_events', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_user_event_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_user_event_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.retail_v2beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -def test_user_event_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - UserEventServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "retail.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="retail.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_no_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_user_event_service_host_with_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='retail.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'retail.googleapis.com:8000' - ) - -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = UserEventServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = UserEventServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_product_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - branch = "nautilus" - product = "scallop" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}".format(project=project, location=location, catalog=catalog, branch=branch, product=product, ) - actual = UserEventServiceClient.product_path(project, location, catalog, branch, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "project": "abalone", - "location": "squid", - "catalog": "clam", - "branch": "whelk", - "product": "octopus", - } - path = UserEventServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/tests/unit/gapic/retail_v2/test_catalog_service.py b/tests/unit/gapic/retail_v2/test_catalog_service.py index 5f48de87..520895a5 100644 --- a/tests/unit/gapic/retail_v2/test_catalog_service.py +++ b/tests/unit/gapic/retail_v2/test_catalog_service.py @@ -2058,7 +2058,6 @@ def test_catalog_service_transport_auth_adc(transport_class): [ transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport, - transports.CatalogServiceRestTransport, ], ) def test_catalog_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2/test_completion_service.py b/tests/unit/gapic/retail_v2/test_completion_service.py index b3eff55d..b2b59a22 100644 --- a/tests/unit/gapic/retail_v2/test_completion_service.py +++ b/tests/unit/gapic/retail_v2/test_completion_service.py @@ -1240,7 +1240,6 @@ def test_completion_service_transport_auth_adc(transport_class): [ transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, ], ) def test_completion_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2/test_prediction_service.py b/tests/unit/gapic/retail_v2/test_prediction_service.py index 7ee15865..6b361632 100644 --- a/tests/unit/gapic/retail_v2/test_prediction_service.py +++ b/tests/unit/gapic/retail_v2/test_prediction_service.py @@ -1084,7 +1084,6 @@ def test_prediction_service_transport_auth_adc(transport_class): [ transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport, - transports.PredictionServiceRestTransport, ], ) def test_prediction_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2/test_product_service.py b/tests/unit/gapic/retail_v2/test_product_service.py index c982d5ae..332e890c 100644 --- a/tests/unit/gapic/retail_v2/test_product_service.py +++ b/tests/unit/gapic/retail_v2/test_product_service.py @@ -3857,7 +3857,6 @@ def test_product_service_transport_auth_adc(transport_class): [ transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport, - transports.ProductServiceRestTransport, ], ) def test_product_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2/test_search_service.py b/tests/unit/gapic/retail_v2/test_search_service.py index f1af1c5a..6248d242 100644 --- a/tests/unit/gapic/retail_v2/test_search_service.py +++ b/tests/unit/gapic/retail_v2/test_search_service.py @@ -1261,7 +1261,6 @@ def test_search_service_transport_auth_adc(transport_class): [ transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport, - transports.SearchServiceRestTransport, ], ) def test_search_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2/test_user_event_service.py b/tests/unit/gapic/retail_v2/test_user_event_service.py index be8770cc..2de46fb5 100644 --- a/tests/unit/gapic/retail_v2/test_user_event_service.py +++ b/tests/unit/gapic/retail_v2/test_user_event_service.py @@ -1782,7 +1782,6 @@ def test_user_event_service_transport_auth_adc(transport_class): [ transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, ], ) def test_user_event_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2alpha/test_catalog_service.py b/tests/unit/gapic/retail_v2alpha/test_catalog_service.py index 1a4a2b89..4d041136 100644 --- a/tests/unit/gapic/retail_v2alpha/test_catalog_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_catalog_service.py @@ -3699,7 +3699,6 @@ def test_catalog_service_transport_auth_adc(transport_class): [ transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport, - transports.CatalogServiceRestTransport, ], ) def test_catalog_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2alpha/test_completion_service.py b/tests/unit/gapic/retail_v2alpha/test_completion_service.py index 0cea0e6e..9ec5012a 100644 --- a/tests/unit/gapic/retail_v2alpha/test_completion_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_completion_service.py @@ -1240,7 +1240,6 @@ def test_completion_service_transport_auth_adc(transport_class): [ transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, ], ) def test_completion_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2alpha/test_control_service.py b/tests/unit/gapic/retail_v2alpha/test_control_service.py index e42c6ba3..f4044454 100644 --- a/tests/unit/gapic/retail_v2alpha/test_control_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_control_service.py @@ -2437,7 +2437,6 @@ def test_control_service_transport_auth_adc(transport_class): [ transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport, - transports.ControlServiceRestTransport, ], ) def test_control_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2alpha/test_prediction_service.py b/tests/unit/gapic/retail_v2alpha/test_prediction_service.py index 5251b25a..e826f0bf 100644 --- a/tests/unit/gapic/retail_v2alpha/test_prediction_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_prediction_service.py @@ -1084,7 +1084,6 @@ def test_prediction_service_transport_auth_adc(transport_class): [ transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport, - transports.PredictionServiceRestTransport, ], ) def test_prediction_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2alpha/test_product_service.py b/tests/unit/gapic/retail_v2alpha/test_product_service.py index 7db42d58..dee97e66 100644 --- a/tests/unit/gapic/retail_v2alpha/test_product_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_product_service.py @@ -4006,7 +4006,6 @@ def test_product_service_transport_auth_adc(transport_class): [ transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport, - transports.ProductServiceRestTransport, ], ) def test_product_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2alpha/test_search_service.py b/tests/unit/gapic/retail_v2alpha/test_search_service.py index ec18ac32..d6e52c44 100644 --- a/tests/unit/gapic/retail_v2alpha/test_search_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_search_service.py @@ -1261,7 +1261,6 @@ def test_search_service_transport_auth_adc(transport_class): [ transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport, - transports.SearchServiceRestTransport, ], ) def test_search_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py b/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py index 2077185f..9b14b428 100644 --- a/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py @@ -3171,7 +3171,6 @@ def test_serving_config_service_transport_auth_adc(transport_class): [ transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport, - transports.ServingConfigServiceRestTransport, ], ) def test_serving_config_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2alpha/test_user_event_service.py b/tests/unit/gapic/retail_v2alpha/test_user_event_service.py index c278649c..9a567eaa 100644 --- a/tests/unit/gapic/retail_v2alpha/test_user_event_service.py +++ b/tests/unit/gapic/retail_v2alpha/test_user_event_service.py @@ -1782,7 +1782,6 @@ def test_user_event_service_transport_auth_adc(transport_class): [ transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, ], ) def test_user_event_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2beta/test_catalog_service.py b/tests/unit/gapic/retail_v2beta/test_catalog_service.py index b165b826..216eebf6 100644 --- a/tests/unit/gapic/retail_v2beta/test_catalog_service.py +++ b/tests/unit/gapic/retail_v2beta/test_catalog_service.py @@ -3699,7 +3699,6 @@ def test_catalog_service_transport_auth_adc(transport_class): [ transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport, - transports.CatalogServiceRestTransport, ], ) def test_catalog_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2beta/test_completion_service.py b/tests/unit/gapic/retail_v2beta/test_completion_service.py index 77ca8c12..be454418 100644 --- a/tests/unit/gapic/retail_v2beta/test_completion_service.py +++ b/tests/unit/gapic/retail_v2beta/test_completion_service.py @@ -1240,7 +1240,6 @@ def test_completion_service_transport_auth_adc(transport_class): [ transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, ], ) def test_completion_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2beta/test_control_service.py b/tests/unit/gapic/retail_v2beta/test_control_service.py index b1aed8ef..38a5a4b5 100644 --- a/tests/unit/gapic/retail_v2beta/test_control_service.py +++ b/tests/unit/gapic/retail_v2beta/test_control_service.py @@ -2401,7 +2401,6 @@ def test_control_service_transport_auth_adc(transport_class): [ transports.ControlServiceGrpcTransport, transports.ControlServiceGrpcAsyncIOTransport, - transports.ControlServiceRestTransport, ], ) def test_control_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2beta/test_prediction_service.py b/tests/unit/gapic/retail_v2beta/test_prediction_service.py index b1e0f4c5..4d3004a7 100644 --- a/tests/unit/gapic/retail_v2beta/test_prediction_service.py +++ b/tests/unit/gapic/retail_v2beta/test_prediction_service.py @@ -1084,7 +1084,6 @@ def test_prediction_service_transport_auth_adc(transport_class): [ transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport, - transports.PredictionServiceRestTransport, ], ) def test_prediction_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2beta/test_product_service.py b/tests/unit/gapic/retail_v2beta/test_product_service.py index ac20808c..53062d95 100644 --- a/tests/unit/gapic/retail_v2beta/test_product_service.py +++ b/tests/unit/gapic/retail_v2beta/test_product_service.py @@ -3857,7 +3857,6 @@ def test_product_service_transport_auth_adc(transport_class): [ transports.ProductServiceGrpcTransport, transports.ProductServiceGrpcAsyncIOTransport, - transports.ProductServiceRestTransport, ], ) def test_product_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2beta/test_search_service.py b/tests/unit/gapic/retail_v2beta/test_search_service.py index fbf14b45..694794d0 100644 --- a/tests/unit/gapic/retail_v2beta/test_search_service.py +++ b/tests/unit/gapic/retail_v2beta/test_search_service.py @@ -1261,7 +1261,6 @@ def test_search_service_transport_auth_adc(transport_class): [ transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport, - transports.SearchServiceRestTransport, ], ) def test_search_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2beta/test_serving_config_service.py b/tests/unit/gapic/retail_v2beta/test_serving_config_service.py index 70bfd6ea..f2d68dbe 100644 --- a/tests/unit/gapic/retail_v2beta/test_serving_config_service.py +++ b/tests/unit/gapic/retail_v2beta/test_serving_config_service.py @@ -3171,7 +3171,6 @@ def test_serving_config_service_transport_auth_adc(transport_class): [ transports.ServingConfigServiceGrpcTransport, transports.ServingConfigServiceGrpcAsyncIOTransport, - transports.ServingConfigServiceRestTransport, ], ) def test_serving_config_service_transport_auth_gdch_credentials(transport_class): diff --git a/tests/unit/gapic/retail_v2beta/test_user_event_service.py b/tests/unit/gapic/retail_v2beta/test_user_event_service.py index 49db13cf..030afbc4 100644 --- a/tests/unit/gapic/retail_v2beta/test_user_event_service.py +++ b/tests/unit/gapic/retail_v2beta/test_user_event_service.py @@ -1782,7 +1782,6 @@ def test_user_event_service_transport_auth_adc(transport_class): [ transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, ], ) def test_user_event_service_transport_auth_gdch_credentials(transport_class): From 7692f592aa9b481a4d67bccec65da3ae8f6d0be1 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 7 Jul 2022 16:22:41 +0000 Subject: [PATCH 07/11] fix(deps): require google-api-core 2.8.0 --- setup.py | 5 +---- testing/constraints-3.6.txt | 24 ------------------------ 2 files changed, 1 insertion(+), 28 deletions(-) delete mode 100644 testing/constraints-3.6.txt diff --git a/setup.py b/setup.py index 665a92f7..f3823f3e 100644 --- a/setup.py +++ b/setup.py @@ -42,10 +42,7 @@ platforms="Posix; MacOS X; Windows", include_package_data=True, install_requires=( - # NOTE: Maintainers, please do not require google-api-core>=2.x.x - # Until this issue is closed - # https://github.com/googleapis/google-cloud-python/issues/10566 - "google-api-core[grpc] >= 1.31.5, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0", + "google-api-core[grpc] >= 2.8.0, <3.0.0dev", "proto-plus >= 1.15.0, <2.0.0dev", "protobuf >= 3.19.0, <4.0.0dev", ), diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt deleted file mode 100644 index e96de949..00000000 --- a/testing/constraints-3.6.txt +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List *all* library dependencies and extras in this file. -# Pin the version to the lower bound. -# -# e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", -# Then this file should have foo==1.14.0 -google-api-core==1.31.5 -proto-plus==1.15.0 -protobuf==3.19.0 From d41c1517181565a1cde684f5c4ea5fc62dec317c Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 12 Jul 2022 14:14:03 +0000 Subject: [PATCH 08/11] update constraints --- testing/constraints-3.7.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index e96de949..f74740e6 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -19,6 +19,6 @@ # # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 -google-api-core==1.31.5 +google-api-core==2.8.0 proto-plus==1.15.0 protobuf==3.19.0 From eadf8e1fe31ea59cfb464ed18dd7074a849c2437 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sat, 16 Jul 2022 12:59:21 +0000 Subject: [PATCH 09/11] fix(deps): require google-api-core>=1.32.0,>=2.8.0 --- setup.py | 2 +- testing/constraints-3.7.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 513eaeae..74007833 100644 --- a/setup.py +++ b/setup.py @@ -42,7 +42,7 @@ platforms="Posix; MacOS X; Windows", include_package_data=True, install_requires=( - "google-api-core[grpc] >= 2.8.0, <3.0.0dev", + "google-api-core[grpc] >= 1.32.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", "proto-plus >= 1.15.0, <2.0.0dev", "protobuf >= 3.19.0, <4.0.0dev", ), diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index f74740e6..b450739b 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -19,6 +19,6 @@ # # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 -google-api-core==2.8.0 +google-api-core==1.32.0 proto-plus==1.15.0 protobuf==3.19.0 From 7121a50990d7ce8e917d8c3f9e9194daf8bab6cf Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Sat, 16 Jul 2022 13:02:11 +0000 Subject: [PATCH 10/11] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- README.rst | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/README.rst b/README.rst index ecaff46c..a2543366 100644 --- a/README.rst +++ b/README.rst @@ -55,22 +55,18 @@ Code samples and snippets live in the `samples/` folder. Supported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^ -Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of +Our client libraries are compatible with all current [active](https://devguide.python.org/devcycle/#in-development-main-branch) and [maintenance](https://devguide.python.org/devcycle/#maintenance-branches) versions of Python. Python >= 3.7 -.. _active: https://devguide.python.org/devcycle/#in-development-main-branch -.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches - Unsupported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Python <= 3.6 -If you are using an `end-of-life`_ +If you are using an [end-of-life](https://devguide.python.org/devcycle/#end-of-life-branches) version of Python, we recommend that you update as soon as possible to an actively supported version. -.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches Mac/Linux ^^^^^^^^^ From d866b993e507fe606673f321c1cbc931935e4281 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Sat, 16 Jul 2022 13:04:45 +0000 Subject: [PATCH 11/11] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- README.rst | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index a2543366..ecaff46c 100644 --- a/README.rst +++ b/README.rst @@ -55,18 +55,22 @@ Code samples and snippets live in the `samples/` folder. Supported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^ -Our client libraries are compatible with all current [active](https://devguide.python.org/devcycle/#in-development-main-branch) and [maintenance](https://devguide.python.org/devcycle/#maintenance-branches) versions of +Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of Python. Python >= 3.7 +.. _active: https://devguide.python.org/devcycle/#in-development-main-branch +.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches + Unsupported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Python <= 3.6 -If you are using an [end-of-life](https://devguide.python.org/devcycle/#end-of-life-branches) +If you are using an `end-of-life`_ version of Python, we recommend that you update as soon as possible to an actively supported version. +.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches Mac/Linux ^^^^^^^^^